token.c 50.4 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 <sys/types.h>
30
#include <unistd.h>
31

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

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

43 44
#define MAX_SUBAUTH_COUNT 1

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

67 68
struct sid_attrs
{
69 70
    const struct sid *sid;
    unsigned int      attrs;
71 72
};

73 74 75 76 77 78 79
const struct sid world_sid = { SID_REVISION, 1, SECURITY_WORLD_SID_AUTHORITY, { SECURITY_WORLD_RID } };
const struct sid local_system_sid = { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_LOCAL_SYSTEM_RID } };
const struct sid high_label_sid = { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_HIGH_RID } };
const struct sid local_user_sid = { SID_REVISION, 5, SECURITY_NT_AUTHORITY, { SECURITY_NT_NON_UNIQUE, 0, 0, 0, 1000 } };
const struct sid builtin_admins_sid = { SID_REVISION, 2, SECURITY_NT_AUTHORITY, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS } };
const struct sid builtin_users_sid = { SID_REVISION, 2, SECURITY_NT_AUTHORITY, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS } };
const struct sid domain_users_sid = { SID_REVISION, 5, SECURITY_NT_AUTHORITY, { SECURITY_NT_NON_UNIQUE, 0, 0, 0, DOMAIN_GROUP_RID_USERS } };
80

81 82 83 84
static const struct sid local_sid = { SID_REVISION, 1, SECURITY_LOCAL_SID_AUTHORITY, { SECURITY_LOCAL_RID } };
static const struct sid interactive_sid = { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_INTERACTIVE_RID } };
static const struct sid anonymous_logon_sid = { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_ANONYMOUS_LOGON_RID } };
static const struct sid authenticated_user_sid = { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_AUTHENTICATED_USER_RID } };
85

86
static struct luid prev_luid_value = { 1000, 0 };
87

88 89 90 91 92
static const WCHAR token_name[] = {'T','o','k','e','n'};

struct type_descr token_type =
{
    { token_name, sizeof(token_name) },   /* name */
93 94 95 96 97 98 99 100
    TOKEN_ALL_ACCESS | SYNCHRONIZE,       /* valid_access */
    {                                     /* mapping */
        STANDARD_RIGHTS_READ | TOKEN_QUERY_SOURCE | TOKEN_QUERY | TOKEN_DUPLICATE,
        STANDARD_RIGHTS_WRITE | TOKEN_ADJUST_SESSIONID | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_GROUPS
        | TOKEN_ADJUST_PRIVILEGES,
        STANDARD_RIGHTS_EXECUTE | TOKEN_IMPERSONATE | TOKEN_ASSIGN_PRIMARY,
        TOKEN_ALL_ACCESS
    },
101 102
};

103 104 105
struct token
{
    struct object  obj;             /* object header */
106 107
    struct luid    token_id;        /* system-unique id of token */
    struct luid    modified_id;     /* new id allocated every time token is modified */
108
    struct list    privileges;      /* privileges available to the token */
109
    struct list    groups;          /* groups that the user of this token belongs to (sid_and_attributes) */
110 111 112
    struct sid    *user;            /* SID of user this token represents */
    struct sid    *owner;           /* SID of owner (points to user or one of groups) */
    struct sid    *primary_group;   /* SID of user's primary group (points to one of groups) */
113 114
    unsigned int   primary;         /* is this a primary or impersonation token? */
    unsigned int   session_id;      /* token session id */
115
    struct acl    *default_dacl;    /* the default DACL to assign to objects created by this user */
116
    int            impersonation_level; /* impersonation level this token is capable of if non-primary token */
117
    int            elevation;       /* elevation type */
118 119 120 121 122
};

struct privilege
{
    struct list entry;
123
    struct luid luid;
124 125
    unsigned    enabled  : 1; /* is the privilege currently enabled? */
    unsigned    def      : 1; /* is the privilege enabled by default? */
126 127
};

128
struct group
129
{
130 131 132
    struct list    entry;
    unsigned int   attrs;
    struct sid     sid;
133 134
};

135
static void token_dump( struct object *obj, int verbose );
136
static void token_destroy( struct object *obj );
137 138 139 140

static const struct object_ops token_ops =
{
    sizeof(struct token),      /* size */
141
    &token_type,               /* type */
142 143 144 145
    token_dump,                /* dump */
    no_add_queue,              /* add_queue */
    NULL,                      /* remove_queue */
    NULL,                      /* signaled */
146 147
    NULL,                      /* satisfied */
    no_signal,                 /* signal */
148
    no_get_fd,                 /* get_fd */
149
    default_map_access,        /* map_access */
150 151
    default_get_sd,            /* get_sd */
    default_set_sd,            /* set_sd */
152
    no_get_full_name,          /* get_full_name */
153
    no_lookup_name,            /* lookup_name */
154 155
    no_link_name,              /* link_name */
    NULL,                      /* unlink_name */
156
    no_open_file,              /* open_file */
157
    no_kernel_obj_list,        /* get_kernel_obj_list */
158
    no_close_handle,           /* close_handle */
159
    token_destroy              /* destroy */
160 161 162 163
};

static void token_dump( struct object *obj, int verbose )
{
164 165 166 167
    struct token *token = (struct token *)obj;
    assert( obj->ops == &token_ops );
    fprintf( stderr, "Token id=%d.%u primary=%u impersonation level=%d\n", token->token_id.high_part,
             token->token_id.low_part, token->primary, token->impersonation_level );
168 169
}

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
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;
        }
    }
}

193
const struct sid *security_unix_uid_to_sid( uid_t uid )
194 195 196
{
    /* very simple mapping: either the current user or not the current user */
    if (uid == getuid())
197
        return &local_user_sid;
198 199 200 201
    else
        return &anonymous_logon_sid;
}

202
static int acl_is_valid( const struct acl *acl, data_size_t size )
203 204
{
    ULONG i;
205
    const struct ace *ace;
206

207
    if (size < sizeof(*acl)) return FALSE;
208 209

    size = min(size, MAX_ACL_LEN);
210
    size -= sizeof(*acl);
211

212
    for (i = 0, ace = ace_first( acl ); i < acl->count; i++, ace = ace_next( ace ))
213
    {
214 215 216
        if (size < sizeof(*ace) || size < ace->size) return FALSE;
        size -= ace->size;
        switch (ace->type)
217 218 219 220 221
        {
        case ACCESS_DENIED_ACE_TYPE:
        case ACCESS_ALLOWED_ACE_TYPE:
        case SYSTEM_AUDIT_ACE_TYPE:
        case SYSTEM_ALARM_ACE_TYPE:
222 223
        case SYSTEM_MANDATORY_LABEL_ACE_TYPE:
            break;
224 225 226
        default:
            return FALSE;
        }
227
        if (!sid_valid_size( (const struct sid *)(ace + 1), ace->size - sizeof(*ace) )) return FALSE;
228 229 230 231
    }
    return TRUE;
}

232
static unsigned int get_sid_count( const struct sid *sid, data_size_t size )
233 234 235
{
    unsigned int count;

236
    for (count = 0; sid_valid_size( sid, size ); count++)
237
    {
238 239
        size -= sid_len( sid );
        sid = (const struct sid *)((char *)sid + sid_len( sid ));
240 241 242 243
    }
    return count;
}

244 245
/* checks whether all members of a security descriptor fit inside the size
 * of memory specified */
246
int sd_is_valid( const struct security_descriptor *sd, data_size_t size )
247 248
{
    size_t offset = sizeof(struct security_descriptor);
249 250
    const struct sid *group;
    const struct sid *owner;
251 252
    const struct acl *sacl;
    const struct acl *dacl;
253 254 255 256 257
    int dummy;

    if (size < offset)
        return FALSE;

258
    if (sd->owner_len >= offsetof(struct sid, sub_auth[255]) || offset + sd->owner_len > size) return FALSE;
259 260
    owner = sd_get_owner( sd );
    offset += sd->owner_len;
261
    if (owner && !sid_valid_size( owner, sd->owner_len )) return FALSE;
262

263
    if (sd->group_len >= offsetof(struct sid, sub_auth[255]) || offset + sd->group_len > size) return FALSE;
264 265
    group = sd_get_group( sd );
    offset += sd->group_len;
266
    if (group && !sid_valid_size( group, sd->group_len )) return FALSE;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

    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;
}

285
/* extract security labels from SACL */
286
struct acl *extract_security_labels( const struct acl *sacl )
287
{
288
    size_t size = sizeof(*sacl);
289 290
    const struct ace *ace;
    struct ace *label_ace;
291
    unsigned int i, count = 0;
292
    struct acl *label_acl;
293

294
    for (i = 0, ace = ace_first( sacl ); i < sacl->count; i++, ace = ace_next( ace ))
295
    {
296
        if (ace->type == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
297
        {
298
            size += ace->size;
299 300 301 302 303 304 305
            count++;
        }
    }

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

306 307 308 309 310
    label_acl->revision = sacl->revision;
    label_acl->pad1     = 0;
    label_acl->size     = size;
    label_acl->count    = count;
    label_acl->pad2     = 0;
311

312 313
    label_ace = ace_first( label_acl );
    for (i = 0, ace = ace_first( sacl ); i < sacl->count; i++, ace = ace_next( ace ))
314
    {
315
        if (ace->type == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
316
        {
317 318
            memcpy( label_ace, ace, ace->size );
            label_ace = ace_next( label_ace );
319 320 321 322 323
        }
    }
    return label_acl;
}

324
/* replace security labels in an existing SACL */
325
struct acl *replace_security_labels( const struct acl *old_sacl, const struct acl *new_sacl )
326
{
327 328
    const struct ace *ace;
    struct ace *replaced_ace;
329
    unsigned int i, count = 0;
330
    unsigned char revision = ACL_REVISION;
331
    struct acl *replaced_acl;
332
    data_size_t size = sizeof(*replaced_acl);
333 334 335

    if (old_sacl)
    {
336
        revision = max( revision, old_sacl->revision );
337
        for (i = 0, ace = ace_first( old_sacl ); i < old_sacl->count; i++, ace = ace_next( ace ))
338
        {
339 340
            if (ace->type == SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            size += ace->size;
341 342 343 344 345 346
            count++;
        }
    }

    if (new_sacl)
    {
347
        revision = max( revision, new_sacl->revision );
348
        for (i = 0, ace = ace_first( new_sacl ); i < new_sacl->count; i++, ace = ace_next( ace ))
349
        {
350 351
            if (ace->type != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            size += ace->size;
352 353 354
            count++;
        }
    }
355 356 357 358 359
    if (size > MAX_ACL_LEN)
    {
        set_error( STATUS_INVALID_ACL );
        return NULL;
    }
360 361 362 363

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

364 365 366 367 368
    replaced_acl->revision = revision;
    replaced_acl->pad1     = 0;
    replaced_acl->size     = size;
    replaced_acl->count    = count;
    replaced_acl->pad2     = 0;
369

370
    replaced_ace = (struct ace *)(replaced_acl + 1);
371 372
    if (old_sacl)
    {
373
        for (i = 0, ace = ace_first( old_sacl ); i < old_sacl->count; i++, ace = ace_next( ace ))
374
        {
375 376 377
            if (ace->type == SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            memcpy( replaced_ace, ace, ace->size );
            replaced_ace = ace_next( replaced_ace );
378 379 380 381 382
        }
    }

    if (new_sacl)
    {
383
        for (i = 0, ace = ace_first( new_sacl ); i < new_sacl->count; i++, ace = ace_next( ace ))
384
        {
385 386 387
            if (ace->type != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
            memcpy( replaced_ace, ace, ace->size );
            replaced_ace = ace_next( replaced_ace );
388 389 390 391 392 393
        }
    }

    return replaced_acl;
}

394
static inline int is_equal_luid( struct luid luid1, struct luid luid2 )
395
{
396
    return (luid1.low_part == luid2.low_part && luid1.high_part == luid2.high_part);
397 398
}

399
static inline void allocate_luid( struct luid *luid )
400
{
401
    prev_luid_value.low_part++;
402 403 404
    *luid = prev_luid_value;
}

405 406
DECL_HANDLER( allocate_locally_unique_id )
{
407
    allocate_luid( &reply->luid );
408 409
}

410
static inline struct luid_attr luid_and_attr_from_privilege( const struct privilege *in )
411
{
412 413 414 415 416
    struct luid_attr ret = { in->luid };

    ret.attrs = (in->enabled ? SE_PRIVILEGE_ENABLED : 0) |
                (in->def ? SE_PRIVILEGE_ENABLED_BY_DEFAULT : 0);
    return ret;
417 418
}

419
static struct privilege *privilege_add( struct token *token, struct luid luid, int enabled )
420 421 422 423
{
    struct privilege *privilege = mem_alloc( sizeof(*privilege) );
    if (privilege)
    {
424
        privilege->luid = luid;
425 426 427 428 429 430
        privilege->def = privilege->enabled = (enabled != 0);
        list_add_tail( &token->privileges, &privilege->entry );
    }
    return privilege;
}

431
static inline void privilege_remove( struct privilege *privilege )
432 433 434 435 436 437 438 439 440 441 442 443 444
{
    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;

445 446
    free( token->user );

447 448 449 450 451
    LIST_FOR_EACH_SAFE( cursor, cursor_next, &token->privileges )
    {
        struct privilege *privilege = LIST_ENTRY( cursor, struct privilege, entry );
        privilege_remove( privilege );
    }
452 453 454

    LIST_FOR_EACH_SAFE( cursor, cursor_next, &token->groups )
    {
455
        struct group *group = LIST_ENTRY( cursor, struct group, entry );
456 457 458
        list_remove( &group->entry );
        free( group );
    }
459 460

    free( token->default_dacl );
461 462
}

463 464 465 466 467
/* 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.
468 469
 *  modified_id may be NULL, indicating that a new modified_id luid should be
 *   allocated.
470
 */
471
static struct token *create_token( unsigned int primary, unsigned int session_id, const struct sid *user,
472
                                   const struct sid_attrs *groups, unsigned int group_count,
473
                                   const struct luid_attr *privs, unsigned int priv_count,
474
                                   const struct acl *default_dacl, const struct luid *modified_id,
475
                                   int impersonation_level, int elevation )
476 477
{
    struct token *token = alloc_object( &token_ops );
478 479
    if (token)
    {
480
        unsigned int i;
481

482 483 484 485 486
        allocate_luid( &token->token_id );
        if (modified_id)
            token->modified_id = *modified_id;
        else
            allocate_luid( &token->modified_id );
487
        list_init( &token->privileges );
488
        list_init( &token->groups );
489
        token->primary = primary;
490
        token->session_id = session_id;
491 492 493 494 495
        /* primary tokens don't have impersonation levels */
        if (primary)
            token->impersonation_level = -1;
        else
            token->impersonation_level = impersonation_level;
496
        token->default_dacl = NULL;
497
        token->primary_group = NULL;
498
        token->elevation = elevation;
499

500
        /* copy user */
501
        token->user = memdup( user, sid_len( user ));
502 503 504 505 506
        if (!token->user)
        {
            release_object( token );
            return NULL;
        }
507

508 509 510
        /* copy groups */
        for (i = 0; i < group_count; i++)
        {
511
            size_t size = offsetof( struct group, sid.sub_auth[groups[i].sid->sub_count] );
512
            struct group *group = mem_alloc( size );
513 514 515 516 517 518

            if (!group)
            {
                release_object( token );
                return NULL;
            }
519
            group->attrs = groups[i].attrs;
520
            copy_sid( &group->sid, groups[i].sid );
521
            list_add_tail( &token->groups, &group->entry );
522
            /* Use first owner capable group as owner and primary group */
523
            if (!token->primary_group && (group->attrs & SE_GROUP_OWNER))
524 525
            {
                token->owner = &group->sid;
526
                token->primary_group = &group->sid;
527
            }
528
        }
529

530
        /* copy privileges */
531 532 533 534
        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 */
535
            if (!privilege_add( token, privs[i].luid, privs[i].attrs & SE_PRIVILEGE_ENABLED ))
536 537 538 539 540
            {
                release_object( token );
                return NULL;
            }
        }
541 542 543

        if (default_dacl)
        {
544
            token->default_dacl = memdup( default_dacl, default_dacl->size );
545 546 547 548 549 550
            if (!token->default_dacl)
            {
                release_object( token );
                return NULL;
            }
        }
551
    }
552 553 554
    return token;
}

555
static int filter_group( struct group *group, const struct sid *filter, unsigned int count )
556 557 558 559 560
{
    unsigned int i;

    for (i = 0; i < count; i++)
    {
561 562
        if (equal_sid( &group->sid, filter )) return 1;
        filter = (const struct sid *)((char *)filter + sid_len( filter ));
563 564 565 566 567
    }

    return 0;
}

568
static int filter_privilege( struct privilege *privilege, const struct luid_attr *filter, unsigned int count )
569 570 571 572
{
    unsigned int i;

    for (i = 0; i < count; i++)
573
        if (is_equal_luid( privilege->luid, filter[i].luid )) return 1;
574 575 576 577

    return 0;
}

578
struct token *token_duplicate( struct token *src_token, unsigned primary,
579
                               int impersonation_level, const struct security_descriptor *sd,
580
                               const struct luid_attr *remove_privs, unsigned int remove_priv_count,
581
                               const struct sid *remove_groups, unsigned int remove_group_count)
582
{
583
    const struct luid *modified_id =
584 585 586 587 588 589
        primary || (impersonation_level == src_token->impersonation_level) ?
            &src_token->modified_id : NULL;
    struct token *token = NULL;
    struct privilege *privilege;
    struct group *group;

590 591 592 593
    if (!primary &&
        (impersonation_level < SecurityAnonymous ||
         impersonation_level > SecurityDelegation ||
         (!src_token->primary && (impersonation_level > src_token->impersonation_level))))
594 595 596 597 598
    {
        set_error( STATUS_BAD_IMPERSONATION_LEVEL );
        return NULL;
    }

599
    token = create_token( primary, src_token->session_id, src_token->user, NULL, 0,
600
                          NULL, 0, src_token->default_dacl, modified_id,
601
                          impersonation_level, src_token->elevation );
602 603 604
    if (!token) return token;

    /* copy groups */
605
    token->primary_group = NULL;
606 607
    LIST_FOR_EACH_ENTRY( group, &src_token->groups, struct group, entry )
    {
608
        size_t size = offsetof( struct group, sid.sub_auth[group->sid.sub_count] );
609 610 611 612 613 614 615
        struct group *newgroup = mem_alloc( size );
        if (!newgroup)
        {
            release_object( token );
            return NULL;
        }
        memcpy( newgroup, group, size );
616 617
        if (filter_group( group, remove_groups, remove_group_count ))
        {
618 619
            newgroup->attrs &= ~(SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT);
            newgroup->attrs |= SE_GROUP_USE_FOR_DENY_ONLY;
620
        }
621
        list_add_tail( &token->groups, &newgroup->entry );
622
        if (src_token->primary_group == &group->sid)
623 624
        {
            token->owner = &newgroup->sid;
625
            token->primary_group = &newgroup->sid;
626
        }
627 628 629 630 631
    }
    assert( token->primary_group );

    /* copy privileges */
    LIST_FOR_EACH_ENTRY( privilege, &src_token->privileges, struct privilege, entry )
632 633
    {
        if (filter_privilege( privilege, remove_privs, remove_priv_count )) continue;
634
        if (!privilege_add( token, privilege->luid, privilege->enabled ))
635 636 637 638
        {
            release_object( token );
            return NULL;
        }
639
    }
640

641 642 643
    if (sd) default_set_sd( &token->obj, sd, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
                            DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION );

644 645 646
    return token;
}

647
static struct acl *create_default_dacl( const struct sid *user )
648
{
649
    struct ace *ace;
650
    struct acl *default_dacl;
651
    size_t default_dacl_size = sizeof(*default_dacl) + 2 * sizeof(*ace) +
652
                               sid_len( &local_system_sid ) + sid_len( user );
653 654 655 656

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

657 658 659 660 661
    default_dacl->revision = ACL_REVISION;
    default_dacl->pad1     = 0;
    default_dacl->size     = default_dacl_size;
    default_dacl->count    = 2;
    default_dacl->pad2     = 0;
662 663

    /* GENERIC_ALL for Local System */
664
    ace = set_ace( ace_first( default_dacl ), &local_system_sid, ACCESS_ALLOWED_ACE_TYPE, 0, GENERIC_ALL );
665
    /* GENERIC_ALL for specified user */
666
    set_ace( ace_next( ace ), user, ACCESS_ALLOWED_ACE_TYPE, 0, GENERIC_ALL );
667 668 669 670

    return default_dacl;
}

671 672 673 674 675 676 677
struct sid_data
{
    SID_IDENTIFIER_AUTHORITY idauth;
    int count;
    unsigned int subauth[MAX_SUBAUTH_COUNT];
};

678
static struct security_descriptor *create_security_label_sd( struct token *token, const struct sid *label_sid )
679
{
680
    size_t sid_size = sid_len( label_sid ), sacl_size, sd_size;
681
    struct security_descriptor *sd;
682
    struct acl *sacl;
683

684
    sacl_size = sizeof(*sacl) + sizeof(struct ace) + sid_size;
685 686 687 688 689 690 691 692 693 694
    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;

695 696 697 698 699 700
    sacl = (struct acl *)(sd + 1);
    sacl->revision = ACL_REVISION;
    sacl->pad1     = 0;
    sacl->size     = sacl_size;
    sacl->count    = 1;
    sacl->pad2     = 0;
701

702 703
    set_ace( ace_first( sacl ), label_sid, SYSTEM_MANDATORY_LABEL_ACE_TYPE, 0,
             SYSTEM_MANDATORY_LABEL_NO_WRITE_UP );
704 705 706 707
    assert( sd_is_valid( sd, sd_size ) );
    return sd;
}

708
int token_assign_label( struct token *token, const struct sid *label )
709 710 711 712 713 714 715 716 717 718 719 720 721
{
    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;
}

722 723 724 725 726
struct token *get_token_obj( struct process *process, obj_handle_t handle, unsigned int access )
{
    return (struct token *)get_handle_obj( process, handle, access, &token_ops );
}

727
struct token *token_create_admin( unsigned primary, int impersonation_level, int elevation, unsigned int session_id )
728
{
729
    struct token *token = NULL;
730 731
    struct sid alias_admins_sid = { SID_REVISION, 2, SECURITY_NT_AUTHORITY, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS }};
    struct sid alias_users_sid = { SID_REVISION, 2, SECURITY_NT_AUTHORITY, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS }};
732
    /* on Windows, this value changes every time the user logs on */
733
    struct sid logon_sid = { SID_REVISION, 3, SECURITY_NT_AUTHORITY, { SECURITY_LOGON_IDS_RID, 0, 0 /* FIXME: should be randomly generated when tokens are inherited by new processes */ }};
734
    const struct sid *user_sid = security_unix_uid_to_sid( getuid() );
735
    struct acl *default_dacl = create_default_dacl( user_sid );
736
    const struct luid_attr admin_privs[] =
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
        { SeChangeNotifyPrivilege, SE_PRIVILEGE_ENABLED },
        { SeTcbPrivilege, 0 },
        { SeSecurityPrivilege, 0 },
        { SeBackupPrivilege, 0 },
        { SeRestorePrivilege, 0 },
        { SeSystemtimePrivilege, 0 },
        { SeShutdownPrivilege, 0 },
        { SeRemoteShutdownPrivilege, 0 },
        { SeTakeOwnershipPrivilege, 0 },
        { SeDebugPrivilege, 0 },
        { SeSystemEnvironmentPrivilege, 0 },
        { SeSystemProfilePrivilege, 0 },
        { SeProfileSingleProcessPrivilege, 0 },
        { SeIncreaseBasePriorityPrivilege, 0 },
        { SeLoadDriverPrivilege, SE_PRIVILEGE_ENABLED },
        { 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 struct sid_attrs admin_groups[] =
    {
        { &world_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
        { &local_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
        { &interactive_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
        { &authenticated_user_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
        { &domain_users_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY|SE_GROUP_OWNER },
        { &alias_admins_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY|SE_GROUP_OWNER },
        { &alias_users_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
        { &logon_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY|SE_GROUP_LOGON_ID },
    };

    token = create_token( primary, session_id, user_sid, admin_groups, ARRAY_SIZE( admin_groups ),
                          admin_privs, ARRAY_SIZE( admin_privs ), default_dacl,
                          NULL, impersonation_level, elevation );
    /* we really need a primary group */
    assert( token->primary_group );
779

780
    free( default_dacl );
781
    return token;
782 783
}

784
static struct privilege *token_find_privilege( struct token *token, struct luid luid, int enabled_only )
785 786 787 788
{
    struct privilege *privilege;
    LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
    {
789
        if (is_equal_luid( luid, privilege->luid ))
790 791 792 793 794 795 796 797 798
        {
            if (enabled_only && !privilege->enabled)
                return NULL;
            return privilege;
        }
    }
    return NULL;
}

799 800
static unsigned int token_adjust_privileges( struct token *token, const struct luid_attr *privs,
                                             unsigned int count, struct luid_attr *mod_privs,
801
                                             unsigned int mod_privs_count )
802
{
803
    unsigned int i, modified_count = 0;
804

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

808 809
    for (i = 0; i < count; i++)
    {
810
        struct privilege *privilege = token_find_privilege( token, privs[i].luid, FALSE );
811 812 813 814 815 816
        if (!privilege)
        {
            set_error( STATUS_NOT_ALL_ASSIGNED );
            continue;
        }

817
        if (privs[i].attrs & SE_PRIVILEGE_REMOVED) privilege_remove( privilege );
818 819 820 821 822
        else
        {
            /* save previous state for caller */
            if (mod_privs_count)
            {
823
                *mod_privs++ = luid_and_attr_from_privilege( privilege );
824 825 826
                mod_privs_count--;
                modified_count++;
            }
827
            privilege->enabled = !!(privs[i].attrs & SE_PRIVILEGE_ENABLED);
828 829 830 831 832 833 834 835
        }
    }
    return modified_count;
}

static void token_disable_privileges( struct token *token )
{
    struct privilege *privilege;
836 837 838 839

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

840 841 842 843
    LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
        privilege->enabled = FALSE;
}

844 845
int token_check_privileges( struct token *token, int all_required, const struct luid_attr *reqprivs,
                            unsigned int count, struct luid_attr *usedprivs)
846
{
847
    unsigned int i, enabled_count = 0;
848 849 850

    for (i = 0; i < count; i++)
    {
851
        struct privilege *privilege = token_find_privilege( token, reqprivs[i].luid, TRUE );
852 853 854 855 856 857 858

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

        if (privilege && privilege->enabled)
        {
            enabled_count++;
859
            if (usedprivs) usedprivs[i].attrs |= SE_PRIVILEGE_USED_FOR_ACCESS;
860 861 862 863 864 865 866 867 868
        }
    }

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

869
int token_sid_present( struct token *token, const struct sid *sid, int deny )
870
{
871
    struct group *group;
872

873
    if (equal_sid( token->user, sid )) return TRUE;
874

875
    LIST_FOR_EACH_ENTRY( group, &token->groups, struct group, entry )
876
    {
877 878
        if (!(group->attrs & SE_GROUP_ENABLED)) continue;
        if (!deny && (group->attrs & SE_GROUP_USE_FOR_DENY_ONLY)) continue;
879
        if (equal_sid( &group->sid, sid )) return TRUE;
880 881 882 883 884
    }

    return FALSE;
}

885 886 887 888 889 890
/* 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.
 */
891 892 893
static unsigned int token_access_check( struct token *token,
                                 const struct security_descriptor *sd,
                                 unsigned int desired_access,
894
                                 struct luid_attr *privs,
895
                                 unsigned int *priv_count,
896
                                 const generic_map_t *mapping,
897 898 899 900 901 902
                                 unsigned int *granted_access,
                                 unsigned int *status )
{
    unsigned int current_access = 0;
    unsigned int denied_access = 0;
    ULONG i;
903
    const struct acl *dacl;
904
    int dacl_present;
905
    const struct ace *ace;
906
    const struct sid *owner;
907

908
    /* assume no access rights */
909 910 911 912 913
    *granted_access = 0;

    /* fail if desired_access contains generic rights */
    if (desired_access & (GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE|GENERIC_ALL))
    {
914
        if (priv_count) *priv_count = 0;
915
        return STATUS_GENERIC_NOT_MAPPED;
916 917 918 919 920 921
    }

    dacl = sd_get_dacl( sd, &dacl_present );
    owner = sd_get_owner( sd );
    if (!owner || !sd_get_group( sd ))
    {
922
        if (priv_count) *priv_count = 0;
923
        return STATUS_INVALID_SECURITY_DESCR;
924 925 926
    }

    /* 1: Grant desired access if the object is unprotected */
927
    if (!dacl_present || !dacl)
928
    {
929
        if (priv_count) *priv_count = 0;
930
        if (desired_access & MAXIMUM_ALLOWED)
931
            *granted_access = mapping->all;
932 933
        else
            *granted_access = desired_access;
934
        return *status = STATUS_SUCCESS;
935 936 937 938 939 940
    }

    /* 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)
    {
941 942
        const struct luid_attr security_priv = { SeSecurityPrivilege, 0 };
        struct luid_attr retpriv = security_priv;
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
        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;
963
                return *status = STATUS_SUCCESS;
964 965 966 967
            }
        }
        else
        {
968
            if (priv_count) *priv_count = 0;
969 970
            *status = STATUS_PRIVILEGE_NOT_HELD;
            return STATUS_SUCCESS;
971 972 973 974 975 976 977 978 979 980
        }
    }
    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 ))
    {
981
        current_access |= (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE);
982 983 984
        if (desired_access == current_access)
        {
            *granted_access = current_access;
985
            return *status = STATUS_SUCCESS;
986 987 988 989
        }
    }

    /* 4: Grant rights according to the DACL */
990
    for (i = 0, ace = ace_first( dacl ); i < dacl->count; i++, ace = ace_next( ace ))
991
    {
992
        const struct sid *sid = (const struct sid *)(ace + 1);
993

994
        if (ace->flags & INHERIT_ONLY_ACE) continue;
995

996
        switch (ace->type)
997 998 999 1000
        {
        case ACCESS_DENIED_ACE_TYPE:
            if (token_sid_present( token, sid, TRUE ))
            {
1001
                unsigned int access = map_access( ace->mask, mapping );
1002 1003 1004 1005 1006
                if (desired_access & MAXIMUM_ALLOWED)
                    denied_access |= access;
                else
                {
                    denied_access |= (access & ~current_access);
1007
                    if (desired_access & access) goto done;
1008 1009 1010 1011 1012 1013
                }
            }
            break;
        case ACCESS_ALLOWED_ACE_TYPE:
            if (token_sid_present( token, sid, FALSE ))
            {
1014
                unsigned int access = map_access( ace->mask, mapping );
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
                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;
    }

1029
done:
1030 1031 1032 1033 1034 1035
    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
1036 1037 1038 1039
            *granted_access = 0;

    *status = *granted_access ? STATUS_SUCCESS : STATUS_ACCESS_DENIED;
    return STATUS_SUCCESS;
1040 1041
}

1042
const struct acl *token_get_default_dacl( struct token *token )
1043 1044 1045 1046
{
    return token->default_dacl;
}

1047
const struct sid *token_get_user( struct token *token )
1048
{
1049 1050
    return token->user;
}
1051

1052
const struct sid *token_get_primary_group( struct token *token )
1053 1054
{
    return token->primary_group;
1055 1056
}

1057 1058 1059 1060 1061
unsigned int token_get_session_id( struct token *token )
{
    return token->session_id;
}

1062
int check_object_access(struct token *token, struct object *obj, unsigned int *access)
1063
{
1064
    generic_map_t mapping;
1065
    unsigned int status;
1066 1067
    int res;

1068 1069 1070
    if (!token)
        token = current->token ? current->token : current->process->token;

1071
    mapping.all = obj->ops->map_access( obj, GENERIC_ALL );
1072 1073 1074

    if (!obj->sd)
    {
1075
        if (*access & MAXIMUM_ALLOWED) *access = mapping.all;
1076 1077 1078
        return TRUE;
    }

1079 1080 1081
    mapping.read  = obj->ops->map_access( obj, GENERIC_READ );
    mapping.write = obj->ops->map_access( obj, GENERIC_WRITE );
    mapping.exec = obj->ops->map_access( obj, GENERIC_EXECUTE );
1082

1083
    res = token_access_check( token, obj->sd, *access, NULL, NULL,
1084 1085 1086 1087 1088 1089 1090 1091
                              &mapping, access, &status ) == STATUS_SUCCESS &&
          status == STATUS_SUCCESS;

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


1092 1093 1094
/* open a security token */
DECL_HANDLER(open_token)
{
1095
    if (req->flags & OPEN_TOKEN_THREAD)
1096 1097 1098 1099 1100
    {
        struct thread *thread = get_thread_from_handle( req->handle, 0 );
        if (thread)
        {
            if (thread->token)
1101
            {
1102
                if (!thread->token->primary && thread->token->impersonation_level <= SecurityAnonymous)
1103 1104 1105 1106 1107
                    set_error( STATUS_CANT_OPEN_ANONYMOUS );
                else
                    reply->token = alloc_handle( current->process, thread->token,
                                                 req->access, req->attributes );
            }
1108
            else
1109
                set_error( STATUS_NO_TOKEN );
1110 1111 1112 1113 1114 1115 1116 1117 1118
            release_object( thread );
        }
    }
    else
    {
        struct process *process = get_process_from_handle( req->handle, 0 );
        if (process)
        {
            if (process->token)
1119
                reply->token = alloc_handle( current->process, process->token, req->access,
1120
                                             req->attributes );
1121
            else
1122
                set_error( STATUS_NO_TOKEN );
1123 1124 1125 1126
            release_object( process );
        }
    }
}
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

/* 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 )))
    {
1139 1140 1141
        const struct luid_attr *privs = get_req_data();
        struct luid_attr *modified_privs = NULL;
        unsigned int priv_count = get_req_data_size() / sizeof(*privs);
1142 1143 1144 1145
        unsigned int modified_priv_count = 0;

        if (req->get_modified_state && !req->disable_all)
        {
1146
            unsigned int i;
1147 1148 1149
            /* count modified privs */
            for (i = 0; i < priv_count; i++)
            {
1150
                struct privilege *privilege = token_find_privilege( token, privs[i].luid, FALSE );
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
                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
1164
            token_adjust_privileges( token, privs, priv_count, modified_privs, modified_priv_count );
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179

        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;
1180
        struct luid_attr *privs;
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
        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)
                LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
1192
                    *privs++ = luid_and_attr_from_privilege( privilege );
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        }
        else
            set_error(STATUS_BUFFER_TOO_SMALL);

        release_object( token );
    }
}

/* creates a duplicate of the token */
DECL_HANDLER(duplicate_token)
{
    struct token *src_token;
1205 1206 1207 1208 1209
    struct unicode_str name;
    const struct security_descriptor *sd;
    const struct object_attributes *objattr = get_req_object_attributes( &sd, &name, NULL );

    if (!objattr) return;
1210

1211 1212 1213 1214
    if ((src_token = (struct token *)get_handle_obj( current->process, req->handle,
                                                     TOKEN_DUPLICATE,
                                                     &token_ops )))
    {
1215
        struct token *token = token_duplicate( src_token, req->primary, req->impersonation_level, sd, NULL, 0, NULL, 0 );
1216 1217
        if (token)
        {
1218 1219
            unsigned int access = req->access ? req->access : get_handle_access( current->process, req->handle );
            reply->new_handle = alloc_handle_no_access_check( current->process, token, access, objattr->attributes );
1220 1221 1222 1223 1224
            release_object( token );
        }
        release_object( src_token );
    }
}
1225

1226 1227 1228 1229 1230 1231 1232
/* creates a restricted version of a token */
DECL_HANDLER(filter_token)
{
    struct token *src_token;

    if ((src_token = (struct token *)get_handle_obj( current->process, req->handle, TOKEN_DUPLICATE, &token_ops )))
    {
1233
        const struct luid_attr *filter_privileges = get_req_data();
1234
        unsigned int priv_count, group_count;
1235
        const struct sid *filter_groups;
1236 1237
        struct token *token;

1238
        priv_count = min( req->privileges_size, get_req_data_size() ) / sizeof(struct luid_attr);
1239
        filter_groups = (const struct sid *)((char *)filter_privileges + priv_count * sizeof(struct luid_attr));
1240
        group_count = get_sid_count( filter_groups, get_req_data_size() - priv_count * sizeof(struct luid_attr) );
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

        token = token_duplicate( src_token, src_token->primary, src_token->impersonation_level, NULL,
                                 filter_privileges, priv_count, filter_groups, group_count );
        if (token)
        {
            unsigned int access = get_handle_access( current->process, req->handle );
            reply->new_handle = alloc_handle_no_access_check( current->process, token, access, 0 );
            release_object( token );
        }
        release_object( src_token );
    }
}

1254 1255 1256 1257 1258 1259 1260 1261 1262
/* 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 )))
    {
1263
        unsigned int count = get_req_data_size() / sizeof(struct luid_attr);
1264 1265 1266

        if (!token->primary && token->impersonation_level <= SecurityAnonymous)
            set_error( STATUS_BAD_IMPERSONATION_LEVEL );
1267
        else if (get_reply_max_size() >= count * sizeof(struct luid_attr))
1268
        {
1269
            struct luid_attr *usedprivs = set_reply_data_size( count * sizeof(*usedprivs) );
1270 1271 1272 1273 1274 1275 1276
            reply->has_privileges = token_check_privileges( token, req->all_required, get_req_data(), count, usedprivs );
        }
        else
            set_error( STATUS_BUFFER_OVERFLOW );
        release_object( token );
    }
}
1277 1278 1279 1280 1281

/* checks that a user represented by a token is allowed to access an object
 * represented by a security descriptor */
DECL_HANDLER(access_check)
{
1282
    data_size_t sd_size = get_req_data_size();
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    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 )))
    {
        unsigned int status;
1297
        struct luid_attr priv;
1298 1299 1300 1301
        unsigned int priv_count = 1;

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

1302 1303 1304 1305 1306 1307 1308
        /* only impersonation tokens may be used with this function */
        if (token->primary)
        {
            set_error( STATUS_NO_IMPERSONATION_TOKEN );
            release_object( token );
            return;
        }
1309 1310 1311 1312 1313 1314 1315
        /* anonymous impersonation tokens can't be used */
        if (token->impersonation_level <= SecurityAnonymous)
        {
            set_error( STATUS_BAD_IMPERSONATION_LEVEL );
            release_object( token );
            return;
        }
1316

1317 1318
        status = token_access_check( token, sd, req->desired_access, &priv, &priv_count, &req->mapping,
                                     &reply->access_granted, &reply->access_status );
1319

1320
        reply->privileges_len = priv_count*sizeof(struct luid_attr);
1321 1322 1323

        if ((priv_count > 0) && (reply->privileges_len <= get_reply_max_size()))
        {
1324
            struct luid_attr *privs = set_reply_data_size( priv_count * sizeof(*privs) );
1325 1326 1327
            memcpy( privs, &priv, sizeof(priv) );
        }

1328
        set_error( status );
1329 1330 1331
        release_object( token );
    }
}
1332

1333
/* retrieves an SID from the token */
1334
DECL_HANDLER(get_token_sid)
1335 1336 1337
{
    struct token *token;

1338
    reply->sid_len = 0;
1339

1340
    if ((token = (struct token *)get_handle_obj( current->process, req->handle, TOKEN_QUERY, &token_ops )))
1341
    {
1342
        const struct sid *sid = NULL;
1343

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
        switch (req->which_sid)
        {
        case TokenUser:
            assert(token->user);
            sid = token->user;
            break;
        case TokenPrimaryGroup:
            sid = token->primary_group;
            break;
        case TokenOwner:
1354
            sid = token->owner;
1355 1356 1357 1358
            break;
        default:
            set_error( STATUS_INVALID_PARAMETER );
            break;
1359 1360
        }

1361 1362
        if (sid)
        {
1363
            reply->sid_len = sid_len( sid );
1364 1365 1366
            if (reply->sid_len <= get_reply_max_size()) set_reply_data( sid, reply->sid_len );
            else set_error( STATUS_BUFFER_TOO_SMALL );
        }
1367 1368 1369
        release_object( token );
    }
}
1370 1371 1372 1373 1374 1375

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

1376
    if ((token = (struct token *)get_handle_obj( current->process, req->handle, TOKEN_QUERY, &token_ops )))
1377 1378 1379 1380 1381 1382
    {
        unsigned int group_count = 0;
        const struct group *group;

        LIST_FOR_EACH_ENTRY( group, &token->groups, const struct group, entry )
        {
1383
            if (req->attr_mask && !(group->attrs & req->attr_mask)) continue;
1384
            group_count++;
1385
            reply->sid_len += sid_len( &group->sid );
1386
        }
1387
        reply->attr_len = sizeof(unsigned int) * group_count;
1388

1389
        if (reply->attr_len + reply->sid_len <= get_reply_max_size())
1390
        {
1391 1392
            unsigned int *attr_ptr = set_reply_data_size( reply->attr_len + reply->sid_len );
            struct sid *sid = (struct sid *)(attr_ptr + group_count);
1393

1394 1395
            if (attr_ptr)
            {
1396 1397
                LIST_FOR_EACH_ENTRY( group, &token->groups, const struct group, entry )
                {
1398
                    if (req->attr_mask && !(group->attrs & req->attr_mask)) continue;
1399
                    sid = copy_sid( sid, &group->sid );
1400
                    *attr_ptr++ = group->attrs;
1401 1402 1403 1404 1405 1406 1407 1408
                }
            }
        }
        else set_error( STATUS_BUFFER_TOO_SMALL );

        release_object( token );
    }
}
1409

1410
DECL_HANDLER(get_token_info)
1411 1412 1413
{
    struct token *token;

1414
    if ((token = (struct token *)get_handle_obj( current->process, req->handle, TOKEN_QUERY, &token_ops )))
1415 1416 1417
    {
        reply->token_id = token->token_id;
        reply->modified_id = token->modified_id;
1418
        reply->session_id = token->session_id;
1419 1420
        reply->primary = token->primary;
        reply->impersonation_level = token->impersonation_level;
1421
        reply->elevation = token->elevation;
1422 1423 1424 1425 1426
        reply->group_count = list_count( &token->groups );
        reply->privilege_count = list_count( &token->privileges );
        release_object( token );
    }
}
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438

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)
1439
            reply->acl_len = token->default_dacl->size;
1440 1441 1442

        if (reply->acl_len <= get_reply_max_size())
        {
1443
            struct acl *acl_reply = set_reply_data_size( reply->acl_len );
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
            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;
1456 1457 1458 1459 1460 1461 1462 1463
    const struct acl *acl = get_req_data();
    unsigned int acl_size = get_req_data_size();

    if (acl_size && !acl_is_valid( acl, acl_size ))
    {
        set_error( STATUS_INVALID_ACL );
        return;
    }
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_ADJUST_DEFAULT,
                                                 &token_ops )))
    {
        free( token->default_dacl );
        token->default_dacl = NULL;

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

        release_object( token );
    }
}
1478

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
DECL_HANDLER(create_linked_token)
{
    struct token *token, *linked;
    int elevation;

    if ((token = (struct token *)get_handle_obj( current->process, req->handle,
                                                 TOKEN_QUERY, &token_ops )))
    {
        switch (token->elevation)
        {
        case TokenElevationTypeFull:
            elevation = TokenElevationTypeLimited;
            break;
        case TokenElevationTypeLimited:
            elevation = TokenElevationTypeFull;
            break;
        default:
            release_object( token );
            return;
        }
1499
        if ((linked = token_create_admin( FALSE, SecurityIdentification, elevation, token->session_id )))
1500 1501 1502 1503 1504 1505 1506
        {
            reply->linked = alloc_handle( current->process, linked, TOKEN_ALL_ACCESS, 0 );
            release_object( linked );
        }
        release_object( token );
    }
}