token.c 54.5 KB
Newer Older
1 2 3 4 5
/*
 * Tokens
 *
 * Copyright (C) 1998 Alexandre Julliard
 * Copyright (C) 2003 Mike McCormack
6
 * Copyright (C) 2005 Robert Shearman
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 22 23 24 25 26 27
 */

#include "config.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
28
#include <stdarg.h>
29
#include <unistd.h>
30

31 32
#include "ntstatus.h"
#define WIN32_NO_STATUS
33
#include "windef.h"
34
#include "winternl.h"
35 36 37 38 39

#include "handle.h"
#include "thread.h"
#include "process.h"
#include "request.h"
40 41
#include "security.h"

42 43
#include "wine/unicode.h"

44 45
#define MAX_SUBAUTH_COUNT 1

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
const LUID SeIncreaseQuotaPrivilege        = {  5, 0 };
const LUID SeSecurityPrivilege             = {  8, 0 };
const LUID SeTakeOwnershipPrivilege        = {  9, 0 };
const LUID SeLoadDriverPrivilege           = { 10, 0 };
const LUID SeSystemProfilePrivilege        = { 11, 0 };
const LUID SeSystemtimePrivilege           = { 12, 0 };
const LUID SeProfileSingleProcessPrivilege = { 13, 0 };
const LUID SeIncreaseBasePriorityPrivilege = { 14, 0 };
const LUID SeCreatePagefilePrivilege       = { 15, 0 };
const LUID SeBackupPrivilege               = { 17, 0 };
const LUID SeRestorePrivilege              = { 18, 0 };
const LUID SeShutdownPrivilege             = { 19, 0 };
const LUID SeDebugPrivilege                = { 20, 0 };
const LUID SeSystemEnvironmentPrivilege    = { 22, 0 };
const LUID SeChangeNotifyPrivilege         = { 23, 0 };
const LUID SeRemoteShutdownPrivilege       = { 24, 0 };
const LUID SeUndockPrivilege               = { 25, 0 };
const LUID SeManageVolumePrivilege         = { 28, 0 };
const LUID SeImpersonatePrivilege          = { 29, 0 };
const LUID SeCreateGlobalPrivilege         = { 30, 0 };
66

67 68 69
static const SID world_sid = { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY }, { SECURITY_WORLD_RID } };
static const SID local_sid = { SID_REVISION, 1, { SECURITY_LOCAL_SID_AUTHORITY }, { SECURITY_LOCAL_RID } };
static const SID interactive_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_INTERACTIVE_RID } };
70
static const SID anonymous_logon_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_ANONYMOUS_LOGON_RID } };
71 72
static const SID authenticated_user_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_AUTHENTICATED_USER_RID } };
static const SID local_system_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_LOCAL_SYSTEM_RID } };
73
static const SID high_label_sid = { SID_REVISION, 1, { SECURITY_MANDATORY_LABEL_AUTHORITY }, { SECURITY_MANDATORY_HIGH_RID } };
74 75 76 77 78 79 80
static const struct /* same fields as struct SID */
{
    BYTE Revision;
    BYTE SubAuthorityCount;
    SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
    DWORD SubAuthority[5];
} local_user_sid = { SID_REVISION, 5, { SECURITY_NT_AUTHORITY }, { SECURITY_NT_NON_UNIQUE, 0, 0, 0, 1000 } };
81 82 83 84 85 86 87
static const struct /* same fields as struct SID */
{
    BYTE Revision;
    BYTE SubAuthorityCount;
    SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
    DWORD SubAuthority[2];
} builtin_admins_sid = { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS } };
88 89 90 91 92 93 94
static const struct /* same fields as struct SID */
{
    BYTE Revision;
    BYTE SubAuthorityCount;
    SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
    DWORD SubAuthority[2];
} builtin_users_sid = { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS } };
95

96
const PSID security_world_sid = (PSID)&world_sid;
97
static const PSID security_local_sid = (PSID)&local_sid;
98
static const PSID security_interactive_sid = (PSID)&interactive_sid;
99
static const PSID security_authenticated_user_sid = (PSID)&authenticated_user_sid;
100
const PSID security_local_system_sid = (PSID)&local_system_sid;
101
const PSID security_local_user_sid = (PSID)&local_user_sid;
102
const PSID security_builtin_admins_sid = (PSID)&builtin_admins_sid;
103
const PSID security_builtin_users_sid = (PSID)&builtin_users_sid;
104
const PSID security_high_label_sid = (PSID)&high_label_sid;
105

106
static luid_t prev_luid_value = { 1000, 0 };
107

108 109 110
struct token
{
    struct object  obj;             /* object header */
111 112
    luid_t         token_id;        /* system-unique id of token */
    luid_t         modified_id;     /* new id allocated every time token is modified */
113
    struct list    privileges;      /* privileges available to the token */
114
    struct list    groups;          /* groups that the user of this token belongs to (sid_and_attributes) */
115
    SID           *user;            /* SID of user this token represents */
116
    SID           *primary_group;   /* SID of user's primary group */
117
    unsigned       primary;         /* is this a primary or impersonation token? */
118
    ACL           *default_dacl;    /* the default DACL to assign to objects created by this user */
119
    TOKEN_SOURCE   source;          /* source of the token */
120
    int            impersonation_level; /* impersonation level this token is capable of if non-primary token */
121 122 123 124 125 126
};

struct privilege
{
    struct list entry;
    LUID        luid;
127 128
    unsigned    enabled  : 1; /* is the privilege currently enabled? */
    unsigned    def      : 1; /* is the privilege enabled by default? */
129 130
};

131
struct group
132 133
{
    struct list entry;
134 135 136 137 138 139 140
    unsigned    enabled  : 1; /* is the sid currently enabled? */
    unsigned    def      : 1; /* is the sid enabled by default? */
    unsigned    logon    : 1; /* is this a logon sid? */
    unsigned    mandatory: 1; /* is this sid always enabled? */
    unsigned    owner    : 1; /* can this sid be an owner of an object? */
    unsigned    resource : 1; /* is this a domain-local group? */
    unsigned    deny_only: 1; /* is this a sid that should be use for denying only? */
141 142 143
    SID         sid;
};

144
static void token_dump( struct object *obj, int verbose );
145
static unsigned int token_map_access( struct object *obj, unsigned int access );
146
static void token_destroy( struct object *obj );
147 148 149 150 151

static const struct object_ops token_ops =
{
    sizeof(struct token),      /* size */
    token_dump,                /* dump */
152
    no_get_type,               /* get_type */
153 154 155
    no_add_queue,              /* add_queue */
    NULL,                      /* remove_queue */
    NULL,                      /* signaled */
156 157
    NULL,                      /* satisfied */
    no_signal,                 /* signal */
158
    no_get_fd,                 /* get_fd */
159
    token_map_access,          /* map_access */
160 161
    default_get_sd,            /* get_sd */
    default_set_sd,            /* set_sd */
162
    no_lookup_name,            /* lookup_name */
163 164
    no_link_name,              /* link_name */
    NULL,                      /* unlink_name */
165
    no_open_file,              /* open_file */
166
    no_close_handle,           /* close_handle */
167
    token_destroy              /* destroy */
168 169 170 171 172 173
};


static void token_dump( struct object *obj, int verbose )
{
    fprintf( stderr, "Security token\n" );
174
    /* FIXME: dump token members */
175 176
}

177 178 179 180 181 182 183 184 185
static unsigned int token_map_access( struct object *obj, unsigned int access )
{
    if (access & GENERIC_READ)    access |= TOKEN_READ;
    if (access & GENERIC_WRITE)   access |= TOKEN_WRITE;
    if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
    if (access & GENERIC_ALL)     access |= TOKEN_ALL_ACCESS;
    return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
}

186 187 188 189 190
static SID *security_sid_alloc( const SID_IDENTIFIER_AUTHORITY *idauthority, int subauthcount, const unsigned int subauth[] )
{
    int i;
    SID *sid = mem_alloc( FIELD_OFFSET(SID, SubAuthority[subauthcount]) );
    if (!sid) return NULL;
191
    sid->Revision = SID_REVISION;
192 193 194 195 196 197 198
    sid->SubAuthorityCount = subauthcount;
    sid->IdentifierAuthority = *idauthority;
    for (i = 0; i < subauthcount; i++)
        sid->SubAuthority[i] = subauth[i];
    return sid;
}

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
void security_set_thread_token( struct thread *thread, obj_handle_t handle )
{
    if (!handle)
    {
        if (thread->token)
            release_object( thread->token );
        thread->token = NULL;
    }
    else
    {
        struct token *token = (struct token *)get_handle_obj( current->process,
                                                              handle,
                                                              TOKEN_IMPERSONATE,
                                                              &token_ops );
        if (token)
        {
            if (thread->token)
                release_object( thread->token );
            thread->token = token;
        }
    }
}

222 223 224 225
const SID *security_unix_uid_to_sid( uid_t uid )
{
    /* very simple mapping: either the current user or not the current user */
    if (uid == getuid())
226
        return (const SID *)&local_user_sid;
227 228 229 230
    else
        return &anonymous_logon_sid;
}

231
static int acl_is_valid( const ACL *acl, data_size_t size )
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
{
    ULONG i;
    const ACE_HEADER *ace;

    if (size < sizeof(ACL))
        return FALSE;

    size = min(size, MAX_ACL_LEN);

    size -= sizeof(ACL);

    ace = (const ACE_HEADER *)(acl + 1);
    for (i = 0; i < acl->AceCount; i++)
    {
        const SID *sid;
247
        data_size_t sid_size;
248 249 250 251 252 253 254 255 256 257

        if (size < sizeof(ACE_HEADER))
            return FALSE;
        if (size < ace->AceSize)
            return FALSE;
        size -= ace->AceSize;
        switch (ace->AceType)
        {
        case ACCESS_DENIED_ACE_TYPE:
            sid = (const SID *)&((const ACCESS_DENIED_ACE *)ace)->SidStart;
258
            sid_size = ace->AceSize - FIELD_OFFSET(ACCESS_DENIED_ACE, SidStart);
259 260 261
            break;
        case ACCESS_ALLOWED_ACE_TYPE:
            sid = (const SID *)&((const ACCESS_ALLOWED_ACE *)ace)->SidStart;
262
            sid_size = ace->AceSize - FIELD_OFFSET(ACCESS_ALLOWED_ACE, SidStart);
263 264 265
            break;
        case SYSTEM_AUDIT_ACE_TYPE:
            sid = (const SID *)&((const SYSTEM_AUDIT_ACE *)ace)->SidStart;
266
            sid_size = ace->AceSize - FIELD_OFFSET(SYSTEM_AUDIT_ACE, SidStart);
267 268 269
            break;
        case SYSTEM_ALARM_ACE_TYPE:
            sid = (const SID *)&((const SYSTEM_ALARM_ACE *)ace)->SidStart;
270
            sid_size = ace->AceSize - FIELD_OFFSET(SYSTEM_ALARM_ACE, SidStart);
271
            break;
272 273 274 275
        case SYSTEM_MANDATORY_LABEL_ACE_TYPE:
            sid = (const SID *)&((const SYSTEM_MANDATORY_LABEL_ACE *)ace)->SidStart;
            sid_size = ace->AceSize - FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart);
            break;
276 277 278
        default:
            return FALSE;
        }
279
        if (sid_size < FIELD_OFFSET(SID, SubAuthority[0]) || sid_size < security_sid_len( sid ))
280 281 282 283 284 285 286 287
            return FALSE;
        ace = ace_next( ace );
    }
    return TRUE;
}

/* checks whether all members of a security descriptor fit inside the size
 * of memory specified */
288
int sd_is_valid( const struct security_descriptor *sd, data_size_t size )
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
{
    size_t offset = sizeof(struct security_descriptor);
    const SID *group;
    const SID *owner;
    const ACL *sacl;
    const ACL *dacl;
    int dummy;

    if (size < offset)
        return FALSE;

    if ((sd->owner_len >= FIELD_OFFSET(SID, SubAuthority[255])) ||
        (offset + sd->owner_len > size))
        return FALSE;
    owner = sd_get_owner( sd );
    if (owner)
    {
306
        size_t needed_size = security_sid_len( owner );
307 308 309 310 311 312 313 314 315 316 317
        if ((sd->owner_len < sizeof(SID)) || (needed_size > sd->owner_len))
            return FALSE;
    }
    offset += sd->owner_len;

    if ((sd->group_len >= FIELD_OFFSET(SID, SubAuthority[255])) ||
        (offset + sd->group_len > size))
        return FALSE;
    group = sd_get_group( sd );
    if (group)
    {
318
        size_t needed_size = security_sid_len( group );
319
        if ((sd->group_len < sizeof(SID)) || (needed_size > sd->group_len))
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
            return FALSE;
    }
    offset += sd->group_len;

    if ((sd->sacl_len >= MAX_ACL_LEN) || (offset + sd->sacl_len > size))
        return FALSE;
    sacl = sd_get_sacl( sd, &dummy );
    if (sacl && !acl_is_valid( sacl, sd->sacl_len ))
        return FALSE;
    offset += sd->sacl_len;

    if ((sd->dacl_len >= MAX_ACL_LEN) || (offset + sd->dacl_len > size))
        return FALSE;
    dacl = sd_get_dacl( sd, &dummy );
    if (dacl && !acl_is_valid( dacl, sd->dacl_len ))
        return FALSE;
    offset += sd->dacl_len;

    return TRUE;
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
/* extract security labels from SACL */
ACL *extract_security_labels( const ACL *sacl )
{
    size_t size = sizeof(ACL);
    const ACE_HEADER *ace;
    ACE_HEADER *label_ace;
    unsigned int i, count = 0;
    ACL *label_acl;

    ace = (const ACE_HEADER *)(sacl + 1);
    for (i = 0; i < sacl->AceCount; i++, ace = ace_next( ace ))
    {
        if (ace->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
        {
            size += ace->AceSize;
            count++;
        }
    }

    label_acl = mem_alloc( size );
    if (!label_acl) return NULL;

    label_acl->AclRevision = sacl->AclRevision;
    label_acl->Sbz1 = 0;
    label_acl->AclSize = size;
    label_acl->AceCount = count;
    label_acl->Sbz2 = 0;
    label_ace = (ACE_HEADER *)(label_acl + 1);

    ace = (const ACE_HEADER *)(sacl + 1);
    for (i = 0; i < sacl->AceCount; i++, ace = ace_next( ace ))
    {
        if (ace->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
        {
            memcpy( label_ace, ace, ace->AceSize );
            label_ace = (ACE_HEADER *)ace_next( label_ace );
        }
    }
    return label_acl;
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
/* replace security labels in an existing SACL */
ACL *replace_security_labels( const ACL *old_sacl, const ACL *new_sacl )
{
    const ACE_HEADER *ace;
    ACE_HEADER *replaced_ace;
    size_t size = sizeof(ACL);
    unsigned int i, count = 0;
    BYTE revision = ACL_REVISION;
    ACL *replaced_acl;

    if (old_sacl)
    {
        revision = max( revision, old_sacl->AclRevision );
        ace = (const ACE_HEADER *)(old_sacl + 1);
        for (i = 0; i < old_sacl->AceCount; i++, ace = ace_next( ace ))
        {
            if (ace->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            size += ace->AceSize;
            count++;
        }
    }

    if (new_sacl)
    {
        revision = max( revision, new_sacl->AclRevision );
        ace = (const ACE_HEADER *)(new_sacl + 1);
        for (i = 0; i < new_sacl->AceCount; i++, ace = ace_next( ace ))
        {
            if (ace->AceType != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            size += ace->AceSize;
            count++;
        }
    }

    replaced_acl = mem_alloc( size );
    if (!replaced_acl) return NULL;

    replaced_acl->AclRevision = revision;
    replaced_acl->Sbz1 = 0;
    replaced_acl->AclSize = size;
    replaced_acl->AceCount = count;
    replaced_acl->Sbz2 = 0;
    replaced_ace = (ACE_HEADER *)(replaced_acl + 1);

    if (old_sacl)
    {
        ace = (const ACE_HEADER *)(old_sacl + 1);
        for (i = 0; i < old_sacl->AceCount; i++, ace = ace_next( ace ))
        {
            if (ace->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            memcpy( replaced_ace, ace, ace->AceSize );
            replaced_ace = (ACE_HEADER *)ace_next( replaced_ace );
        }
    }

    if (new_sacl)
    {
        ace = (const ACE_HEADER *)(new_sacl + 1);
        for (i = 0; i < new_sacl->AceCount; i++, ace = ace_next( ace ))
        {
            if (ace->AceType != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            memcpy( replaced_ace, ace, ace->AceSize );
            replaced_ace = (ACE_HEADER *)ace_next( replaced_ace );
        }
    }

    return replaced_acl;
}

451 452 453 454 455 456 457 458 459 460
/* maps from generic rights to specific rights as given by a mapping */
static inline void map_generic_mask(unsigned int *mask, const GENERIC_MAPPING *mapping)
{
    if (*mask & GENERIC_READ) *mask |= mapping->GenericRead;
    if (*mask & GENERIC_WRITE) *mask |= mapping->GenericWrite;
    if (*mask & GENERIC_EXECUTE) *mask |= mapping->GenericExecute;
    if (*mask & GENERIC_ALL) *mask |= mapping->GenericAll;
    *mask &= 0x0FFFFFFF;
}

461 462 463 464 465
static inline int is_equal_luid( const LUID *luid1, const LUID *luid2 )
{
    return (luid1->LowPart == luid2->LowPart && luid1->HighPart == luid2->HighPart);
}

466
static inline void allocate_luid( luid_t *luid )
467
{
468
    prev_luid_value.low_part++;
469 470 471
    *luid = prev_luid_value;
}

472 473
DECL_HANDLER( allocate_locally_unique_id )
{
474
    allocate_luid( &reply->luid );
475 476
}

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
static inline void luid_and_attr_from_privilege( LUID_AND_ATTRIBUTES *out, const struct privilege *in)
{
    out->Luid = in->luid;
    out->Attributes =
        (in->enabled ? SE_PRIVILEGE_ENABLED : 0) |
        (in->def ? SE_PRIVILEGE_ENABLED_BY_DEFAULT : 0);
}

static struct privilege *privilege_add( struct token *token, const LUID *luid, int enabled )
{
    struct privilege *privilege = mem_alloc( sizeof(*privilege) );
    if (privilege)
    {
        privilege->luid = *luid;
        privilege->def = privilege->enabled = (enabled != 0);
        list_add_tail( &token->privileges, &privilege->entry );
    }
    return privilege;
}

497
static inline void privilege_remove( struct privilege *privilege )
498 499 500 501 502 503 504 505 506 507 508 509 510
{
    list_remove( &privilege->entry );
    free( privilege );
}

static void token_destroy( struct object *obj )
{
    struct token* token;
    struct list *cursor, *cursor_next;

    assert( obj->ops == &token_ops );
    token = (struct token *)obj;

511 512
    free( token->user );

513 514 515 516 517
    LIST_FOR_EACH_SAFE( cursor, cursor_next, &token->privileges )
    {
        struct privilege *privilege = LIST_ENTRY( cursor, struct privilege, entry );
        privilege_remove( privilege );
    }
518 519 520

    LIST_FOR_EACH_SAFE( cursor, cursor_next, &token->groups )
    {
521
        struct group *group = LIST_ENTRY( cursor, struct group, entry );
522 523 524
        list_remove( &group->entry );
        free( group );
    }
525 526

    free( token->default_dacl );
527 528
}

529 530 531 532 533
/* creates a new token.
 *  groups may be NULL if group_count is 0.
 *  privs may be NULL if priv_count is 0.
 *  default_dacl may be NULL, indicating that all objects created by the user
 *   are unsecured.
534 535
 *  modified_id may be NULL, indicating that a new modified_id luid should be
 *   allocated.
536
 */
537
static struct token *create_token( unsigned primary, const SID *user,
538
                                   const SID_AND_ATTRIBUTES *groups, unsigned int group_count,
539
                                   const LUID_AND_ATTRIBUTES *privs, unsigned int priv_count,
540
                                   const ACL *default_dacl, TOKEN_SOURCE source,
541
                                   const luid_t *modified_id,
542
                                   int impersonation_level )
543 544
{
    struct token *token = alloc_object( &token_ops );
545 546
    if (token)
    {
547
        unsigned int i;
548

549 550 551 552 553
        allocate_luid( &token->token_id );
        if (modified_id)
            token->modified_id = *modified_id;
        else
            allocate_luid( &token->modified_id );
554
        list_init( &token->privileges );
555
        list_init( &token->groups );
556
        token->primary = primary;
557 558 559 560 561
        /* primary tokens don't have impersonation levels */
        if (primary)
            token->impersonation_level = -1;
        else
            token->impersonation_level = impersonation_level;
562
        token->default_dacl = NULL;
563
        token->primary_group = NULL;
564

565
        /* copy user */
566
        token->user = memdup( user, security_sid_len( user ));
567 568 569 570 571
        if (!token->user)
        {
            release_object( token );
            return NULL;
        }
572

573 574 575
        /* copy groups */
        for (i = 0; i < group_count; i++)
        {
576 577
            size_t size = FIELD_OFFSET( struct group, sid.SubAuthority[((const SID *)groups[i].Sid)->SubAuthorityCount] );
            struct group *group = mem_alloc( size );
578 579 580 581 582 583

            if (!group)
            {
                release_object( token );
                return NULL;
            }
584
            memcpy( &group->sid, groups[i].Sid, security_sid_len( groups[i].Sid ));
585 586
            group->enabled = TRUE;
            group->def = TRUE;
587 588 589
            group->logon = (groups[i].Attributes & SE_GROUP_LOGON_ID) != 0;
            group->mandatory = (groups[i].Attributes & SE_GROUP_MANDATORY) != 0;
            group->owner = (groups[i].Attributes & SE_GROUP_OWNER) != 0;
590 591 592
            group->resource = FALSE;
            group->deny_only = FALSE;
            list_add_tail( &token->groups, &group->entry );
593 594 595
            /* Use first owner capable group as an owner */
            if (!token->primary_group && group->owner)
                token->primary_group = &group->sid;
596
        }
597

598
        /* copy privileges */
599 600 601 602 603 604 605 606 607 608 609
        for (i = 0; i < priv_count; i++)
        {
            /* note: we don't check uniqueness: the caller must make sure
             * privs doesn't contain any duplicate luids */
            if (!privilege_add( token, &privs[i].Luid,
                                privs[i].Attributes & SE_PRIVILEGE_ENABLED ))
            {
                release_object( token );
                return NULL;
            }
        }
610 611 612 613 614 615 616 617 618 619

        if (default_dacl)
        {
            token->default_dacl = memdup( default_dacl, default_dacl->AclSize );
            if (!token->default_dacl)
            {
                release_object( token );
                return NULL;
            }
        }
620 621

        token->source = source;
622
    }
623 624 625
    return token;
}

626
struct token *token_duplicate( struct token *src_token, unsigned primary,
627
                               int impersonation_level, const struct security_descriptor *sd )
628 629 630 631 632 633 634 635
{
    const luid_t *modified_id =
        primary || (impersonation_level == src_token->impersonation_level) ?
            &src_token->modified_id : NULL;
    struct token *token = NULL;
    struct privilege *privilege;
    struct group *group;

636 637 638 639
    if (!primary &&
        (impersonation_level < SecurityAnonymous ||
         impersonation_level > SecurityDelegation ||
         (!src_token->primary && (impersonation_level > src_token->impersonation_level))))
640 641 642 643 644
    {
        set_error( STATUS_BAD_IMPERSONATION_LEVEL );
        return NULL;
    }

645 646 647 648
    token = create_token( primary, src_token->user, NULL, 0,
                          NULL, 0, src_token->default_dacl,
                          src_token->source, modified_id,
                          impersonation_level );
649 650 651
    if (!token) return token;

    /* copy groups */
652
    token->primary_group = NULL;
653 654 655 656 657 658 659 660 661 662 663
    LIST_FOR_EACH_ENTRY( group, &src_token->groups, struct group, entry )
    {
        size_t size = FIELD_OFFSET( struct group, sid.SubAuthority[group->sid.SubAuthorityCount] );
        struct group *newgroup = mem_alloc( size );
        if (!newgroup)
        {
            release_object( token );
            return NULL;
        }
        memcpy( newgroup, group, size );
        list_add_tail( &token->groups, &newgroup->entry );
664 665
        if (src_token->primary_group == &group->sid)
            token->primary_group = &newgroup->sid;
666 667 668 669 670 671 672 673 674 675 676
    }
    assert( token->primary_group );

    /* copy privileges */
    LIST_FOR_EACH_ENTRY( privilege, &src_token->privileges, struct privilege, entry )
        if (!privilege_add( token, &privilege->luid, privilege->enabled ))
        {
            release_object( token );
            return NULL;
        }

677 678 679
    if (sd) default_set_sd( &token->obj, sd, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
                            DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION );

680 681 682
    return token;
}

683 684 685 686 687 688 689 690
static ACL *create_default_dacl( const SID *user )
{
    ACCESS_ALLOWED_ACE *aaa;
    ACL *default_dacl;
    SID *sid;
    size_t default_dacl_size = sizeof(ACL) +
                               2*(sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) +
                               sizeof(local_system_sid) +
691
                               security_sid_len( user );
692 693 694 695

    default_dacl = mem_alloc( default_dacl_size );
    if (!default_dacl) return NULL;

696
    default_dacl->AclRevision = ACL_REVISION;
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    default_dacl->Sbz1 = 0;
    default_dacl->AclSize = default_dacl_size;
    default_dacl->AceCount = 2;
    default_dacl->Sbz2 = 0;

    /* GENERIC_ALL for Local System */
    aaa = (ACCESS_ALLOWED_ACE *)(default_dacl + 1);
    aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
    aaa->Header.AceFlags = 0;
    aaa->Header.AceSize = (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) +
                          sizeof(local_system_sid);
    aaa->Mask = GENERIC_ALL;
    sid = (SID *)&aaa->SidStart;
    memcpy( sid, &local_system_sid, sizeof(local_system_sid) );

    /* GENERIC_ALL for specified user */
713
    aaa = (ACCESS_ALLOWED_ACE *)((char *)aaa + aaa->Header.AceSize);
714 715
    aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
    aaa->Header.AceFlags = 0;
716
    aaa->Header.AceSize = (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + security_sid_len( user );
717 718
    aaa->Mask = GENERIC_ALL;
    sid = (SID *)&aaa->SidStart;
719
    memcpy( sid, user, security_sid_len( user ));
720 721 722 723

    return default_dacl;
}

724 725 726 727 728 729 730
struct sid_data
{
    SID_IDENTIFIER_AUTHORITY idauth;
    int count;
    unsigned int subauth[MAX_SUBAUTH_COUNT];
};

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
static struct security_descriptor *create_security_label_sd( struct token *token, PSID label_sid )
{
    size_t sid_len = security_sid_len( label_sid ), sacl_size, sd_size;
    SYSTEM_MANDATORY_LABEL_ACE *smla;
    struct security_descriptor *sd;
    ACL *sacl;

    sacl_size = sizeof(ACL) + FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + sid_len;
    sd_size = sizeof(struct security_descriptor) + sacl_size;
    if (!(sd = mem_alloc( sd_size )))
        return NULL;

    sd->control   = SE_SACL_PRESENT;
    sd->owner_len = 0;
    sd->group_len = 0;
    sd->sacl_len  = sacl_size;
    sd->dacl_len  = 0;

    sacl = (ACL *)(sd + 1);
    sacl->AclRevision = ACL_REVISION;
    sacl->Sbz1 = 0;
    sacl->AclSize = sacl_size;
    sacl->AceCount = 1;
    sacl->Sbz2 = 0;

    smla = (SYSTEM_MANDATORY_LABEL_ACE *)(sacl + 1);
    smla->Header.AceType = SYSTEM_MANDATORY_LABEL_ACE_TYPE;
    smla->Header.AceFlags = 0;
    smla->Header.AceSize = FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + sid_len;
    smla->Mask = SYSTEM_MANDATORY_LABEL_NO_WRITE_UP;
    memcpy( &smla->SidStart, label_sid, sid_len );

    assert( sd_is_valid( sd, sd_size ) );
    return sd;
}

int token_assign_label( struct token *token, PSID label )
{
    struct security_descriptor *sd;
    int ret = 0;

    if ((sd = create_security_label_sd( token, label )))
    {
        ret = set_sd_defaults_from_token( &token->obj, sd, LABEL_SECURITY_INFORMATION, token );
        free( sd );
    }

    return ret;
}

781
struct token *token_create_admin( void )
782
{
783 784 785 786
    struct token *token = NULL;
    static const SID_IDENTIFIER_AUTHORITY nt_authority = { SECURITY_NT_AUTHORITY };
    static const unsigned int alias_admins_subauth[] = { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS };
    static const unsigned int alias_users_subauth[] = { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS };
787 788
    /* on Windows, this value changes every time the user logs on */
    static const unsigned int logon_subauth[] = { SECURITY_LOGON_IDS_RID, 0, 1 /* FIXME: should be randomly generated when tokens are inherited by new processes */ };
789 790
    PSID alias_admins_sid;
    PSID alias_users_sid;
791
    PSID logon_sid;
792 793
    const SID *user_sid = security_unix_uid_to_sid( getuid() );
    ACL *default_dacl = create_default_dacl( user_sid );
794 795 796 797 798

    alias_admins_sid = security_sid_alloc( &nt_authority, sizeof(alias_admins_subauth)/sizeof(alias_admins_subauth[0]),
                                           alias_admins_subauth );
    alias_users_sid = security_sid_alloc( &nt_authority, sizeof(alias_users_subauth)/sizeof(alias_users_subauth[0]),
                                          alias_users_subauth );
799 800
    logon_sid = security_sid_alloc( &nt_authority, sizeof(logon_subauth)/sizeof(logon_subauth[0]),
                                    logon_subauth );
801

802
    if (alias_admins_sid && alias_users_sid && logon_sid && default_dacl)
803
    {
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
        const LUID_AND_ATTRIBUTES admin_privs[] =
        {
            { SeChangeNotifyPrivilege        , SE_PRIVILEGE_ENABLED },
            { SeSecurityPrivilege            , 0                    },
            { SeBackupPrivilege              , 0                    },
            { SeRestorePrivilege             , 0                    },
            { SeSystemtimePrivilege          , 0                    },
            { SeShutdownPrivilege            , 0                    },
            { SeRemoteShutdownPrivilege      , 0                    },
            { SeTakeOwnershipPrivilege       , 0                    },
            { SeDebugPrivilege               , 0                    },
            { SeSystemEnvironmentPrivilege   , 0                    },
            { SeSystemProfilePrivilege       , 0                    },
            { SeProfileSingleProcessPrivilege, 0                    },
            { SeIncreaseBasePriorityPrivilege, 0                    },
819
            { SeLoadDriverPrivilege          , SE_PRIVILEGE_ENABLED },
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
            { SeCreatePagefilePrivilege      , 0                    },
            { SeIncreaseQuotaPrivilege       , 0                    },
            { SeUndockPrivilege              , 0                    },
            { SeManageVolumePrivilege        , 0                    },
            { SeImpersonatePrivilege         , SE_PRIVILEGE_ENABLED },
            { SeCreateGlobalPrivilege        , SE_PRIVILEGE_ENABLED },
        };
        /* note: we don't include non-builtin groups here for the user -
         * telling us these is the job of a client-side program */
        const SID_AND_ATTRIBUTES admin_groups[] =
        {
            { security_world_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
            { security_local_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
            { security_interactive_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
            { security_authenticated_user_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
835
            { alias_admins_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY|SE_GROUP_OWNER },
836
            { alias_users_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
837
            { logon_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY|SE_GROUP_LOGON_ID },
838
        };
839
        static const TOKEN_SOURCE admin_source = {"SeMgr", {0, 0}};
840 841 842
        token = create_token( TRUE, user_sid, admin_groups, sizeof(admin_groups)/sizeof(admin_groups[0]),
                              admin_privs, sizeof(admin_privs)/sizeof(admin_privs[0]), default_dacl,
                              admin_source, NULL, -1 );
843 844
        /* we really need a primary group */
        assert( token->primary_group );
845 846
    }

847
    free( logon_sid );
848 849 850
    free( alias_admins_sid );
    free( alias_users_sid );
    free( default_dacl );
851

852
    return token;
853 854
}

855
static struct privilege *token_find_privilege( struct token *token, const LUID *luid, int enabled_only )
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
{
    struct privilege *privilege;
    LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
    {
        if (is_equal_luid( luid, &privilege->luid ))
        {
            if (enabled_only && !privilege->enabled)
                return NULL;
            return privilege;
        }
    }
    return NULL;
}

static unsigned int token_adjust_privileges( struct token *token, const LUID_AND_ATTRIBUTES *privs,
                                             unsigned int count, LUID_AND_ATTRIBUTES *mod_privs,
872
                                             unsigned int mod_privs_count )
873
{
874
    unsigned int i, modified_count = 0;
875

876 877 878
    /* mark as modified */
    allocate_luid( &token->modified_id );

879 880 881 882 883 884 885 886 887 888
    for (i = 0; i < count; i++)
    {
        struct privilege *privilege =
            token_find_privilege( token, &privs[i].Luid, FALSE );
        if (!privilege)
        {
            set_error( STATUS_NOT_ALL_ASSIGNED );
            continue;
        }

889
        if (privs[i].Attributes & SE_PRIVILEGE_REMOVED)
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
            privilege_remove( privilege );
        else
        {
            /* save previous state for caller */
            if (mod_privs_count)
            {
                luid_and_attr_from_privilege(mod_privs, privilege);
                mod_privs++;
                mod_privs_count--;
                modified_count++;
            }

            if (privs[i].Attributes & SE_PRIVILEGE_ENABLED)
                privilege->enabled = TRUE;
            else
                privilege->enabled = FALSE;
        }
    }
    return modified_count;
}

static void token_disable_privileges( struct token *token )
{
    struct privilege *privilege;
914 915 916 917

    /* mark as modified */
    allocate_luid( &token->modified_id );

918 919 920 921
    LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
        privilege->enabled = FALSE;
}

922 923 924 925
int token_check_privileges( struct token *token, int all_required,
                            const LUID_AND_ATTRIBUTES *reqprivs,
                            unsigned int count, LUID_AND_ATTRIBUTES *usedprivs)
{
926
    unsigned int i, enabled_count = 0;
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949

    for (i = 0; i < count; i++)
    {
        struct privilege *privilege = 
            token_find_privilege( token, &reqprivs[i].Luid, TRUE );

        if (usedprivs)
            usedprivs[i] = reqprivs[i];

        if (privilege && privilege->enabled)
        {
            enabled_count++;
            if (usedprivs)
                usedprivs[i].Attributes |= SE_PRIVILEGE_USED_FOR_ACCESS;
        }
    }

    if (all_required)
        return (enabled_count == count);
    else
        return (enabled_count > 0);
}

950
int token_sid_present( struct token *token, const SID *sid, int deny )
951
{
952
    struct group *group;
953 954 955

    if (security_equal_sid( token->user, sid )) return TRUE;

956
    LIST_FOR_EACH_ENTRY( group, &token->groups, struct group, entry )
957 958 959 960 961 962 963 964 965 966
    {
        if (!group->enabled) continue;
        if (group->deny_only && !deny) continue;

        if (security_equal_sid( &group->sid, sid )) return TRUE;
    }

    return FALSE;
}

967 968 969 970 971 972
/* Checks access to a security descriptor. 'sd' must have been validated by
 * caller. It returns STATUS_SUCCESS if call succeeded or an error indicating
 * the reason. 'status' parameter will indicate if access is granted or denied.
 *
 * If both returned value and 'status' are STATUS_SUCCESS then access is granted.
 */
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
static unsigned int token_access_check( struct token *token,
                                 const struct security_descriptor *sd,
                                 unsigned int desired_access,
                                 LUID_AND_ATTRIBUTES *privs,
                                 unsigned int *priv_count,
                                 const GENERIC_MAPPING *mapping,
                                 unsigned int *granted_access,
                                 unsigned int *status )
{
    unsigned int current_access = 0;
    unsigned int denied_access = 0;
    ULONG i;
    const ACL *dacl;
    int dacl_present;
    const ACE_HEADER *ace;
    const SID *owner;

990
    /* assume no access rights */
991 992 993 994 995
    *granted_access = 0;

    /* fail if desired_access contains generic rights */
    if (desired_access & (GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE|GENERIC_ALL))
    {
996
        if (priv_count) *priv_count = 0;
997
        return STATUS_GENERIC_NOT_MAPPED;
998 999 1000 1001 1002 1003
    }

    dacl = sd_get_dacl( sd, &dacl_present );
    owner = sd_get_owner( sd );
    if (!owner || !sd_get_group( sd ))
    {
1004
        if (priv_count) *priv_count = 0;
1005
        return STATUS_INVALID_SECURITY_DESCR;
1006 1007 1008
    }

    /* 1: Grant desired access if the object is unprotected */
1009
    if (!dacl_present || !dacl)
1010
    {
1011
        if (priv_count) *priv_count = 0;
1012 1013 1014 1015
        if (desired_access & MAXIMUM_ALLOWED)
            *granted_access = mapping->GenericAll;
        else
            *granted_access = desired_access;
1016
        return *status = STATUS_SUCCESS;
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    }

    /* 2: Check if caller wants access to system security part. Note: access
     * is only granted if specifically asked for */
    if (desired_access & ACCESS_SYSTEM_SECURITY)
    {
        const LUID_AND_ATTRIBUTES security_priv = { SeSecurityPrivilege, 0 };
        LUID_AND_ATTRIBUTES retpriv = security_priv;
        if (token_check_privileges( token, TRUE, &security_priv, 1, &retpriv ))
        {
            if (priv_count)
            {
                /* assumes that there will only be one privilege to return */
                if (*priv_count >= 1)
                {
                    *priv_count = 1;
                    *privs = retpriv;
                }
                else
                {
                    *priv_count = 1;
                    return STATUS_BUFFER_TOO_SMALL;
                }
            }
            current_access |= ACCESS_SYSTEM_SECURITY;
            if (desired_access == current_access)
            {
                *granted_access = current_access;
1045
                return *status = STATUS_SUCCESS;
1046 1047 1048 1049
            }
        }
        else
        {
1050
            if (priv_count) *priv_count = 0;
1051 1052
            *status = STATUS_PRIVILEGE_NOT_HELD;
            return STATUS_SUCCESS;
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
        }
    }
    else if (priv_count) *priv_count = 0;

    /* 3: Check whether the token is the owner */
    /* NOTE: SeTakeOwnershipPrivilege is not checked for here - it is instead
     * checked when a "set owner" call is made, overriding the access rights
     * determined here. */
    if (token_sid_present( token, owner, FALSE ))
    {
        current_access |= (READ_CONTROL | WRITE_DAC);
        if (desired_access == current_access)
        {
            *granted_access = current_access;
1067
            return *status = STATUS_SUCCESS;
1068 1069 1070 1071 1072
        }
    }

    /* 4: Grant rights according to the DACL */
    ace = (const ACE_HEADER *)(dacl + 1);
1073
    for (i = 0; i < dacl->AceCount; i++, ace = ace_next( ace ))
1074 1075 1076 1077
    {
        const ACCESS_ALLOWED_ACE *aa_ace;
        const ACCESS_DENIED_ACE *ad_ace;
        const SID *sid;
1078 1079 1080 1081

        if (ace->AceFlags & INHERIT_ONLY_ACE)
            continue;

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        switch (ace->AceType)
        {
        case ACCESS_DENIED_ACE_TYPE:
            ad_ace = (const ACCESS_DENIED_ACE *)ace;
            sid = (const SID *)&ad_ace->SidStart;
            if (token_sid_present( token, sid, TRUE ))
            {
                unsigned int access = ad_ace->Mask;
                map_generic_mask(&access, mapping);
                if (desired_access & MAXIMUM_ALLOWED)
                    denied_access |= access;
                else
                {
                    denied_access |= (access & ~current_access);
1096
                    if (desired_access & access) goto done;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
                }
            }
            break;
        case ACCESS_ALLOWED_ACE_TYPE:
            aa_ace = (const ACCESS_ALLOWED_ACE *)ace;
            sid = (const SID *)&aa_ace->SidStart;
            if (token_sid_present( token, sid, FALSE ))
            {
                unsigned int access = aa_ace->Mask;
                map_generic_mask(&access, mapping);
                if (desired_access & MAXIMUM_ALLOWED)
                    current_access |= access;
                else
                    current_access |= (access & ~denied_access);
            }
            break;
        }

        /* don't bother carrying on checking if we've already got all of
            * rights we need */
        if (desired_access == *granted_access)
            break;
    }

1121
done:
1122 1123 1124 1125 1126 1127
    if (desired_access & MAXIMUM_ALLOWED)
        *granted_access = current_access & ~denied_access;
    else
        if ((current_access & desired_access) == desired_access)
            *granted_access = current_access & desired_access;
        else
1128 1129 1130 1131
            *granted_access = 0;

    *status = *granted_access ? STATUS_SUCCESS : STATUS_ACCESS_DENIED;
    return STATUS_SUCCESS;
1132 1133
}

1134 1135 1136 1137 1138
const ACL *token_get_default_dacl( struct token *token )
{
    return token->default_dacl;
}

1139
const SID *token_get_user( struct token *token )
1140
{
1141 1142
    return token->user;
}
1143

1144 1145 1146
const SID *token_get_primary_group( struct token *token )
{
    return token->primary_group;
1147 1148
}

1149 1150 1151 1152
int check_object_access(struct object *obj, unsigned int *access)
{
    GENERIC_MAPPING mapping;
    struct token *token = current->token ? current->token : current->process->token;
1153
    unsigned int status;
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    int res;

    mapping.GenericAll = obj->ops->map_access( obj, GENERIC_ALL );

    if (!obj->sd)
    {
        if (*access & MAXIMUM_ALLOWED)
            *access = mapping.GenericAll;
        return TRUE;
    }

    mapping.GenericRead  = obj->ops->map_access( obj, GENERIC_READ );
    mapping.GenericWrite = obj->ops->map_access( obj, GENERIC_WRITE );
    mapping.GenericExecute = obj->ops->map_access( obj, GENERIC_EXECUTE );

1169
    res = token_access_check( token, obj->sd, *access, NULL, NULL,
1170 1171 1172 1173 1174 1175 1176 1177
                              &mapping, access, &status ) == STATUS_SUCCESS &&
          status == STATUS_SUCCESS;

    if (!res) set_error( STATUS_ACCESS_DENIED );
    return res;
}


1178 1179 1180
/* open a security token */
DECL_HANDLER(open_token)
{
1181
    if (req->flags & OPEN_TOKEN_THREAD)
1182 1183 1184 1185 1186
    {
        struct thread *thread = get_thread_from_handle( req->handle, 0 );
        if (thread)
        {
            if (thread->token)
1187
            {
1188
                if (!thread->token->primary && thread->token->impersonation_level <= SecurityAnonymous)
1189 1190 1191 1192 1193
                    set_error( STATUS_CANT_OPEN_ANONYMOUS );
                else
                    reply->token = alloc_handle( current->process, thread->token,
                                                 req->access, req->attributes );
            }
1194
            else
1195
                set_error( STATUS_NO_TOKEN );
1196 1197 1198 1199 1200 1201 1202 1203 1204
            release_object( thread );
        }
    }
    else
    {
        struct process *process = get_process_from_handle( req->handle, 0 );
        if (process)
        {
            if (process->token)
1205
                reply->token = alloc_handle( current->process, process->token, req->access,
1206
                                             req->attributes );
1207
            else
1208
                set_error( STATUS_NO_TOKEN );
1209 1210 1211 1212
            release_object( process );
        }
    }
}
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231

/* adjust the privileges held by a token */
DECL_HANDLER(adjust_token_privileges)
{
    struct token *token;
    unsigned int access = TOKEN_ADJUST_PRIVILEGES;

    if (req->get_modified_state) access |= TOKEN_QUERY;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 access, &token_ops )))
    {
        const LUID_AND_ATTRIBUTES *privs = get_req_data();
        LUID_AND_ATTRIBUTES *modified_privs = NULL;
        unsigned int priv_count = get_req_data_size() / sizeof(LUID_AND_ATTRIBUTES);
        unsigned int modified_priv_count = 0;

        if (req->get_modified_state && !req->disable_all)
        {
1232
            unsigned int i;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
            /* count modified privs */
            for (i = 0; i < priv_count; i++)
            {
                struct privilege *privilege =
                    token_find_privilege( token, &privs[i].Luid, FALSE );
                if (privilege && req->get_modified_state)
                    modified_priv_count++;
            }
            reply->len = modified_priv_count;
            modified_priv_count = min( modified_priv_count, get_reply_max_size() / sizeof(*modified_privs) );
            if (modified_priv_count)
                modified_privs = set_reply_data_size( modified_priv_count * sizeof(*modified_privs) );
        }
        reply->len = modified_priv_count * sizeof(*modified_privs);

        if (req->disable_all)
            token_disable_privileges( token );
        else
1251
            token_adjust_privileges( token, privs, priv_count, modified_privs, modified_priv_count );
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

        release_object( token );
    }
}

/* retrieves the list of privileges that may be held be the token */
DECL_HANDLER(get_token_privileges)
{
    struct token *token;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        int priv_count = 0;
        LUID_AND_ATTRIBUTES *privs;
        struct privilege *privilege;

        LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
            priv_count++;

        reply->len = priv_count * sizeof(*privs);
        if (reply->len <= get_reply_max_size())
        {
            privs = set_reply_data_size( priv_count * sizeof(*privs) );
            if (privs)
            {
                int i = 0;
                LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
                {
                    luid_and_attr_from_privilege( &privs[i], privilege );
                    i++;
                }
            }
        }
        else
            set_error(STATUS_BUFFER_TOO_SMALL);

        release_object( token );
    }
}

/* creates a duplicate of the token */
DECL_HANDLER(duplicate_token)
{
    struct token *src_token;
1298 1299 1300 1301 1302
    struct unicode_str name;
    const struct security_descriptor *sd;
    const struct object_attributes *objattr = get_req_object_attributes( &sd, &name, NULL );

    if (!objattr) return;
1303

1304 1305 1306 1307
    if ((src_token = (struct token *)get_handle_obj( current->process, req->handle,
                                                     TOKEN_DUPLICATE,
                                                     &token_ops )))
    {
1308
        struct token *token = token_duplicate( src_token, req->primary, req->impersonation_level, sd );
1309 1310
        if (token)
        {
1311
            reply->new_handle = alloc_handle_no_access_check( current->process, token, req->access, objattr->attributes );
1312 1313 1314 1315 1316
            release_object( token );
        }
        release_object( src_token );
    }
}
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

/* checks the specified privileges are held by the token */
DECL_HANDLER(check_token_privileges)
{
    struct token *token;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        unsigned int count = get_req_data_size() / sizeof(LUID_AND_ATTRIBUTES);
1328 1329 1330 1331

        if (!token->primary && token->impersonation_level <= SecurityAnonymous)
            set_error( STATUS_BAD_IMPERSONATION_LEVEL );
        else if (get_reply_max_size() >= count * sizeof(LUID_AND_ATTRIBUTES))
1332 1333 1334 1335 1336 1337 1338 1339 1340
        {
            LUID_AND_ATTRIBUTES *usedprivs = set_reply_data_size( count * sizeof(*usedprivs) );
            reply->has_privileges = token_check_privileges( token, req->all_required, get_req_data(), count, usedprivs );
        }
        else
            set_error( STATUS_BUFFER_OVERFLOW );
        release_object( token );
    }
}
1341 1342 1343 1344 1345

/* checks that a user represented by a token is allowed to access an object
 * represented by a security descriptor */
DECL_HANDLER(access_check)
{
1346
    data_size_t sd_size = get_req_data_size();
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    const struct security_descriptor *sd = get_req_data();
    struct token *token;

    if (!sd_is_valid( sd, sd_size ))
    {
        set_error( STATUS_ACCESS_VIOLATION );
        return;
    }

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        GENERIC_MAPPING mapping;
        unsigned int status;
        LUID_AND_ATTRIBUTES priv;
        unsigned int priv_count = 1;

        memset(&priv, 0, sizeof(priv));

1367 1368 1369 1370 1371 1372 1373
        /* only impersonation tokens may be used with this function */
        if (token->primary)
        {
            set_error( STATUS_NO_IMPERSONATION_TOKEN );
            release_object( token );
            return;
        }
1374 1375 1376 1377 1378 1379 1380
        /* anonymous impersonation tokens can't be used */
        if (token->impersonation_level <= SecurityAnonymous)
        {
            set_error( STATUS_BAD_IMPERSONATION_LEVEL );
            release_object( token );
            return;
        }
1381 1382 1383 1384 1385 1386

        mapping.GenericRead = req->mapping_read;
        mapping.GenericWrite = req->mapping_write;
        mapping.GenericExecute = req->mapping_execute;
        mapping.GenericAll = req->mapping_all;

1387
        status = token_access_check(
1388
            token, sd, req->desired_access, &priv, &priv_count, &mapping,
1389
            &reply->access_granted, &reply->access_status );
1390 1391 1392 1393 1394 1395 1396 1397 1398

        reply->privileges_len = priv_count*sizeof(LUID_AND_ATTRIBUTES);

        if ((priv_count > 0) && (reply->privileges_len <= get_reply_max_size()))
        {
            LUID_AND_ATTRIBUTES *privs = set_reply_data_size( priv_count * sizeof(*privs) );
            memcpy( privs, &priv, sizeof(priv) );
        }

1399
        set_error( status );
1400 1401 1402
        release_object( token );
    }
}
1403

1404
/* retrieves the SID of the user that the token represents */
1405
DECL_HANDLER(get_token_sid)
1406 1407 1408
{
    struct token *token;

1409
    reply->sid_len = 0;
1410 1411 1412 1413 1414

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
1415
        const SID *sid = NULL;
1416

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        switch (req->which_sid)
        {
        case TokenUser:
            assert(token->user);
            sid = token->user;
            break;
        case TokenPrimaryGroup:
            sid = token->primary_group;
            break;
        case TokenOwner:
1427
        {
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
            struct group *group;
            LIST_FOR_EACH_ENTRY( group, &token->groups, struct group, entry )
            {
                if (group->owner)
                {
                    sid = &group->sid;
                    break;
                }
            }
            break;
        }
        default:
            set_error( STATUS_INVALID_PARAMETER );
            break;
1442 1443
        }

1444 1445
        if (sid)
        {
1446
            reply->sid_len = security_sid_len( sid );
1447 1448 1449
            if (reply->sid_len <= get_reply_max_size()) set_reply_data( sid, reply->sid_len );
            else set_error( STATUS_BUFFER_TOO_SMALL );
        }
1450 1451 1452
        release_object( token );
    }
}
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465

/* retrieves the groups that the user represented by the token belongs to */
DECL_HANDLER(get_token_groups)
{
    struct token *token;

    reply->user_len = 0;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        size_t size_needed = sizeof(struct token_groups);
1466
        size_t sid_size = 0;
1467 1468 1469 1470 1471 1472
        unsigned int group_count = 0;
        const struct group *group;

        LIST_FOR_EACH_ENTRY( group, &token->groups, const struct group, entry )
        {
            group_count++;
1473
            sid_size += security_sid_len( &group->sid );
1474
        }
1475 1476
        size_needed += sid_size;
        /* attributes size */
1477 1478
        size_needed += sizeof(unsigned int) * group_count;

1479
        /* reply buffer contains size_needed bytes formatted as:
1480

1481 1482 1483 1484 1485 1486 1487 1488 1489
           unsigned int count;
           unsigned int attrib[count];
           char sid_data[];

           user_len includes extra data needed for TOKEN_GROUPS representation,
           required caller buffer size calculated here to avoid extra server call */
        reply->user_len = FIELD_OFFSET( TOKEN_GROUPS, Groups[group_count] ) + sid_size;

        if (reply->user_len <= get_reply_max_size())
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
        {
            struct token_groups *tg = set_reply_data_size( size_needed );
            if (tg)
            {
                unsigned int *attr_ptr = (unsigned int *)(tg + 1);
                SID *sid_ptr = (SID *)(attr_ptr + group_count);

                tg->count = group_count;

                LIST_FOR_EACH_ENTRY( group, &token->groups, const struct group, entry )
                {

                    *attr_ptr = 0;
                    if (group->mandatory) *attr_ptr |= SE_GROUP_MANDATORY;
                    if (group->def) *attr_ptr |= SE_GROUP_ENABLED_BY_DEFAULT;
                    if (group->enabled) *attr_ptr |= SE_GROUP_ENABLED;
                    if (group->owner) *attr_ptr |= SE_GROUP_OWNER;
                    if (group->deny_only) *attr_ptr |= SE_GROUP_USE_FOR_DENY_ONLY;
                    if (group->resource) *attr_ptr |= SE_GROUP_RESOURCE;
1509
                    if (group->logon) *attr_ptr |= SE_GROUP_LOGON_ID;
1510

1511
                    memcpy(sid_ptr, &group->sid, security_sid_len( &group->sid ));
1512

1513
                    sid_ptr = (SID *)((char *)sid_ptr + security_sid_len( &group->sid ));
1514 1515 1516 1517 1518 1519 1520 1521 1522
                    attr_ptr++;
                }
            }
        }
        else set_error( STATUS_BUFFER_TOO_SMALL );

        release_object( token );
    }
}
1523

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
DECL_HANDLER(get_token_impersonation_level)
{
    struct token *token;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        if (token->primary)
            set_error( STATUS_INVALID_PARAMETER );
        else
            reply->impersonation_level = token->impersonation_level;

        release_object( token );
    }
}

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
DECL_HANDLER(get_token_statistics)
{
    struct token *token;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        reply->token_id = token->token_id;
        reply->modified_id = token->modified_id;
        reply->primary = token->primary;
        reply->impersonation_level = token->impersonation_level;
        reply->group_count = list_count( &token->groups );
        reply->privilege_count = list_count( &token->privileges );

        release_object( token );
    }
}
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604

DECL_HANDLER(get_token_default_dacl)
{
    struct token *token;

    reply->acl_len = 0;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY,
                                                 &token_ops )))
    {
        if (token->default_dacl)
            reply->acl_len = token->default_dacl->AclSize;

        if (reply->acl_len <= get_reply_max_size())
        {
            ACL *acl_reply = set_reply_data_size( reply->acl_len );
            if (acl_reply)
                memcpy( acl_reply, token->default_dacl, reply->acl_len );
        }
        else set_error( STATUS_BUFFER_TOO_SMALL );

        release_object( token );
    }
}

DECL_HANDLER(set_token_default_dacl)
{
    struct token *token;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_ADJUST_DEFAULT,
                                                 &token_ops )))
    {
        const ACL *acl = get_req_data();
        unsigned int acl_size = get_req_data_size();

        free( token->default_dacl );
        token->default_dacl = NULL;

        if (acl_size)
            token->default_dacl = memdup( acl, acl_size );

        release_object( token );
    }
}