security.c 186 KB
Newer Older
1 2 3 4
/*
 * Unit tests for security functions
 *
 * Copyright (c) 2004 Mike McCormack
5
 * Copyright (c) 2011 Dmitry Timoshkov
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21
 */

22
#include <stdarg.h>
23 24
#include <stdio.h>

25 26
#include "ntstatus.h"
#define WIN32_NO_STATUS
27 28 29
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
30
#include "aclapi.h"
31
#include "winnt.h"
32
#include "sddl.h"
33
#include "ntsecapi.h"
34
#include "lmcons.h"
35 36

#include "wine/test.h"
37

38 39 40
/* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
#define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)

41 42 43 44
#ifndef EVENT_QUERY_STATE
#define EVENT_QUERY_STATE 0x0001
#endif

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/* copied from Wine winternl.h - not included in the Windows SDK */
typedef enum _OBJECT_INFORMATION_CLASS {
    ObjectBasicInformation,
    ObjectNameInformation,
    ObjectTypeInformation,
    ObjectAllInformation,
    ObjectDataInformation
} OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;

typedef struct _OBJECT_BASIC_INFORMATION {
    ULONG  Attributes;
    ACCESS_MASK  GrantedAccess;
    ULONG  HandleCount;
    ULONG  PointerCount;
    ULONG  PagedPoolUsage;
    ULONG  NonPagedPoolUsage;
    ULONG  Reserved[3];
    ULONG  NameInformationLength;
    ULONG  TypeInformationLength;
    ULONG  SecurityDescriptorLength;
    LARGE_INTEGER  CreateTime;
} OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;

68 69
#define expect_eq(expr, value, type, format) { type ret = expr; ok((value) == ret, #expr " expected " format "  got " format "\n", (value), (ret)); }

70 71 72
static BOOL (WINAPI *pAddAccessAllowedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
static BOOL (WINAPI *pAddAccessDeniedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
static BOOL (WINAPI *pAddAuditAccessAceEx)(PACL, DWORD, DWORD, DWORD, PSID, BOOL, BOOL);
73 74 75
static VOID (WINAPI *pBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
static VOID (WINAPI *pBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
static VOID (WINAPI *pBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
76 77 78 79 80
                                                          POBJECTS_AND_NAME_A pObjName,
                                                          SE_OBJECT_TYPE ObjectType,
                                                          LPSTR ObjectTypeName,
                                                          LPSTR InheritedObjectTypeName,
                                                          LPSTR Name );
81
static VOID (WINAPI *pBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
82 83 84 85
                                                         POBJECTS_AND_SID pObjSid,
                                                         GUID* pObjectGuid,
                                                         GUID* pInheritedObjectGuid,
                                                         PSID pSid );
86 87 88 89
static LPSTR (WINAPI *pGetTrusteeNameA)( PTRUSTEEA pTrustee );
static BOOL (WINAPI *pMakeSelfRelativeSD)( PSECURITY_DESCRIPTOR, PSECURITY_DESCRIPTOR, LPDWORD );
static BOOL (WINAPI *pConvertSidToStringSidA)( PSID pSid, LPSTR *str );
static BOOL (WINAPI *pConvertStringSidToSidA)( LPCSTR str, PSID pSid );
90
static BOOL (WINAPI *pCheckTokenMembership)(HANDLE, PSID, PBOOL);
91 92
static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
                                                                            PSECURITY_DESCRIPTOR*, PULONG );
93 94
static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorW)(LPCWSTR, DWORD,
                                                                            PSECURITY_DESCRIPTOR*, PULONG );
95 96
static BOOL (WINAPI *pConvertSecurityDescriptorToStringSecurityDescriptorA)(PSECURITY_DESCRIPTOR, DWORD,
                                                                            SECURITY_INFORMATION, LPSTR *, PULONG );
97
static BOOL (WINAPI *pGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
98
                                          PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
99
static BOOL (WINAPI *pSetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
100
                                          PSECURITY_DESCRIPTOR);
101 102 103
static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
                                              PSID*, PSID*, PACL*, PACL*,
                                              PSECURITY_DESCRIPTOR*);
104 105 106
static PDWORD (WINAPI *pGetSidSubAuthority)(PSID, DWORD);
static PUCHAR (WINAPI *pGetSidSubAuthorityCount)(PSID);
static BOOL (WINAPI *pIsValidSid)(PSID);
107 108 109
static DWORD (WINAPI *pRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
static BOOL (WINAPI *pCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
110
                                        SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
111

112 113 114 115
static NTSTATUS (WINAPI *pLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
static NTSTATUS (WINAPI *pLsaClose)(LSA_HANDLE);
static NTSTATUS (WINAPI *pLsaFreeMemory)(PVOID);
static NTSTATUS (WINAPI *pLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
116
static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
117
static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
118
static DWORD (WINAPI *pSetEntriesInAclA)(ULONG, PEXPLICIT_ACCESSA, PACL, PACL*);
119 120
static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
                                                    SECURITY_DESCRIPTOR_CONTROL);
121 122
static DWORD (WINAPI *pGetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
                                        PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
123 124
static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
                                         PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
125 126
static BOOL (WINAPI *pCreateRestrictedToken)(HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD,
                                             PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
127

128
static HMODULE hmod;
129 130
static int     myARGC;
static char**  myARGV;
131

132 133 134 135 136
struct sidRef
{
    SID_IDENTIFIER_AUTHORITY auth;
    const char *refStr;
};
137

138 139
static void init(void)
{
140 141 142 143
    HMODULE hntdll;

    hntdll = GetModuleHandleA("ntdll.dll");
    pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
144
    pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
145

146
    hmod = GetModuleHandle("advapi32.dll");
147 148 149
    pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
    pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
    pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
150
    pCheckTokenMembership = (void *)GetProcAddress(hmod, "CheckTokenMembership");
151 152
    pConvertStringSecurityDescriptorToSecurityDescriptorA =
        (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
153 154
    pConvertStringSecurityDescriptorToSecurityDescriptorW =
        (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
155 156
    pConvertSecurityDescriptorToStringSecurityDescriptorA =
        (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
157 158 159
    pGetFileSecurityA = (void *)GetProcAddress(hmod, "GetFileSecurityA" );
    pSetFileSecurityA = (void *)GetProcAddress(hmod, "SetFileSecurityA" );
    pCreateWellKnownSid = (void *)GetProcAddress( hmod, "CreateWellKnownSid" );
160
    pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
161 162 163
    pGetSidSubAuthority = (void *)GetProcAddress(hmod, "GetSidSubAuthority");
    pGetSidSubAuthorityCount = (void *)GetProcAddress(hmod, "GetSidSubAuthorityCount");
    pIsValidSid = (void *)GetProcAddress(hmod, "IsValidSid");
164
    pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
165
    pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
166
    pSetEntriesInAclA = (void *)GetProcAddress(hmod, "SetEntriesInAclA");
167
    pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
168
    pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
169
    pCreateRestrictedToken = (void *)GetProcAddress(hmod, "CreateRestrictedToken");
170 171
    pConvertSidToStringSidA = (void *)GetProcAddress(hmod, "ConvertSidToStringSidA");
    pConvertStringSidToSidA = (void *)GetProcAddress(hmod, "ConvertStringSidToSidA");
172

173
    myARGC = winetest_get_mainargs( &myARGV );
174 175
}

176
static void test_str_sid(const char *str_sid)
177 178 179 180 181 182 183 184 185 186 187
{
    PSID psid;
    char *temp;

    if (pConvertStringSidToSidA(str_sid, &psid))
    {
        if (pConvertSidToStringSidA(psid, &temp))
        {
            trace(" %s: %s\n", str_sid, temp);
            LocalFree(temp);
        }
188
        LocalFree(psid);
189 190
    }
    else
191 192
    {
        if (GetLastError() != ERROR_INVALID_SID)
193
            trace(" %s: couldn't be converted, returned %d\n", str_sid, GetLastError());
194 195 196
        else
            trace(" %s: couldn't be converted\n", str_sid);
    }
197 198
}

Mike McCormack's avatar
Mike McCormack committed
199
static void test_sid(void)
200
{
201 202 203 204 205 206 207 208 209 210 211
    struct sidRef refs[] = {
     { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
     { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1"  },
     { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1"     },
     { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1"       },
     { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1"         },
     { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1"        },
    };
    const char noSubAuthStr[] = "S-1-5";
    unsigned int i;
    PSID psid = NULL;
212
    SID *pisid;
213
    BOOL r;
214
    LPSTR str = NULL;
215

216 217 218
    if( !pConvertSidToStringSidA || !pConvertStringSidToSidA )
    {
        win_skip("ConvertSidToStringSidA or ConvertStringSidToSidA not available\n");
219
        return;
220
    }
221

222 223 224
    r = pConvertStringSidToSidA( NULL, NULL );
    ok( !r, "expected failure with NULL parameters\n" );
    if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
225
        return;
226
    ok( GetLastError() == ERROR_INVALID_PARAMETER,
227
     "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
228 229 230 231
     GetLastError() );

    r = pConvertStringSidToSidA( refs[0].refStr, NULL );
    ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
232
     "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
233 234 235 236
     GetLastError() );

    r = pConvertStringSidToSidA( NULL, &str );
    ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
237
     "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
238 239 240 241 242 243
     GetLastError() );

    r = pConvertStringSidToSidA( noSubAuthStr, &psid );
    ok( !r,
     "expected failure with no sub authorities\n" );
    ok( GetLastError() == ERROR_INVALID_SID,
244
     "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
245 246
     GetLastError() );

247
    ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
248
    pisid = psid;
249
    ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
250 251
    ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expected 21, got %d\n", pisid->SubAuthority[0]);
    ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expected 4576, got %d\n", pisid->SubAuthority[3]);
252
    LocalFree(str);
253
    LocalFree(psid);
254

255 256 257 258 259 260 261 262 263
    for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
    {
        PISID pisid;

        r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
         &psid );
        ok( r, "failed to allocate sid\n" );
        r = pConvertSidToStringSidA( psid, &str );
        ok( r, "failed to convert sid\n" );
264 265 266 267
        if (r)
        {
            ok( !strcmp( str, refs[i].refStr ),
                "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
268
            LocalFree( str );
269
        }
270 271 272 273 274
        if( psid )
            FreeSid( psid );

        r = pConvertStringSidToSidA( refs[i].refStr, &psid );
        ok( r, "failed to parse sid string\n" );
275
        pisid = psid;
276 277 278 279
        ok( pisid &&
         !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
         sizeof(refs[i].auth) ),
         "string sid %s didn't parse to expected value\n"
280
         "(got 0x%04x%08x, expected 0x%04x%08x)\n",
281 282 283 284 285 286 287 288 289 290 291 292 293
         refs[i].refStr,
         MAKEWORD( pisid->IdentifierAuthority.Value[1],
         pisid->IdentifierAuthority.Value[0] ),
         MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
         pisid->IdentifierAuthority.Value[4] ),
         MAKEWORD( pisid->IdentifierAuthority.Value[3],
         pisid->IdentifierAuthority.Value[2] ) ),
         MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
         MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
         MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
        if( psid )
            LocalFree( psid );
    }
294

295
    trace("String SIDs:\n");
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    test_str_sid("AO");
    test_str_sid("RU");
    test_str_sid("AN");
    test_str_sid("AU");
    test_str_sid("BA");
    test_str_sid("BG");
    test_str_sid("BO");
    test_str_sid("BU");
    test_str_sid("CA");
    test_str_sid("CG");
    test_str_sid("CO");
    test_str_sid("DA");
    test_str_sid("DC");
    test_str_sid("DD");
    test_str_sid("DG");
    test_str_sid("DU");
    test_str_sid("EA");
    test_str_sid("ED");
    test_str_sid("WD");
    test_str_sid("PA");
    test_str_sid("IU");
    test_str_sid("LA");
    test_str_sid("LG");
    test_str_sid("LS");
    test_str_sid("SY");
    test_str_sid("NU");
    test_str_sid("NO");
    test_str_sid("NS");
    test_str_sid("PO");
    test_str_sid("PS");
    test_str_sid("PU");
    test_str_sid("RS");
    test_str_sid("RD");
    test_str_sid("RE");
    test_str_sid("RC");
    test_str_sid("SA");
    test_str_sid("SO");
    test_str_sid("SU");
334 335
}

Mike McCormack's avatar
Mike McCormack committed
336
static void test_trustee(void)
337
{
338 339 340 341 342
    GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
    GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
    GUID ZeroGuid;
    OBJECTS_AND_NAME_ oan;
    OBJECTS_AND_SID oas;
343 344
    TRUSTEE trustee;
    PSID psid;
345 346 347
    char szObjectTypeName[] = "ObjectTypeName";
    char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
    char szTrusteeName[] = "szTrusteeName";
348
    SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
349 350

    memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
351

352 353 354 355 356
    pBuildTrusteeWithSidA = (void *)GetProcAddress( hmod, "BuildTrusteeWithSidA" );
    pBuildTrusteeWithNameA = (void *)GetProcAddress( hmod, "BuildTrusteeWithNameA" );
    pBuildTrusteeWithObjectsAndNameA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
    pBuildTrusteeWithObjectsAndSidA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
    pGetTrusteeNameA = (void *)GetProcAddress (hmod, "GetTrusteeNameA" );
357 358 359
    if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
        !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
        !pGetTrusteeNameA )
360 361
        return;

362 363 364 365 366
    if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
    {
        trace( "failed to init SID\n" );
       return;
    }
367

368
    /* test BuildTrusteeWithSidA */
369
    memset( &trustee, 0xff, sizeof trustee );
370
    pBuildTrusteeWithSidA( &trustee, psid );
371 372 373 374 375 376

    ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
        "MultipleTrusteeOperation wrong\n");
    ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
    ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
377
    ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
378 379 380 381 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

    /* test BuildTrusteeWithObjectsAndSidA (test 1) */
    memset( &trustee, 0xff, sizeof trustee );
    memset( &oas, 0xff, sizeof(oas) );
    pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
                                    &InheritedObjectType, psid);

    ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
    ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
    ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
    ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
 
    ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
    ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
    ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
    ok(oas.pSid == psid, "pSid wrong\n");

    /* test GetTrusteeNameA */
    ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");

    /* test BuildTrusteeWithObjectsAndSidA (test 2) */
    memset( &trustee, 0xff, sizeof trustee );
    memset( &oas, 0xff, sizeof(oas) );
    pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
                                    &InheritedObjectType, psid);

    ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
    ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
    ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
    ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
 
    ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
    ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
    ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
    ok(oas.pSid == psid, "pSid wrong\n");

416
    FreeSid( psid );
417

418 419
    /* test BuildTrusteeWithNameA */
    memset( &trustee, 0xff, sizeof trustee );
420
    pBuildTrusteeWithNameA( &trustee, szTrusteeName );
421 422 423 424 425 426

    ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
        "MultipleTrusteeOperation wrong\n");
    ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
    ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );

    /* test BuildTrusteeWithObjectsAndNameA (test 1) */
    memset( &trustee, 0xff, sizeof trustee );
    memset( &oan, 0xff, sizeof(oan) );
    pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
                                     szInheritedObjectTypeName, szTrusteeName);

    ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
    ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
    ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
    ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
 
    ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
    ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
    ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
    ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");

    /* test GetTrusteeNameA */
    ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");

    /* test BuildTrusteeWithObjectsAndNameA (test 2) */
    memset( &trustee, 0xff, sizeof trustee );
    memset( &oan, 0xff, sizeof(oan) );
    pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
                                     szInheritedObjectTypeName, szTrusteeName);

    ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
    ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
    ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
    ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
 
    ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
    ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
    ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
    ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");

    /* test BuildTrusteeWithObjectsAndNameA (test 3) */
    memset( &trustee, 0xff, sizeof trustee );
    memset( &oan, 0xff, sizeof(oan) );
    pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
                                     NULL, szTrusteeName);

    ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
    ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
    ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
    ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
    ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
 
    ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
    ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
    ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
    ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
482 483
}
 
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
/* If the first isn't defined, assume none is */
#ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
#define SE_MIN_WELL_KNOWN_PRIVILEGE       2L
#define SE_CREATE_TOKEN_PRIVILEGE         2L
#define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE   3L
#define SE_LOCK_MEMORY_PRIVILEGE          4L
#define SE_INCREASE_QUOTA_PRIVILEGE       5L
#define SE_MACHINE_ACCOUNT_PRIVILEGE      6L
#define SE_TCB_PRIVILEGE                  7L
#define SE_SECURITY_PRIVILEGE             8L
#define SE_TAKE_OWNERSHIP_PRIVILEGE       9L
#define SE_LOAD_DRIVER_PRIVILEGE         10L
#define SE_SYSTEM_PROFILE_PRIVILEGE      11L
#define SE_SYSTEMTIME_PRIVILEGE          12L
#define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
#define SE_INC_BASE_PRIORITY_PRIVILEGE   14L
#define SE_CREATE_PAGEFILE_PRIVILEGE     15L
#define SE_CREATE_PERMANENT_PRIVILEGE    16L
#define SE_BACKUP_PRIVILEGE              17L
#define SE_RESTORE_PRIVILEGE             18L
#define SE_SHUTDOWN_PRIVILEGE            19L
#define SE_DEBUG_PRIVILEGE               20L
#define SE_AUDIT_PRIVILEGE               21L
#define SE_SYSTEM_ENVIRONMENT_PRIVILEGE  22L
508
#define SE_CHANGE_NOTIFY_PRIVILEGE       23L
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
#define SE_REMOTE_SHUTDOWN_PRIVILEGE     24L
#define SE_UNDOCK_PRIVILEGE              25L
#define SE_SYNC_AGENT_PRIVILEGE          26L
#define SE_ENABLE_DELEGATION_PRIVILEGE   27L
#define SE_MANAGE_VOLUME_PRIVILEGE       28L
#define SE_IMPERSONATE_PRIVILEGE         29L
#define SE_CREATE_GLOBAL_PRIVILEGE       30L
#define SE_MAX_WELL_KNOWN_PRIVILEGE      SE_CREATE_GLOBAL_PRIVILEGE
#endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */

static void test_allocateLuid(void)
{
    BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
    LUID luid1, luid2;
    BOOL ret;

525
    pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
526 527 528 529 530 531 532
    if (!pAllocateLocallyUniqueId) return;

    ret = pAllocateLocallyUniqueId(&luid1);
    if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
        return;

    ok(ret,
533
     "AllocateLocallyUniqueId failed: %d\n", GetLastError());
534 535
    ret = pAllocateLocallyUniqueId(&luid2);
    ok( ret,
536
     "AllocateLocallyUniqueId failed: %d\n", GetLastError());
537 538 539 540
    ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
     "AllocateLocallyUniqueId returned a well-known LUID\n");
    ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
     "AllocateLocallyUniqueId returned non-unique LUIDs\n");
541 542
    ret = pAllocateLocallyUniqueId(NULL);
    ok( !ret && GetLastError() == ERROR_NOACCESS,
543
     "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
544 545 546 547 548
     GetLastError());
}

static void test_lookupPrivilegeName(void)
{
Mike McCormack's avatar
Mike McCormack committed
549
    BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
550 551 552 553 554 555 556
    char buf[MAX_PATH]; /* arbitrary, seems long enough */
    DWORD cchName = sizeof(buf);
    LUID luid = { 0, 0 };
    LONG i;
    BOOL ret;

    /* check whether it's available first */
557
    pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
558 559 560 561 562 563 564 565 566
    if (!pLookupPrivilegeNameA) return;
    luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
    ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
    if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
        return;

    /* check with a short buffer */
    cchName = 0;
    luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
567 568
    ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
    ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
569
     "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
570 571 572
     GetLastError());
    ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
     "LookupPrivilegeNameA returned an incorrect required length for\n"
573
     "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
574
     lstrlenA("SeCreateTokenPrivilege") + 1);
575 576 577 578 579
    /* check a known value and its returned length on success */
    cchName = sizeof(buf);
    ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
     cchName == strlen("SeCreateTokenPrivilege"),
     "LookupPrivilegeNameA returned an incorrect output length for\n"
580
     "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
Vincent Béron's avatar
Vincent Béron committed
581
     (int)strlen("SeCreateTokenPrivilege"));
582
    /* check known values */
583
    for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
584 585 586
    {
        luid.LowPart = i;
        cchName = sizeof(buf);
587
        ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
Jakob Eriksson's avatar
Jakob Eriksson committed
588
        ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
589
         "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
590 591 592 593
    }
    /* check a bogus LUID */
    luid.LowPart = 0xdeadbeef;
    cchName = sizeof(buf);
594 595
    ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
    ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
596
     "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
597 598 599 600
     GetLastError());
    /* check on a bogus system */
    luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
    cchName = sizeof(buf);
601
    ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
602 603 604
    ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
                 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
     "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
605 606 607 608 609 610
     GetLastError());
}

struct NameToLUID
{
    const char *name;
611
    DWORD lowPart;
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
};

static void test_lookupPrivilegeValue(void)
{
    static const struct NameToLUID privs[] = {
     { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
     { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
     { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
     { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
     { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
     { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
     { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
     { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
     { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
     { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
     { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
     { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
     { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
     { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
     { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
     { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
     { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
     { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
     { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
     { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
     { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
638
     { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
639 640 641 642 643 644 645 646 647
     { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
     { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
     { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
     { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
     { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
     { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
     { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
    };
    BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
648
    unsigned int i;
649 650 651 652
    LUID luid;
    BOOL ret;

    /* check whether it's available first */
653
    pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
654 655 656 657 658 659
    if (!pLookupPrivilegeValueA) return;
    ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
    if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
        return;

    /* check a bogus system name */
660
    ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
661 662 663
    ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
                GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
     "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
664 665
     GetLastError());
    /* check a NULL string */
666 667
    ret = pLookupPrivilegeValueA(NULL, 0, &luid);
    ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
668
     "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
669 670
     GetLastError());
    /* check a bogus privilege name */
671 672
    ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
    ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
673
     "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
674 675
     GetLastError());
    /* check case insensitive */
676 677
    ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
    ok( ret,
678
     "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
     GetLastError());
    for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
    {
        /* Not all privileges are implemented on all Windows versions, so
         * don't worry if the call fails
         */
        if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
        {
            ok(luid.LowPart == privs[i].lowPart,
             "LookupPrivilegeValueA returned an invalid LUID for %s\n",
             privs[i].name);
        }
    }
}

static void test_luid(void)
{
    test_allocateLuid();
    test_lookupPrivilegeName();
    test_lookupPrivilegeValue();
}

701 702
static void test_FileSecurity(void)
{
703 704 705
    char wintmpdir [MAX_PATH];
    char path [MAX_PATH];
    char file [MAX_PATH];
706 707 708 709
    HANDLE fh, token;
    DWORD sdSize, retSize, rc, granted, priv_set_len;
    PRIVILEGE_SET priv_set;
    BOOL status;
710
    BYTE *sd;
711
    GENERIC_MAPPING mapping = { FILE_READ_DATA, FILE_WRITE_DATA, FILE_EXECUTE, FILE_ALL_ACCESS };
712
    const SECURITY_INFORMATION request = OWNER_SECURITY_INFORMATION
713 714 715 716 717
                                       | GROUP_SECURITY_INFORMATION
                                       | DACL_SECURITY_INFORMATION;

    if (!pGetFileSecurityA) {
        win_skip ("GetFileSecurity is not available\n");
718
        return;
719
    }
720

721 722
    if (!pSetFileSecurityA) {
        win_skip ("SetFileSecurity is not available\n");
723 724 725
        return;
    }

726 727 728 729
    if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
        win_skip ("GetTempPathA failed\n");
        return;
    }
730

731 732
    /* Create a temporary directory and in it a temporary file */
    strcat (strcpy (path, wintmpdir), "rary");
733
    SetLastError(0xdeadbeef);
734 735 736 737 738
    rc = CreateDirectoryA (path, NULL);
    ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
        "failed for '%s' with %d\n", path, GetLastError());

    strcat (strcpy (file, path), "\\ess");
739
    SetLastError(0xdeadbeef);
740 741 742 743 744 745 746 747 748
    fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
        "failed for '%s' with %d\n", file, GetLastError());
    CloseHandle (fh);

    /* For the temporary file ... */

    /* Get size needed */
    retSize = 0;
749
    SetLastError(0xdeadbeef);
750
    rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
751 752 753 754
    if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
        win_skip("GetFileSecurityA is not implemented\n");
        goto cleanup;
    }
755 756 757 758
    ok (!rc, "GetFileSecurityA "
        "was expected to fail for '%s'\n", file);
    ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
        "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
759
    ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
760 761 762 763 764

    sdSize = retSize;
    sd = HeapAlloc (GetProcessHeap (), 0, sdSize);

    /* Get security descriptor for real */
765
    retSize = -1;
766
    SetLastError(0xdeadbeef);
767 768
    rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
    ok (rc, "GetFileSecurityA "
769
        "was not expected to fail '%s': %d\n", file, GetLastError());
770 771 772
    ok (retSize == sdSize ||
        broken(retSize == 0), /* NT4 */
        "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
773 774

    /* Use it to set security descriptor */
775
    SetLastError(0xdeadbeef);
776 777
    rc = pSetFileSecurityA (file, request, sd);
    ok (rc, "SetFileSecurityA "
778
        "was not expected to fail '%s': %d\n", file, GetLastError());
779 780 781

    HeapFree (GetProcessHeap (), 0, sd);

782 783 784 785
    /* Repeat for the temporary directory ... */

    /* Get size needed */
    retSize = 0;
786
    SetLastError(0xdeadbeef);
787 788 789 790 791
    rc = pGetFileSecurityA (path, request, NULL, 0, &retSize);
    ok (!rc, "GetFileSecurityA "
        "was expected to fail for '%s'\n", path);
    ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
        "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
792
    ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
793 794 795 796 797

    sdSize = retSize;
    sd = HeapAlloc (GetProcessHeap (), 0, sdSize);

    /* Get security descriptor for real */
798
    retSize = -1;
799
    SetLastError(0xdeadbeef);
800 801
    rc = pGetFileSecurityA (path, request, sd, sdSize, &retSize);
    ok (rc, "GetFileSecurityA "
802
        "was not expected to fail '%s': %d\n", path, GetLastError());
803 804 805
    ok (retSize == sdSize ||
        broken(retSize == 0), /* NT4 */
        "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
806 807

    /* Use it to set security descriptor */
808
    SetLastError(0xdeadbeef);
809 810
    rc = pSetFileSecurityA (path, request, sd);
    ok (rc, "SetFileSecurityA "
811
        "was not expected to fail '%s': %d\n", path, GetLastError());
812 813
    HeapFree (GetProcessHeap (), 0, sd);

814 815
    /* Old test */
    strcpy (wintmpdir, "\\Should not exist");
816
    SetLastError(0xdeadbeef);
817 818
    rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
    ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
819 820 821 822 823 824 825
    ok (GetLastError() == ERROR_FILE_NOT_FOUND,
        "last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());

cleanup:
    /* Remove temporary file and directory */
    DeleteFileA(file);
    RemoveDirectoryA(path);
826

827
    /* Test file access permissions for a file with FILE_ATTRIBUTE_ARCHIVE */
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
    SetLastError(0xdeadbeef);
    rc = GetTempPath(sizeof(wintmpdir), wintmpdir);
    ok(rc, "GetTempPath error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    rc = GetTempFileName(wintmpdir, "tmp", 0, file);
    ok(rc, "GetTempFileName error %d\n", GetLastError());

    rc = GetFileAttributes(file);
    rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
    ok(rc == FILE_ATTRIBUTE_ARCHIVE, "expected FILE_ATTRIBUTE_ARCHIVE got %#x\n", rc);

    retSize = 0xdeadbeef;
    rc = GetFileSecurity(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
                         NULL, 0, &sdSize);
    ok(!rc, "GetFileSecurity should fail\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER got %d\n", GetLastError());
    ok(sdSize > sizeof(SECURITY_DESCRIPTOR), "got sd size %d\n", sdSize);

    sd = HeapAlloc(GetProcessHeap (), 0, sdSize);
    retSize = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = GetFileSecurity(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
                         sd, sdSize, &retSize);
    ok(rc, "GetFileSecurity error %d\n", GetLastError());
854
    ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896

    SetLastError(0xdeadbeef);
    rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
    ok(!rc, "OpenThreadToken should fail\n");
    ok(GetLastError() == ERROR_NO_TOKEN, "expected ERROR_NO_TOKEN, got %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    rc = ImpersonateSelf(SecurityIdentification);
    ok(rc, "ImpersonateSelf error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
    ok(rc, "OpenThreadToken error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    rc = RevertToSelf();
    ok(rc, "RevertToSelf error %d\n", GetLastError());

    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);

    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);

    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
897

898 899 900 901 902 903 904 905
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == DELETE, "expected DELETE, got %#x\n", granted);

906 907 908 909 910 911 912
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
913

914 915 916 917 918 919 920
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
921

922 923 924 925 926 927 928
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
929

930 931 932 933 934
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, 0xffffffff, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(!rc, "AccessCheck should fail\n");
    ok(GetLastError() == ERROR_GENERIC_NOT_MAPPED, "expected ERROR_GENERIC_NOT_MAPPED, got %d\n", GetLastError());

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    /* Test file access permissions for a file with FILE_ATTRIBUTE_READONLY */
    SetLastError(0xdeadbeef);
    fh = CreateFile(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
    ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
    retSize = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = WriteFile(fh, "1", 1, &retSize, NULL);
    ok(!rc, "WriteFile should fail\n");
    ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
    ok(retSize == 0, "expected 0, got %d\n", retSize);
    CloseHandle(fh);

    rc = GetFileAttributes(file);
    rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
todo_wine
    ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
       "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);

    SetLastError(0xdeadbeef);
    rc = SetFileAttributes(file, FILE_ATTRIBUTE_ARCHIVE);
    ok(rc, "SetFileAttributes error %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    rc = DeleteFile(file);
    ok(rc, "DeleteFile error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    fh = CreateFile(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
    ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
    retSize = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = WriteFile(fh, "1", 1, &retSize, NULL);
    ok(!rc, "WriteFile should fail\n");
    ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
    ok(retSize == 0, "expected 0, got %d\n", retSize);
    CloseHandle(fh);

    rc = GetFileAttributes(file);
    rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
    ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
       "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);

    retSize = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = GetFileSecurity(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
                         sd, sdSize, &retSize);
    ok(rc, "GetFileSecurity error %d\n", GetLastError());
    ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);

    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);

    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
}
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
1008

1009 1010 1011 1012 1013 1014 1015 1016 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 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
}
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
}
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
}
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
    ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
}
    SetLastError(0xdeadbeef);
    rc = DeleteFile(file);
    ok(!rc, "DeleteFile should fail\n");
    ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    rc = SetFileAttributes(file, FILE_ATTRIBUTE_ARCHIVE);
    ok(rc, "SetFileAttributes error %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    rc = DeleteFile(file);
    ok(rc, "DeleteFile error %d\n", GetLastError());

1056
    CloseHandle(token);
1057
    HeapFree(GetProcessHeap(), 0, sd);
1058 1059
}

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
static void test_AccessCheck(void)
{
    PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
    PACL Acl = NULL;
    SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
    GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
    ACCESS_MASK Access;
    BOOL AccessStatus;
    HANDLE Token;
1071
    HANDLE ProcessToken;
1072 1073 1074 1075
    BOOL ret;
    DWORD PrivSetLen;
    PRIVILEGE_SET *PrivSet;
    BOOL res;
1076 1077
    HMODULE NtDllModule;
    BOOLEAN Enabled;
1078
    DWORD err;
1079
    NTSTATUS ntret, ntAccessStatus;
1080 1081 1082 1083

    NtDllModule = GetModuleHandle("ntdll.dll");
    if (!NtDllModule)
    {
1084
        skip("not running on NT, skipping test\n");
1085 1086
        return;
    }
1087
    pRtlAdjustPrivilege = (void *)GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
1088 1089
    if (!pRtlAdjustPrivilege)
    {
1090
        win_skip("missing RtlAdjustPrivilege, skipping test\n");
1091 1092
        return;
    }
1093

1094 1095 1096 1097
    Acl = HeapAlloc(GetProcessHeap(), 0, 256);
    res = InitializeAcl(Acl, 256, ACL_REVISION);
    if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
1098
        skip("ACLs not implemented - skipping tests\n");
1099
        HeapFree(GetProcessHeap(), 0, Acl);
1100 1101
        return;
    }
1102
    ok(res, "InitializeAcl failed with error %d\n", GetLastError());
1103

1104
    res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
1105
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1106 1107 1108

    res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
1109
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1110 1111 1112

    res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
1113
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1114 1115 1116 1117

    SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);

    res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1118
    ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
1119 1120

    res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1121
    ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1122 1123 1124 1125 1126

    PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
    PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
    PrivSet->PrivilegeCount = 16;

1127 1128
    res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
    ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
1129

1130 1131
    pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);

1132
    res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
1133
    ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1134

1135 1136
    /* SD without owner/group */
    SetLastError(0xdeadbeef);
1137
    Access = AccessStatus = 0x1abe11ed;
1138 1139 1140 1141 1142
    ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
       "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
1143
    ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
       "Access and/or AccessStatus were changed!\n");

    /* Set owner and group */
    res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
    ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
    res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
    ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());

    /* Generic access mask */
    SetLastError(0xdeadbeef);
1154
    Access = AccessStatus = 0x1abe11ed;
1155 1156 1157 1158 1159
    ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
       "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
1160
    ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1161 1162
       "Access and/or AccessStatus were changed!\n");

1163 1164
    /* Generic access mask - no privilegeset buffer */
    SetLastError(0xdeadbeef);
1165
    Access = AccessStatus = 0x1abe11ed;
1166 1167 1168 1169 1170
    ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                      NULL, &PrivSetLen, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
       "with ERROR_NOACCESS, instead of %d\n", err);
1171
    ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1172 1173 1174 1175
       "Access and/or AccessStatus were changed!\n");

    /* Generic access mask - no returnlength */
    SetLastError(0xdeadbeef);
1176
    Access = AccessStatus = 0x1abe11ed;
1177 1178 1179 1180 1181
    ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                      PrivSet, NULL, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
       "with ERROR_NOACCESS, instead of %d\n", err);
1182
    ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1183 1184 1185 1186
       "Access and/or AccessStatus were changed!\n");

    /* Generic access mask - no privilegeset buffer, no returnlength */
    SetLastError(0xdeadbeef);
1187
    Access = AccessStatus = 0x1abe11ed;
1188 1189 1190 1191 1192
    ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                      NULL, NULL, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
       "with ERROR_NOACCESS, instead of %d\n", err);
1193
    ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1194 1195
       "Access and/or AccessStatus were changed!\n");

1196
    /* sd with no dacl present */
1197
    Access = AccessStatus = 0x1abe11ed;
1198 1199 1200 1201 1202 1203 1204 1205 1206
    ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
    ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
    ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
    ok(AccessStatus && (Access == KEY_READ),
        "AccessCheck failed to grant access with error %d\n",
        GetLastError());

1207 1208
    /* sd with no dacl present - no privilegeset buffer */
    SetLastError(0xdeadbeef);
1209
    Access = AccessStatus = 0x1abe11ed;
1210 1211 1212 1213 1214
    ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                      NULL, &PrivSetLen, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
       "with ERROR_NOACCESS, instead of %d\n", err);
1215
    ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1216 1217 1218 1219 1220 1221
       "Access and/or AccessStatus were changed!\n");

    if(pNtAccessCheck)
    {
       /* Generic access mask - no privilegeset buffer */
       SetLastError(0xdeadbeef);
1222
       Access = ntAccessStatus = 0x1abe11ed;
1223 1224 1225 1226 1227 1228 1229
       ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                              NULL, &PrivSetLen, &Access, &ntAccessStatus);
       err = GetLastError();
       ok(ntret == STATUS_ACCESS_VIOLATION,
          "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
       ok(err == 0xdeadbeef,
          "NtAccessCheck shouldn't set last error, got %d\n", err);
1230
       ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1231 1232 1233 1234
          "Access and/or AccessStatus were changed!\n");

      /* Generic access mask - no returnlength */
      SetLastError(0xdeadbeef);
1235
      Access = ntAccessStatus = 0x1abe11ed;
1236 1237 1238 1239 1240 1241 1242
      ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                             PrivSet, NULL, &Access, &ntAccessStatus);
      err = GetLastError();
      ok(ntret == STATUS_ACCESS_VIOLATION,
         "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
      ok(err == 0xdeadbeef,
         "NtAccessCheck shouldn't set last error, got %d\n", err);
1243
      ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1244 1245 1246 1247
         "Access and/or AccessStatus were changed!\n");

      /* Generic access mask - no privilegeset buffer, no returnlength */
      SetLastError(0xdeadbeef);
1248
      Access = ntAccessStatus = 0x1abe11ed;
1249 1250 1251 1252 1253 1254 1255
      ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
                             NULL, NULL, &Access, &ntAccessStatus);
      err = GetLastError();
      ok(ntret == STATUS_ACCESS_VIOLATION,
         "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
      ok(err == 0xdeadbeef,
         "NtAccessCheck shouldn't set last error, got %d\n", err);
1256
      ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1257 1258 1259 1260 1261
         "Access and/or AccessStatus were changed!\n");
    }
    else
       win_skip("NtAccessCheck unavailable. Skipping.\n");

1262
    /* sd with NULL dacl */
1263
    Access = AccessStatus = 0x1abe11ed;
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
    ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
    ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
    ok(AccessStatus && (Access == KEY_READ),
        "AccessCheck failed to grant access with error %d\n",
        GetLastError());

    /* sd with blank dacl */
    ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
    ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
    ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
    err = GetLastError();
    ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
       "with ERROR_ACCESS_DENIED, instead of %d\n", err);
    ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);

    res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
1285
    ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1286 1287 1288 1289 1290

    res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
    ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());

    /* sd with dacl */
1291
    Access = AccessStatus = 0x1abe11ed;
1292 1293
    ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
1294
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1295
    ok(AccessStatus && (Access == KEY_READ),
1296
        "AccessCheck failed to grant access with error %d\n",
1297 1298 1299 1300
        GetLastError());

    ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
1301
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1302
    ok(AccessStatus,
1303
        "AccessCheck failed to grant any access with error %d\n",
1304
        GetLastError());
1305
    trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
1306

1307 1308
    /* Access denied by SD */
    SetLastError(0xdeadbeef);
1309
    Access = AccessStatus = 0x1abe11ed;
1310 1311 1312 1313 1314 1315 1316 1317
    ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
    err = GetLastError();
    ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
       "with ERROR_ACCESS_DENIED, instead of %d\n", err);
    ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);

1318 1319 1320 1321 1322
    SetLastError(0);
    PrivSet->PrivilegeCount = 16;
    ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
1323
        "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
1324 1325
        GetLastError());

1326 1327
    ret = ImpersonateLoggedOnUser(Token);
    ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1328 1329 1330 1331 1332 1333 1334 1335
    ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
    if (!ret)
    {
        SetLastError(0);
        PrivSet->PrivilegeCount = 16;
        ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
                          PrivSet, &PrivSetLen, &Access, &AccessStatus);
        ok(ret && AccessStatus && GetLastError() == 0,
1336
            "AccessCheck should have succeeded, error %d\n",
1337 1338
            GetLastError());
        ok(Access == ACCESS_SYSTEM_SECURITY,
1339
            "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1340 1341 1342
            Access);
    }
    else
1343
        trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1344
            ret);
1345 1346
    ret = RevertToSelf();
    ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1347

1348 1349 1350
    /* test INHERIT_ONLY_ACE */
    ret = InitializeAcl(Acl, 256, ACL_REVISION);
    ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360

    /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
     * the next ones.
     */
    if (pAddAccessAllowedAceEx)
    {
        ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
        ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
    }
    else
1361
        win_skip("AddAccessAllowedAceEx is not available\n");
1362 1363 1364 1365 1366 1367 1368 1369 1370

    ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    ok(ret, "AccessCheck failed with error %d\n", GetLastError());
    err = GetLastError();
    ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
       "with ERROR_ACCESS_DENIED, instead of %d\n", err);
    ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    CloseHandle(Token);

    res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
    ok(res, "DuplicateToken failed with error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
       "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);

    CloseHandle(Token);

    SetLastError(0xdeadbeef);
    ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
                      PrivSet, &PrivSetLen, &Access, &AccessStatus);
    err = GetLastError();
    ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
       "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);

    CloseHandle(ProcessToken);
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

    if (EveryoneSid)
        FreeSid(EveryoneSid);
    if (AdminSid)
        FreeSid(AdminSid);
    if (UsersSid)
        FreeSid(UsersSid);
    HeapFree(GetProcessHeap(), 0, Acl);
    HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
    HeapFree(GetProcessHeap(), 0, PrivSet);
}

1405 1406 1407
/* test GetTokenInformation for the various attributes */
static void test_token_attr(void)
{
1408
    HANDLE Token, ImpersonationToken;
1409
    DWORD Size, Size2;
1410 1411 1412
    TOKEN_PRIVILEGES *Privileges;
    TOKEN_GROUPS *Groups;
    TOKEN_USER *User;
1413
    TOKEN_DEFAULT_DACL *Dacl;
1414
    BOOL ret;
1415 1416
    DWORD i, GLE;
    LPSTR SidString;
1417
    SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1418
    ACL *acl;
1419

1420
    /* cygwin-like use case */
1421
    SetLastError(0xdeadbeef);
1422
    ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1423 1424
    if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
    {
1425
        win_skip("OpenProcessToken is not implemented\n");
1426 1427
        return;
    }
1428 1429 1430
    ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
    if (ret)
    {
1431
        DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1432 1433
        Size = sizeof(buf);
        ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1434
        ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1435 1436 1437 1438
        Size = sizeof(ImpersonationLevel);
        ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
        GLE = GetLastError();
        ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1439 1440 1441
        CloseHandle(Token);
    }

1442
    if(!pConvertSidToStringSidA)
Paul Vriens's avatar
Paul Vriens committed
1443
    {
1444
        win_skip("ConvertSidToStringSidA is not available\n");
1445
        return;
Paul Vriens's avatar
Paul Vriens committed
1446
    }
1447

1448
    SetLastError(0xdeadbeef);
1449
    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1450
    ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1451 1452

    /* groups */
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
    /* insufficient buffer length */
    SetLastError(0xdeadbeef);
    Size2 = 0;
    ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size2);
    ok(Size2 > 1, "got %d\n", Size2);
    ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
        "%d with error %d\n", ret, GetLastError());
    Size2 -= 1;
    Groups = HeapAlloc(GetProcessHeap(), 0, Size2);
    memset(Groups, 0xcc, Size2);
    Size = 0;
    ret = GetTokenInformation(Token, TokenGroups, Groups, Size2, &Size);
    ok(Size > 1, "got %d\n", Size);
1466
    ok((!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER) || broken(ret) /* wow64 */,
1467
        "%d with error %d\n", ret, GetLastError());
1468 1469 1470
    if(!ret)
        ok(*((BYTE*)Groups) == 0xcc, "buffer altered\n");

1471 1472
    HeapFree(GetProcessHeap(), 0, Groups);

1473
    SetLastError(0xdeadbeef);
1474
    ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1475 1476 1477
    ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
        "GetTokenInformation(TokenGroups) %s with error %d\n",
        ret ? "succeeded" : "failed", GetLastError());
1478
    Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1479
    SetLastError(0xdeadbeef);
1480
    ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1481
    ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1482 1483 1484
    ok(GetLastError() == 0xdeadbeef,
       "GetTokenInformation shouldn't have set last error to %d\n",
       GetLastError());
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    trace("TokenGroups:\n");
    for (i = 0; i < Groups->GroupCount; i++)
    {
        DWORD NameLength = 255;
        TCHAR Name[255];
        DWORD DomainLength = 255;
        TCHAR Domain[255];
        SID_NAME_USE SidNameUse;
        Name[0] = '\0';
        Domain[0] = '\0';
        ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1496
        if (ret)
1497
        {
1498
            pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1499 1500 1501 1502
            trace("%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
            LocalFree(SidString);
        }
        else trace("attr: 0x%08x LookupAccountSid failed with error %d\n", Groups->Groups[i].Attributes, GetLastError());
1503
    }
1504
    HeapFree(GetProcessHeap(), 0, Groups);
1505 1506 1507 1508

    /* user */
    ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
    ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1509
        "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1510 1511 1512
    User = HeapAlloc(GetProcessHeap(), 0, Size);
    ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
    ok(ret,
1513
        "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1514

1515
    pConvertSidToStringSidA(User->User.Sid, &SidString);
1516
    trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1517
    LocalFree(SidString);
1518
    HeapFree(GetProcessHeap(), 0, User);
1519 1520 1521 1522

    /* privileges */
    ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
    ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1523
        "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1524 1525 1526
    Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
    ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
    ok(ret,
1527
        "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1528 1529 1530 1531 1532 1533
    trace("TokenPrivileges:\n");
    for (i = 0; i < Privileges->PrivilegeCount; i++)
    {
        TCHAR Name[256];
        DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
        LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1534
        trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1535
    }
1536
    HeapFree(GetProcessHeap(), 0, Privileges);
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

    ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
    ok(ret, "DuplicateToken failed with error %d\n", GetLastError());

    Size = sizeof(ImpersonationLevel);
    ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
    ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
    ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);

    CloseHandle(ImpersonationToken);
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

    /* default dacl */
    ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
    ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
        "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());

    Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
    ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
    ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
    GLE = GetLastError();
    ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
    ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);

    SetLastError(0xdeadbeef);
    ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
    GLE = GetLastError();
    ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
    ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);

    acl = Dacl->DefaultDacl;
    Dacl->DefaultDacl = NULL;

    ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
    ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");

    Size2 = 0;
    Dacl->DefaultDacl = (ACL *)0xdeadbeef;
    ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
    ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
    ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
1580
    ok(Size2 == sizeof(TOKEN_DEFAULT_DACL) || broken(Size2 == 2*sizeof(TOKEN_DEFAULT_DACL)), /* WoW64 */
1581
       "got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
1582 1583 1584 1585 1586

    Dacl->DefaultDacl = acl;
    ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
    ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());

1587 1588 1589 1590 1591
    if (Size2 == sizeof(TOKEN_DEFAULT_DACL)) {
        ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
        ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
    } else
        win_skip("TOKEN_DEFAULT_DACL size too small on WoW64\n");
1592 1593

    HeapFree(GetProcessHeap(), 0, Dacl);
1594
    CloseHandle(Token);
1595 1596
}

1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
typedef union _MAX_SID
{
    SID sid;
    char max[SECURITY_MAX_SID_SIZE];
} MAX_SID;

static void test_sid_str(PSID * sid)
{
    char *str_sid;
    BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
1607
    ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
1608 1609 1610 1611 1612 1613 1614 1615
    if (ret)
    {
        char account[MAX_PATH], domain[MAX_PATH];
        SID_NAME_USE use;
        DWORD acc_size = MAX_PATH;
        DWORD dom_size = MAX_PATH;
        ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
        ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
1616
           "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
1617 1618 1619
        if (ret)
            trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
        else if (GetLastError() == ERROR_NONE_MAPPED)
1620
            trace(" %s couldn't be mapped\n", str_sid);
1621 1622 1623 1624
        LocalFree(str_sid);
    }
}

1625
static const struct well_known_sid_value
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
{
    BOOL without_domain;
    const char *sid_string;
} well_known_sid_values[] = {
/*  0 */ {TRUE, "S-1-0-0"},  {TRUE, "S-1-1-0"},  {TRUE, "S-1-2-0"},  {TRUE, "S-1-3-0"},
/*  4 */ {TRUE, "S-1-3-1"},  {TRUE, "S-1-3-2"},  {TRUE, "S-1-3-3"},  {TRUE, "S-1-5"},
/*  8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"},  {TRUE, "S-1-5-3"},  {TRUE, "S-1-5-4"},
/* 12 */ {TRUE, "S-1-5-6"},  {TRUE, "S-1-5-7"},  {TRUE, "S-1-5-8"},  {TRUE, "S-1-5-9"},
/* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
/* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL},      {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
/* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
/* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
/* 29 */ {TRUE, "S-1-5-32-547"},  {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
/* 32 */ {TRUE, "S-1-5-32-550"},  {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
/* 35 */ {TRUE, "S-1-5-32-554"},  {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
/* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
/* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
/* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
/* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
/* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
/* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
/* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
1648
/* Added in Windows Server 2003 */
1649 1650 1651
/* 51 */ {TRUE, "S-1-5-64-10"},   {TRUE, "S-1-5-64-21"},   {TRUE, "S-1-5-64-14"},
/* 54 */ {TRUE, "S-1-5-15"},      {TRUE, "S-1-5-1000"},    {FALSE, "S-1-5-32-557"},
/* 57 */ {TRUE, "S-1-5-32-558"},  {TRUE, "S-1-5-32-559"},  {TRUE, "S-1-5-32-560"},
1652
/* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
1653
/* Added in Windows Vista: */
1654
/* 62 */ {TRUE, "S-1-5-32-568"},
1655 1656 1657 1658
/* 63 */ {TRUE, "S-1-5-17"},      {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
/* 66 */ {TRUE, "S-1-16-4096"},   {TRUE, "S-1-16-8192"},   {TRUE, "S-1-16-12288"},
/* 69 */ {TRUE, "S-1-16-16384"},  {TRUE, "S-1-5-33"},      {TRUE, "S-1-3-4"},
/* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"},  {FALSE, "S-1-5-21-12-23-34-45-56-572"},
1659 1660
/* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"},
/* 77 */ {FALSE, "S-1-5-21-12-23-34-45-56-498"}, {TRUE, "S-1-5-32-574"}, {TRUE, "S-1-16-8448"}
1661 1662
};

1663
static void test_CreateWellKnownSid(void)
1664 1665
{
    SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1666 1667 1668
    PSID domainsid, sid;
    DWORD size, error;
    BOOL ret;
1669
    unsigned int i;
1670 1671 1672

    if (!pCreateWellKnownSid)
    {
1673
        win_skip("CreateWellKnownSid not available\n");
1674 1675 1676
        return;
    }

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
    size = 0;
    SetLastError(0xdeadbeef);
    ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
    error = GetLastError();
    ok(!ret, "CreateWellKnownSid succeeded\n");
    ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
    ok(size, "expected size > 0\n");

    SetLastError(0xdeadbeef);
    ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
    error = GetLastError();
    ok(!ret, "CreateWellKnownSid succeeded\n");
    ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);

    sid = HeapAlloc(GetProcessHeap(), 0, size);
    ret = pCreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
    ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, sid);

1696 1697 1698 1699 1700
    /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
    AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);

    for (i = 0; i < sizeof(well_known_sid_values)/sizeof(well_known_sid_values[0]); i++)
    {
1701
        const struct well_known_sid_value *value = &well_known_sid_values[i];
1702 1703 1704 1705
        char sid_buffer[SECURITY_MAX_SID_SIZE];
        LPSTR str;
        DWORD cb;

1706
        if (value->sid_string == NULL)
1707 1708
            continue;

1709
        if (i > WinAccountRasAndIasServersSid)
1710 1711 1712 1713 1714
        {
            /* These SIDs aren't implemented by all Windows versions - detect it and break the loop */
            cb = sizeof(sid_buffer);
            if (!pCreateWellKnownSid(i, domainsid, sid_buffer, &cb))
            {
1715
                skip("Well known SIDs starting from %u are not implemented\n", i);
1716 1717 1718 1719 1720
                break;
            }
        }

        cb = sizeof(sid_buffer);
1721
        ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %u\n", i);
1722 1723
        expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
        ok(IsValidSid(sid_buffer), "The sid is not valid\n");
1724
        ok(pConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
1725
        ok(strcmp(str, value->sid_string) == 0, "%d: SID mismatch - expected %s, got %s\n", i,
1726 1727
            value->sid_string, str);
        LocalFree(str);
1728 1729 1730 1731 1732

        if (value->without_domain)
        {
            char buf2[SECURITY_MAX_SID_SIZE];
            cb = sizeof(buf2);
1733
            ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %u with optional domain\n", i);
1734
            expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1735
            ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%u)\n", i);
1736
        }
1737
    }
1738

1739
    FreeSid(domainsid);
1740 1741
}

1742 1743 1744
static void test_LookupAccountSid(void)
{
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1745 1746
    CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
    DWORD acc_sizeA, dom_sizeA, user_sizeA;
1747 1748 1749 1750
    DWORD real_acc_sizeA, real_dom_sizeA;
    WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
    DWORD acc_sizeW, dom_sizeW;
    DWORD real_acc_sizeW, real_dom_sizeW;
1751 1752 1753
    PSID pUsersSid = NULL;
    SID_NAME_USE use;
    BOOL ret;
1754
    DWORD error, size, cbti = 0;
1755
    MAX_SID  max_sid;
1756
    CHAR *str_sidA;
1757
    int i;
1758 1759
    HANDLE hToken;
    PTOKEN_USER ptiUser = NULL;
1760 1761 1762 1763 1764

    /* native windows crashes if account size, domain size, or name use is NULL */

    ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
1765
    ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
1766
       "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1767 1768 1769 1770

    /* not running on NT so give up */
    if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
        return;
1771

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
    real_acc_sizeA = MAX_PATH;
    real_dom_sizeA = MAX_PATH;
    ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
    ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");

    /* try NULL account */
    acc_sizeA = MAX_PATH;
    dom_sizeA = MAX_PATH;
    ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
    ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");

    /* try NULL domain */
    acc_sizeA = MAX_PATH;
    dom_sizeA = MAX_PATH;
    ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
    ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");

    /* try a small account buffer */
    acc_sizeA = 1;
    dom_sizeA = MAX_PATH;
    accountA[0] = 0;
    ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
    ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1796
       "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1797 1798 1799 1800 1801

    /* try a 0 sized account buffer */
    acc_sizeA = 0;
    dom_sizeA = MAX_PATH;
    accountA[0] = 0;
1802
    LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1803 1804
    /* this can fail or succeed depending on OS version but the size will always be returned */
    ok(acc_sizeA == real_acc_sizeA + 1,
1805
       "LookupAccountSidA() Expected acc_size = %u, got %u\n",
1806 1807 1808 1809 1810
       real_acc_sizeA + 1, acc_sizeA);

    /* try a 0 sized account buffer */
    acc_sizeA = 0;
    dom_sizeA = MAX_PATH;
1811
    LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1812 1813
    /* this can fail or succeed depending on OS version but the size will always be returned */
    ok(acc_sizeA == real_acc_sizeA + 1,
1814
       "LookupAccountSid() Expected acc_size = %u, got %u\n",
1815 1816 1817 1818 1819 1820 1821 1822 1823
       real_acc_sizeA + 1, acc_sizeA);

    /* try a small domain buffer */
    dom_sizeA = 1;
    acc_sizeA = MAX_PATH;
    accountA[0] = 0;
    ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
    ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1824
       "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1825 1826 1827 1828 1829

    /* try a 0 sized domain buffer */
    dom_sizeA = 0;
    acc_sizeA = MAX_PATH;
    accountA[0] = 0;
1830
    LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1831 1832
    /* this can fail or succeed depending on OS version but the size will always be returned */
    ok(dom_sizeA == real_dom_sizeA + 1,
1833
       "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1834 1835 1836 1837 1838
       real_dom_sizeA + 1, dom_sizeA);

    /* try a 0 sized domain buffer */
    dom_sizeA = 0;
    acc_sizeA = MAX_PATH;
1839
    LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1840 1841
    /* this can fail or succeed depending on OS version but the size will always be returned */
    ok(dom_sizeA == real_dom_sizeA + 1,
1842
       "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1843 1844 1845 1846 1847 1848
       real_dom_sizeA + 1, dom_sizeA);

    real_acc_sizeW = MAX_PATH;
    real_dom_sizeW = MAX_PATH;
    ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
    ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
1849

1850 1851 1852 1853 1854
    /* try an invalid system name */
    real_acc_sizeA = MAX_PATH;
    real_dom_sizeA = MAX_PATH;
    ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
    ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1855 1856
    ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
       "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
1857

1858
    /* native windows crashes if domainW or accountW is NULL */
1859

1860
    /* try a small account buffer */
1861 1862 1863 1864 1865 1866
    acc_sizeW = 1;
    dom_sizeW = MAX_PATH;
    accountW[0] = 0;
    ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
    ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1867
       "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1868 1869

    /* try a 0 sized account buffer */
1870 1871 1872
    acc_sizeW = 0;
    dom_sizeW = MAX_PATH;
    accountW[0] = 0;
1873
    LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1874
    /* this can fail or succeed depending on OS version but the size will always be returned */
1875
    ok(acc_sizeW == real_acc_sizeW + 1,
1876
       "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1877
       real_acc_sizeW + 1, acc_sizeW);
1878 1879

    /* try a 0 sized account buffer */
1880 1881
    acc_sizeW = 0;
    dom_sizeW = MAX_PATH;
1882
    LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1883
    /* this can fail or succeed depending on OS version but the size will always be returned */
1884
    ok(acc_sizeW == real_acc_sizeW + 1,
1885
       "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1886
       real_acc_sizeW + 1, acc_sizeW);
1887 1888

    /* try a small domain buffer */
1889 1890 1891 1892 1893 1894
    dom_sizeW = 1;
    acc_sizeW = MAX_PATH;
    accountW[0] = 0;
    ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
    ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1895
       "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1896 1897

    /* try a 0 sized domain buffer */
1898 1899 1900
    dom_sizeW = 0;
    acc_sizeW = MAX_PATH;
    accountW[0] = 0;
1901
    LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1902
    /* this can fail or succeed depending on OS version but the size will always be returned */
1903
    ok(dom_sizeW == real_dom_sizeW + 1,
1904
       "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1905
       real_dom_sizeW + 1, dom_sizeW);
1906 1907

    /* try a 0 sized domain buffer */
1908 1909
    dom_sizeW = 0;
    acc_sizeW = MAX_PATH;
1910
    LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1911
    /* this can fail or succeed depending on OS version but the size will always be returned */
1912
    ok(dom_sizeW == real_dom_sizeW + 1,
1913
       "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1914
       real_dom_sizeW + 1, dom_sizeW);
1915

1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
    acc_sizeW = dom_sizeW = use = 0;
    SetLastError(0xdeadbeef);
    ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, NULL, &dom_sizeW, &use);
    error = GetLastError();
    ok(!ret, "LookupAccountSidW failed %u\n", GetLastError());
    ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
    ok(acc_sizeW, "expected non-zero account size\n");
    ok(dom_sizeW, "expected non-zero domain size\n");
    ok(!use, "expected zero use %u\n", use);

1926 1927
    FreeSid(pUsersSid);

1928 1929 1930
    /* Test LookupAccountSid with Sid retrieved from token information.
     This assumes this process is running under the account of the current user.*/
    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
1931
    ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1932
    ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
1933
    ok(!ret, "GetTokenInformation failed with error %d\n", GetLastError());
1934
    ptiUser = HeapAlloc(GetProcessHeap(), 0, cbti);
1935 1936 1937 1938 1939 1940 1941 1942
    if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
    {
        acc_sizeA = dom_sizeA = MAX_PATH;
        ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
        ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
        user_sizeA = MAX_PATH;
        ret = GetUserNameA(usernameA , &user_sizeA);
        ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
1943
        ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
1944 1945 1946
    }
    HeapFree(GetProcessHeap(), 0, ptiUser);

1947 1948 1949 1950 1951 1952 1953 1954
    if (pCreateWellKnownSid && pConvertSidToStringSidA)
    {
        trace("Well Known SIDs:\n");
        for (i = 0; i <= 60; i++)
        {
            size = SECURITY_MAX_SID_SIZE;
            if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
            {
1955
                if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1956
                {
1957 1958 1959 1960 1961
                    acc_sizeA = MAX_PATH;
                    dom_sizeA = MAX_PATH;
                    if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
                        trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
                    LocalFree(str_sidA);
1962 1963 1964
                }
            }
            else
1965 1966
            {
                if (GetLastError() != ERROR_INVALID_PARAMETER)
1967
                    trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1968 1969 1970
                else
                    trace(" %d: not supported\n", i);
            }
1971 1972
        }

1973 1974 1975 1976
        pLsaQueryInformationPolicy = (void *)GetProcAddress( hmod, "LsaQueryInformationPolicy");
        pLsaOpenPolicy = (void *)GetProcAddress( hmod, "LsaOpenPolicy");
        pLsaFreeMemory = (void *)GetProcAddress( hmod, "LsaFreeMemory");
        pLsaClose = (void *)GetProcAddress( hmod, "LsaClose");
1977 1978 1979 1980 1981 1982 1983 1984

        if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
        {
            NTSTATUS status;
            LSA_HANDLE handle;
            LSA_OBJECT_ATTRIBUTES object_attributes;

            ZeroMemory(&object_attributes, sizeof(object_attributes));
1985
            object_attributes.Length = sizeof(object_attributes);
1986 1987

            status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1988
            ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1989
               "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1990 1991 1992 1993 1994

            /* try a more restricted access mask if necessary */
            if (status == STATUS_ACCESS_DENIED) {
                trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
                status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1995
                ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
1996
            }
1997 1998 1999 2000 2001

            if (status == STATUS_SUCCESS)
            {
                PPOLICY_ACCOUNT_DOMAIN_INFO info;
                status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
2002
                ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
2003 2004 2005 2006 2007 2008
                if (status == STATUS_SUCCESS)
                {
                    ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
                    if (info->DomainSid)
                    {
                        int count = *GetSidSubAuthorityCount(info->DomainSid);
2009 2010
                        CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
                        test_sid_str((PSID)&max_sid.sid);
2011 2012
                        max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
                        max_sid.sid.SubAuthorityCount = count + 1;
2013
                        test_sid_str((PSID)&max_sid.sid);
2014
                        max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
                        test_sid_str((PSID)&max_sid.sid);
                        max_sid.sid.SubAuthority[count] = 1000;	/* first user account */
                        test_sid_str((PSID)&max_sid.sid);
2038 2039 2040 2041 2042 2043
                    }

                    pLsaFreeMemory((LPVOID)info);
                }

                status = pLsaClose(handle);
2044
                ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
2045
            }
2046 2047
        }
    }
2048 2049
}

2050
static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
{
    static CHAR account[UNLEN + 1];
    static CHAR domain[UNLEN + 1];
    DWORD size, dom_size;
    SID_NAME_USE use;

    *user = account;
    *dom = domain;

    size = dom_size = UNLEN + 1;
    account[0] = '\0';
    domain[0] = '\0';
2063 2064
    SetLastError(0xdeadbeef);
    return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
2065 2066
}

2067
static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
2068
{
2069
    SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
2070
    PSID domainsid = NULL;
2071 2072 2073
    char wk_sid[SECURITY_MAX_SID_SIZE];
    DWORD cb;

2074 2075
    DWORD sid_size, domain_size;
    SID_NAME_USE sid_use;
2076
    LPSTR domain, account, sid_domain, wk_domain, wk_account;
2077
    PSID psid;
2078
    BOOL ret ,ret2;
2079 2080 2081 2082

    sid_size = 0;
    domain_size = 0;
    ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2083
    ok(!ret, " %s Should have failed to lookup account name\n", name);
2084 2085 2086 2087
    psid = HeapAlloc(GetProcessHeap(),0,sid_size);
    domain = HeapAlloc(GetProcessHeap(),0,domain_size);
    ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);

2088
    if (!result)
2089 2090
    {
        ok(!ret, " %s Should have failed to lookup account name\n",name);
2091
        goto cleanup;
2092
    }
2093 2094 2095 2096 2097

    AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
    cb = sizeof(wk_sid);
    if (!pCreateWellKnownSid(result, domainsid, wk_sid, &cb))
    {
2098 2099 2100 2101 2102 2103 2104 2105 2106
        win_skip("SID %i is not available on the system\n",result);
        goto cleanup;
    }

    ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
    if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
    {
        win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
        goto cleanup;
2107 2108 2109 2110
    }

    get_sid_info(psid, &account, &sid_domain);

2111 2112
    ok(ret, "Failed to lookup account name %s\n",name);
    ok(sid_size != 0, "sid_size was zero\n");
2113 2114 2115 2116 2117 2118

    ok(EqualSid(psid,wk_sid),"(%s) Sids fail to match well known sid!\n",name);

    ok(!lstrcmp(account, wk_account), "Expected %s , got %s\n", account, wk_account);
    ok(!lstrcmp(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
    ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
2119

2120
cleanup:
2121
    FreeSid(domainsid);
2122 2123 2124 2125
    HeapFree(GetProcessHeap(),0,psid);
    HeapFree(GetProcessHeap(),0,domain);
}

2126 2127 2128 2129 2130
static void test_LookupAccountName(void)
{
    DWORD sid_size, domain_size, user_size;
    DWORD sid_save, domain_save;
    CHAR user_name[UNLEN + 1];
2131
    CHAR computer_name[UNLEN + 1];
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
    SID_NAME_USE sid_use;
    LPSTR domain, account, sid_dom;
    PSID psid;
    BOOL ret;

    /* native crashes if (assuming all other parameters correct):
     *  - peUse is NULL
     *  - Sid is NULL and cbSid is > 0
     *  - cbSid or cchReferencedDomainName are NULL
     *  - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
     */

    user_size = UNLEN + 1;
2145
    SetLastError(0xdeadbeef);
2146
    ret = GetUserNameA(user_name, &user_size);
2147
    ok(ret, "Failed to get user name : %d\n", GetLastError());
2148 2149 2150 2151 2152 2153 2154

    /* get sizes */
    sid_size = 0;
    domain_size = 0;
    sid_use = 0xcafebabe;
    SetLastError(0xdeadbeef);
    ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2155 2156
    if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
    {
2157
        win_skip("LookupAccountNameA is not implemented\n");
2158 2159
        return;
    }
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
    ok(!ret, "Expected 0, got %d\n", ret);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(sid_size != 0, "Expected non-zero sid size\n");
    ok(domain_size != 0, "Expected non-zero domain size\n");
    ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);

    sid_save = sid_size;
    domain_save = domain_size;

    psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
    domain = HeapAlloc(GetProcessHeap(), 0, domain_size);

    /* try valid account name */
    ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
    get_sid_info(psid, &account, &sid_dom);
    ok(ret, "Failed to lookup account name\n");
    ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
2178 2179
    ok(!lstrcmp(account, user_name), "Expected %s, got %s\n", user_name, account);
    ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2180
    ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
2181
    ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
2182
    ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
2183 2184 2185
    domain_size = domain_save;
    sid_size = sid_save;

2186
    if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2187
    {
2188
        skip("Non-English locale (test with hardcoded 'Everyone')\n");
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
    }
    else
    {
        ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
        get_sid_info(psid, &account, &sid_dom);
        ok(ret, "Failed to lookup account name\n");
        ok(sid_size != 0, "sid_size was zero\n");
        ok(!lstrcmp(account, "Everyone"), "Expected Everyone, got %s\n", account);
        ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
        ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2199
        ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
2200
        ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
2201 2202
        domain_size = domain_save;
    }
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242

    /* NULL Sid with zero sid size */
    SetLastError(0xdeadbeef);
    sid_size = 0;
    ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
    ok(!ret, "Expected 0, got %d\n", ret);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
    ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);

    /* try cchReferencedDomainName - 1 */
    SetLastError(0xdeadbeef);
    domain_size--;
    ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
    ok(!ret, "Expected 0, got %d\n", ret);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
    ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);

    /* NULL ReferencedDomainName with zero domain name size */
    SetLastError(0xdeadbeef);
    domain_size = 0;
    ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
    ok(!ret, "Expected 0, got %d\n", ret);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
    ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);

    HeapFree(GetProcessHeap(), 0, psid);
    HeapFree(GetProcessHeap(), 0, domain);

    /* get sizes for NULL account name */
    sid_size = 0;
    domain_size = 0;
    sid_use = 0xcafebabe;
    SetLastError(0xdeadbeef);
    ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2243 2244 2245
    if (!ret && GetLastError() == ERROR_NONE_MAPPED)
        win_skip("NULL account name doesn't work on NT4\n");
    else
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    {
        ok(!ret, "Expected 0, got %d\n", ret);
        ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
           "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
        ok(sid_size != 0, "Expected non-zero sid size\n");
        ok(domain_size != 0, "Expected non-zero domain size\n");
        ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);

        psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
        domain = HeapAlloc(GetProcessHeap(), 0, domain_size);

        /* try NULL account name */
        ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
        get_sid_info(psid, &account, &sid_dom);
        ok(ret, "Failed to lookup account name\n");
        /* Using a fixed string will not work on different locales */
        ok(!lstrcmp(account, domain),
           "Got %s for account and %s for domain, these should be the same\n",
           account, domain);
        ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);

        HeapFree(GetProcessHeap(), 0, psid);
        HeapFree(GetProcessHeap(), 0, domain);
    }
2270 2271 2272 2273 2274 2275 2276

    /* try an invalid account name */
    SetLastError(0xdeadbeef);
    sid_size = 0;
    domain_size = 0;
    ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
    ok(!ret, "Expected 0, got %d\n", ret);
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
    ok(GetLastError() == ERROR_NONE_MAPPED ||
       broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
       "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
    ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
    ok(domain_size == 0, "Expected 0, got %d\n", domain_size);

    /* try an invalid system name */
    SetLastError(0xdeadbeef);
    sid_size = 0;
    domain_size = 0;
    ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
    ok(!ret, "Expected 0, got %d\n", ret);
2289 2290
    ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
       "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
2291 2292
    ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
    ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2293 2294 2295 2296 2297 2298 2299 2300

    /* try with the computer name as the account name */
    domain_size = sizeof(computer_name);
    GetComputerNameA(computer_name, &domain_size);
    sid_size = 0;
    domain_size = 0;
    ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
    ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
2301
       GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
2302 2303 2304 2305 2306 2307 2308 2309 2310
       broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
       broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
       "LookupAccountNameA failed: %d\n", GetLastError());
    if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
        domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
        ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
        ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
2311 2312
        ok(sid_use == SidTypeDomain ||
           (sid_use == SidTypeUser && ! strcmp(computer_name, user_name)), "expected SidTypeDomain for %s, got %d\n", computer_name, sid_use);
2313 2314 2315
        HeapFree(GetProcessHeap(), 0, domain);
        HeapFree(GetProcessHeap(), 0, psid);
    }
2316 2317

    /* Well Known names */
2318 2319 2320 2321 2322 2323
    if (!pCreateWellKnownSid)
    {
        win_skip("CreateWellKnownSid not available\n");
        return;
    }

2324
    if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2325
    {
2326
        skip("Non-English locale (skipping well known name creation tests)\n");
2327 2328 2329 2330 2331
        return;
    }

    check_wellknown_name("LocalService", WinLocalServiceSid);
    check_wellknown_name("Local Service", WinLocalServiceSid);
2332
    /* 2 spaces */
2333 2334 2335
    check_wellknown_name("Local  Service", 0);
    check_wellknown_name("NetworkService", WinNetworkServiceSid);
    check_wellknown_name("Network Service", WinNetworkServiceSid);
2336 2337

    /* example of some names where the spaces are not optional */
2338 2339 2340 2341
    check_wellknown_name("Terminal Server User", WinTerminalServerSid);
    check_wellknown_name("TerminalServer User", 0);
    check_wellknown_name("TerminalServerUser", 0);
    check_wellknown_name("Terminal ServerUser", 0);
2342

2343 2344 2345 2346
    check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
    check_wellknown_name("enterprisedomain controllers", 0);
    check_wellknown_name("enterprise domaincontrollers", 0);
    check_wellknown_name("enterprisedomaincontrollers", 0);
2347 2348

    /* case insensitivity */
2349
    check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
2350 2351 2352 2353 2354 2355 2356

    /* fully qualified account names */
    check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
    check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
    check_wellknown_name("nt authority test\\Network Service", 0);
    check_wellknown_name("Dummy\\Network Service", 0);
    check_wellknown_name("ntauthority\\Network Service", 0);
2357 2358
}

2359 2360 2361 2362 2363
static void test_security_descriptor(void)
{
    SECURITY_DESCRIPTOR sd;
    char buf[8192];
    DWORD size;
2364
    BOOL isDefault, isPresent, ret;
2365 2366 2367
    PACL pacl;
    PSID psid;

2368 2369 2370 2371
    SetLastError(0xdeadbeef);
    ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
    if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
2372
        win_skip("InitializeSecurityDescriptor is not implemented\n");
2373 2374 2375
        return;
    }

2376 2377
    ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
    expect_eq(psid, NULL, PSID, "%p");
2378
    expect_eq(isDefault, FALSE, BOOL, "%d");
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
    sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;

    SetLastError(0xdeadbeef);
    size = 5;
    expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
    expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
    ok(size > 5, "Size not increased\n");
    if (size <= 8192)
    {
        expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
        ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
        expect_eq(psid, NULL, PSID, "%p");
2391
        expect_eq(isDefault, FALSE, BOOL, "%d");
2392
        ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
2393
        expect_eq(psid, NULL, PSID, "%p");
2394
        expect_eq(isDefault, FALSE, BOOL, "%d");
2395
        ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
2396 2397 2398
        expect_eq(isPresent, TRUE, BOOL, "%d");
        expect_eq(psid, NULL, PSID, "%p");
        expect_eq(isDefault, FALSE, BOOL, "%d");
2399
        ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
2400 2401 2402 2403 2404 2405
        expect_eq(isPresent, TRUE, BOOL, "%d");
        expect_eq(psid, NULL, PSID, "%p");
        expect_eq(isDefault, FALSE, BOOL, "%d");
    }
}

2406 2407 2408 2409
#define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
#define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
static void test_granted_access(HANDLE handle, ACCESS_MASK access,
                                ACCESS_MASK alt, int line)
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
{
    OBJECT_BASIC_INFORMATION obj_info;
    NTSTATUS status;

    if (!pNtQueryObject)
    {
        skip_(__FILE__, line)("Not NT platform - skipping tests\n");
        return;
    }

    status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
                             sizeof(obj_info), NULL );
    ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2423 2424 2425 2426 2427 2428 2429
    if (alt)
        ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
            obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
            "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
    else
        ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
            "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
2430 2431
}

2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445
#define CHECK_SET_SECURITY(o,i,e) \
    do{ \
        BOOL res; \
        DWORD err; \
        SetLastError( 0xdeadbeef ); \
        res = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
        err = GetLastError(); \
        if (e == ERROR_SUCCESS) \
            ok(res, "SetKernelObjectSecurity failed with %d\n", err); \
        else \
            ok(!res && err == e, "SetKernelObjectSecurity should have failed " \
               "with %s, instead of %d\n", #e, err); \
    }while(0)

2446 2447 2448
static void test_process_security(void)
{
    BOOL res;
2449 2450
    PTOKEN_OWNER owner;
    PTOKEN_PRIMARY_GROUP group;
2451 2452 2453 2454 2455 2456 2457
    PSID AdminSid = NULL, UsersSid = NULL;
    PACL Acl = NULL;
    SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
    char buffer[MAX_PATH];
    PROCESS_INFORMATION info;
    STARTUPINFOA startup;
    SECURITY_ATTRIBUTES psa;
2458
    HANDLE token, event;
2459
    DWORD size;
2460 2461 2462 2463 2464

    Acl = HeapAlloc(GetProcessHeap(), 0, 256);
    res = InitializeAcl(Acl, 256, ACL_REVISION);
    if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
2465
        win_skip("ACLs not implemented - skipping tests\n");
2466
        HeapFree(GetProcessHeap(), 0, Acl);
2467 2468 2469 2470
        return;
    }
    ok(res, "InitializeAcl failed with error %d\n", GetLastError());

2471 2472 2473
    /* get owner from the token we might be running as a user not admin */
    res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
    ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
2474 2475 2476 2477 2478
    if (!res)
    {
        HeapFree(GetProcessHeap(), 0, Acl);
        return;
    }
2479

2480 2481 2482 2483 2484 2485 2486
    res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
    ok(!res, "Expected failure, got %d\n", res);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());

    owner = HeapAlloc(GetProcessHeap(), 0, size);
    res = GetTokenInformation( token, TokenOwner, owner, size, &size );
2487 2488
    ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
    AdminSid = ((TOKEN_OWNER*)owner)->Owner;
2489 2490 2491 2492 2493 2494 2495 2496

    res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
    ok(!res, "Expected failure, got %d\n", res);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());

    group = HeapAlloc(GetProcessHeap(), 0, size);
    res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
2497 2498 2499 2500
    ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
    UsersSid = ((TOKEN_PRIMARY_GROUP*)group)->PrimaryGroup;

    CloseHandle( token );
2501 2502
    if (!res)
    {
2503 2504
        HeapFree(GetProcessHeap(), 0, group);
        HeapFree(GetProcessHeap(), 0, owner);
2505 2506 2507
        HeapFree(GetProcessHeap(), 0, Acl);
        return;
    }
2508 2509 2510 2511

    res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
    ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
    res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
2512
    ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2513 2514 2515 2516 2517

    SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
    res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
    ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());

2518 2519 2520
    event = CreateEvent( NULL, TRUE, TRUE, "test_event" );
    ok(event != NULL, "CreateEvent %d\n", GetLastError());

2521 2522 2523 2524
    SecurityDescriptor->Revision = 0;
    CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
    SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;

2525 2526 2527 2528
    CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
    CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
    CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
    CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2529 2530 2531
    /* NULL DACL is valid and means default DACL from token */
    SecurityDescriptor->Control |= SE_DACL_PRESENT;
    CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2532

2533 2534 2535
    /* Set owner and group and dacl */
    res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
    ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2536 2537
    CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
    res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
2538
    ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2539
    CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
2540 2541
    res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
    ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
2542
    CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554

    sprintf(buffer, "%s tests/security.c test", myARGV[0]);
    memset(&startup, 0, sizeof(startup));
    startup.cb = sizeof(startup);
    startup.dwFlags = STARTF_USESHOWWINDOW;
    startup.wShowWindow = SW_SHOWNORMAL;

    psa.nLength = sizeof(psa);
    psa.lpSecurityDescriptor = SecurityDescriptor;
    psa.bInheritHandle = TRUE;

    /* Doesn't matter what ACL say we should get full access for ourselves */
2555 2556
    res = CreateProcessA( NULL, buffer, &psa, NULL, FALSE, 0, NULL, NULL, &startup, &info );
    ok(res, "CreateProcess with err:%d\n", GetLastError());
2557
    TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS_NT4,
2558
                          STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2559
    winetest_wait_child_process( info.hProcess );
2560

2561 2562
    CloseHandle( info.hProcess );
    CloseHandle( info.hThread );
2563
    CloseHandle( event );
2564 2565
    HeapFree(GetProcessHeap(), 0, group);
    HeapFree(GetProcessHeap(), 0, owner);
2566 2567 2568 2569 2570 2571 2572
    HeapFree(GetProcessHeap(), 0, Acl);
    HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
}

static void test_process_security_child(void)
{
    HANDLE handle, handle1;
2573 2574
    BOOL ret;
    DWORD err;
2575 2576 2577 2578 2579

    handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
    ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
    TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );

2580 2581 2582
    ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
                           &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS );
    ok(ret, "duplicating handle err:%d\n", GetLastError());
2583
    TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
2584 2585

    CloseHandle( handle1 );
2586 2587 2588 2589 2590 2591 2592 2593 2594

    SetLastError( 0xdeadbeef );
    ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
                           &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
    err = GetLastError();
    todo_wine
    ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
       "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);

2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
    CloseHandle( handle );

    /* These two should fail - they are denied by ACL */
    handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
    todo_wine
    ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
    handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
    todo_wine
    ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");

    /* Documented privilege elevation */
2606 2607 2608
    ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
                           &handle, 0, TRUE, DUPLICATE_SAME_ACCESS );
    ok(ret, "duplicating handle err:%d\n", GetLastError());
2609
    TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
2610
                          STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2611 2612

    CloseHandle( handle );
2613 2614

    /* Same only explicitly asking for all access rights */
2615 2616 2617
    ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
                           &handle, PROCESS_ALL_ACCESS, TRUE, 0 );
    ok(ret, "duplicating handle err:%d\n", GetLastError());
2618
    TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
2619
                          PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
2620 2621 2622
    ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
                           &handle1, PROCESS_VM_READ, TRUE, 0 );
    ok(ret, "duplicating handle err:%d\n", GetLastError());
2623 2624 2625
    TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
    CloseHandle( handle1 );
    CloseHandle( handle );
2626 2627
}

2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
static void test_impersonation_level(void)
{
    HANDLE Token, ProcessToken;
    HANDLE Token2;
    DWORD Size;
    TOKEN_PRIVILEGES *Privileges;
    TOKEN_USER *User;
    PRIVILEGE_SET *PrivilegeSet;
    BOOL AccessGranted;
    BOOL ret;
    HKEY hkey;
    DWORD error;

2641
    pDuplicateTokenEx = (void *)GetProcAddress(hmod, "DuplicateTokenEx");
2642
    if( !pDuplicateTokenEx ) {
2643
        win_skip("DuplicateTokenEx is not available\n");
2644 2645
        return;
    }
2646
    SetLastError(0xdeadbeef);
2647
    ret = ImpersonateSelf(SecurityAnonymous);
2648 2649
    if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
    {
2650
        win_skip("ImpersonateSelf is not implemented\n");
2651 2652
        return;
    }
2653 2654 2655 2656 2657 2658
    ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
    ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
    ok(!ret, "OpenThreadToken should have failed\n");
    error = GetLastError();
    ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
    /* can't perform access check when opening object against an anonymous impersonation token */
2659
    todo_wine {
2660
    error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2661 2662
    ok(error == ERROR_INVALID_HANDLE || error == ERROR_CANT_OPEN_ANONYMOUS,
       "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE or ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2663 2664 2665 2666 2667 2668
    }
    RevertToSelf();

    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
    ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());

2669
    ret = pDuplicateTokenEx(ProcessToken,
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
        TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
        SecurityAnonymous, TokenImpersonation, &Token);
    ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
    /* can't increase the impersonation level */
    ret = DuplicateToken(Token, SecurityIdentification, &Token2);
    error = GetLastError();
    ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
        "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
    /* we can query anything from an anonymous token, including the user */
    ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
    error = GetLastError();
    ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2682
    User = HeapAlloc(GetProcessHeap(), 0, Size);
2683 2684 2685 2686 2687 2688 2689 2690
    ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
    ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, User);

    /* PrivilegeCheck fails with SecurityAnonymous level */
    ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
    error = GetLastError();
    ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2691
    Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
2692 2693 2694
    ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
    ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());

2695
    PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
    PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
    memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
    PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
    HeapFree(GetProcessHeap(), 0, Privileges);

    ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
    error = GetLastError();
    ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);

    CloseHandle(Token);

    ret = ImpersonateSelf(SecurityIdentification);
    ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
    ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
    ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());

    /* can't perform access check when opening object against an identification impersonation token */
    error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
    todo_wine {
2715 2716
    ok(error == ERROR_INVALID_HANDLE || error == ERROR_BAD_IMPERSONATION_LEVEL,
       "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE or ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
    }
    ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
    ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
    CloseHandle(Token);
    RevertToSelf();

    ret = ImpersonateSelf(SecurityImpersonation);
    ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
    ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
    ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
    error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
    ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
    RegCloseKey(hkey);
    ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
    ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
    RevertToSelf();

    CloseHandle(Token);
    CloseHandle(ProcessToken);

    HeapFree(GetProcessHeap(), 0, PrivilegeSet);
}

2740
static void test_SetEntriesInAclW(void)
2741 2742
{
    DWORD res;
2743 2744 2745 2746 2747 2748
    PSID EveryoneSid = NULL, UsersSid = NULL;
    PACL OldAcl = NULL, NewAcl;
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
    EXPLICIT_ACCESSW ExplicitAccess;
    static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
2749
    static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
2750

2751 2752
    if (!pSetEntriesInAclW)
    {
2753
        win_skip("SetEntriesInAclW is not available\n");
2754 2755 2756
        return;
    }

2757 2758
    NewAcl = (PACL)0xdeadbeef;
    res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
2759 2760
    if(res == ERROR_CALL_NOT_IMPLEMENTED)
    {
2761
        win_skip("SetEntriesInAclW is not implemented\n");
2762 2763 2764
        return;
    }
    ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2765 2766 2767 2768
    ok(NewAcl == NULL ||
        broken(NewAcl != NULL), /* NT4 */
        "NewAcl=%p, expected NULL\n", NewAcl);
    LocalFree(NewAcl);
2769 2770 2771 2772 2773

    OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
    res = InitializeAcl(OldAcl, 256, ACL_REVISION);
    if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
2774
        win_skip("ACLs not implemented - skipping tests\n");
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
        HeapFree(GetProcessHeap(), 0, OldAcl);
        return;
    }
    ok(res, "InitializeAcl failed with error %d\n", GetLastError());

    res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());

    res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());

    res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
    ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());

    ExplicitAccess.grfAccessPermissions = KEY_WRITE;
    ExplicitAccess.grfAccessMode = GRANT_ACCESS;
    ExplicitAccess.grfInheritance = NO_INHERITANCE;
2793
    ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
2794
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2795
    ExplicitAccess.Trustee.ptstrName = EveryoneSid;
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
    ExplicitAccess.Trustee.MultipleTrusteeOperation = 0xDEADBEEF;
    ExplicitAccess.Trustee.pMultipleTrustee = (PVOID)0xDEADBEEF;
    res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

    ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
    ExplicitAccess.Trustee.pMultipleTrustee = NULL;
    ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2806 2807 2808 2809 2810
    res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

2811
    if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2812
    {
2813
        skip("Non-English locale (test with hardcoded 'Everyone')\n");
2814 2815 2816
    }
    else
    {
2817
        ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2818 2819 2820 2821 2822 2823 2824 2825
        ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
        res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
        ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
        ok(NewAcl != NULL, "returned acl was NULL\n");
        LocalFree(NewAcl);

        ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
        res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2826 2827 2828
        ok(res == ERROR_INVALID_PARAMETER ||
            broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
            "SetEntriesInAclW failed: %u\n", res);
2829 2830 2831
        ok(NewAcl == NULL ||
            broken(NewAcl != NULL), /* NT4 */
            "returned acl wasn't NULL: %p\n", NewAcl);
2832

2833
        ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2834 2835
        ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
        res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2836 2837 2838
        ok(res == ERROR_INVALID_PARAMETER ||
            broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
            "SetEntriesInAclW failed: %u\n", res);
2839 2840 2841
        ok(NewAcl == NULL ||
            broken(NewAcl != NULL), /* NT4 */
            "returned acl wasn't NULL: %p\n", NewAcl);
2842 2843 2844 2845 2846 2847 2848 2849

        ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
        ExplicitAccess.grfAccessMode = SET_ACCESS;
        res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
        ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
        ok(NewAcl != NULL, "returned acl was NULL\n");
        LocalFree(NewAcl);
    }
2850

2851
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2852 2853 2854 2855 2856 2857
    ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
    res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

2858 2859
    ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2860
    ExplicitAccess.Trustee.ptstrName = UsersSid;
2861 2862 2863 2864 2865
    res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

2866 2867
    FreeSid(UsersSid);
    FreeSid(EveryoneSid);
2868
    HeapFree(GetProcessHeap(), 0, OldAcl);
2869 2870
}

2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
static void test_SetEntriesInAclA(void)
{
    DWORD res;
    PSID EveryoneSid = NULL, UsersSid = NULL;
    PACL OldAcl = NULL, NewAcl;
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
    EXPLICIT_ACCESS ExplicitAccess;
    static const CHAR szEveryone[] = {'E','v','e','r','y','o','n','e',0};
    static const CHAR szCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};

    if (!pSetEntriesInAclA)
    {
        win_skip("SetEntriesInAclA is not available\n");
        return;
    }

    NewAcl = (PACL)0xdeadbeef;
    res = pSetEntriesInAclA(0, NULL, NULL, &NewAcl);
    if(res == ERROR_CALL_NOT_IMPLEMENTED)
    {
        win_skip("SetEntriesInAclA is not implemented\n");
        return;
    }
    ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
    ok(NewAcl == NULL ||
        broken(NewAcl != NULL), /* NT4 */
        "NewAcl=%p, expected NULL\n", NewAcl);
    LocalFree(NewAcl);

    OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
    res = InitializeAcl(OldAcl, 256, ACL_REVISION);
    if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
        win_skip("ACLs not implemented - skipping tests\n");
        HeapFree(GetProcessHeap(), 0, OldAcl);
        return;
    }
    ok(res, "InitializeAcl failed with error %d\n", GetLastError());

    res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());

    res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
    ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());

    res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
    ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());

    ExplicitAccess.grfAccessPermissions = KEY_WRITE;
    ExplicitAccess.grfAccessMode = GRANT_ACCESS;
    ExplicitAccess.grfInheritance = NO_INHERITANCE;
    ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ExplicitAccess.Trustee.ptstrName = EveryoneSid;
2927 2928
    ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
    res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

    ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
    ExplicitAccess.Trustee.pMultipleTrustee = NULL;
    ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

2942
    if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2943
    {
2944
        skip("Non-English locale (test with hardcoded 'Everyone')\n");
2945 2946 2947
    }
    else
    {
2948
        ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
        ExplicitAccess.Trustee.ptstrName = (LPSTR)szEveryone;
        res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
        ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
        ok(NewAcl != NULL, "returned acl was NULL\n");
        LocalFree(NewAcl);

        ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
        res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
        ok(res == ERROR_INVALID_PARAMETER ||
            broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
            "SetEntriesInAclA failed: %u\n", res);
        ok(NewAcl == NULL ||
            broken(NewAcl != NULL), /* NT4 */
            "returned acl wasn't NULL: %p\n", NewAcl);

2964
        ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
        ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
        res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
        ok(res == ERROR_INVALID_PARAMETER ||
            broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
            "SetEntriesInAclA failed: %u\n", res);
        ok(NewAcl == NULL ||
            broken(NewAcl != NULL), /* NT4 */
            "returned acl wasn't NULL: %p\n", NewAcl);

        ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
        ExplicitAccess.grfAccessMode = SET_ACCESS;
        res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
        ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
        ok(NewAcl != NULL, "returned acl was NULL\n");
        LocalFree(NewAcl);
    }

2982
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001
    ExplicitAccess.Trustee.ptstrName = (LPSTR)szCurrentUser;
    res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

    ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ExplicitAccess.Trustee.ptstrName = UsersSid;
    res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
    ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
    ok(NewAcl != NULL, "returned acl was NULL\n");
    LocalFree(NewAcl);

    FreeSid(UsersSid);
    FreeSid(EveryoneSid);
    HeapFree(GetProcessHeap(), 0, OldAcl);
}

3002 3003 3004 3005 3006 3007 3008
static void test_GetNamedSecurityInfoA(void)
{
    PSECURITY_DESCRIPTOR pSecDesc;
    DWORD revision;
    SECURITY_DESCRIPTOR_CONTROL control;
    PSID owner;
    PSID group;
3009
    PACL dacl;
3010 3011 3012
    BOOL owner_defaulted;
    BOOL group_defaulted;
    DWORD error;
3013
    BOOL ret, isNT4;
3014 3015
    CHAR windows_dir[MAX_PATH];

3016 3017
    if (!pGetNamedSecurityInfoA)
    {
3018
        win_skip("GetNamedSecurityInfoA is not available\n");
3019 3020 3021
        return;
    }

3022 3023 3024
    ret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
    ok(ret, "GetWindowsDirectory failed with error %d\n", GetLastError());

3025
    SetLastError(0xdeadbeef);
3026
    error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
3027 3028
        OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
        NULL, NULL, NULL, NULL, &pSecDesc);
3029 3030
    if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
    {
3031
        win_skip("GetNamedSecurityInfoA is not implemented\n");
3032 3033
        return;
    }
3034 3035 3036 3037
    ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);

    ret = GetSecurityDescriptorControl(pSecDesc, &control, &revision);
    ok(ret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
3038 3039
    ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
        broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
3040 3041
        "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
    ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
3042 3043 3044

    isNT4 = (control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT;

3045 3046 3047
    ret = GetSecurityDescriptorOwner(pSecDesc, &owner, &owner_defaulted);
    ok(ret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
    ok(owner != NULL, "owner should not be NULL\n");
3048

3049 3050 3051
    ret = GetSecurityDescriptorGroup(pSecDesc, &group, &group_defaulted);
    ok(ret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
    ok(group != NULL, "group should not be NULL\n");
3052
    LocalFree(pSecDesc);
3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073


    /* NULL descriptor tests */
    if(isNT4)
    {
        win_skip("NT4 does not support GetNamedSecutityInfo with a NULL descriptor\n");
        return;
    }

    error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
        NULL, NULL, NULL, NULL, NULL);
    ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);

    error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
        NULL, NULL, &dacl, NULL, NULL);
    ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
    ok(dacl != NULL, "dacl should not be NULL\n");

    error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,
        NULL, NULL, &dacl, NULL, NULL);
    ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3074 3075
}

3076
static void test_ConvertStringSecurityDescriptor(void)
3077 3078 3079
{
    BOOL ret;
    PSECURITY_DESCRIPTOR pSD;
3080
    static const WCHAR Blank[] = { 0 };
3081
    unsigned int i;
3082 3083 3084 3085 3086 3087
    static const struct
    {
        const char *sidstring;
        DWORD      revision;
        BOOL       ret;
        DWORD      GLE;
3088
        DWORD      altGLE;
3089 3090 3091 3092 3093 3094 3095
    } cssd[] =
    {
        { "D:(A;;GA;;;WD)",                  0xdeadbeef,      FALSE, ERROR_UNKNOWN_REVISION },
        /* test ACE string type */
        { "D:(A;;GA;;;WD)",                  SDDL_REVISION_1, TRUE },
        { "D:(D;;GA;;;WD)",                  SDDL_REVISION_1, TRUE },
        { "ERROR:(D;;GA;;;WD)",              SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
3096
        /* test ACE string with spaces */
3097 3098 3099
        { " D:(D;;GA;;;WD)",                SDDL_REVISION_1, TRUE },
        { "D: (D;;GA;;;WD)",                SDDL_REVISION_1, TRUE },
        { "D:( D;;GA;;;WD)",                SDDL_REVISION_1, TRUE },
3100
        { "D:(D ;;GA;;;WD)",                SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
3101 3102 3103 3104 3105 3106 3107
        { "D:(D; ;GA;;;WD)",                SDDL_REVISION_1, TRUE },
        { "D:(D;; GA;;;WD)",                SDDL_REVISION_1, TRUE },
        { "D:(D;;GA ;;;WD)",                SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
        { "D:(D;;GA; ;;WD)",                SDDL_REVISION_1, TRUE },
        { "D:(D;;GA;; ;WD)",                SDDL_REVISION_1, TRUE },
        { "D:(D;;GA;;; WD)",                SDDL_REVISION_1, TRUE },
        { "D:(D;;GA;;;WD )",                SDDL_REVISION_1, TRUE },
3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
        /* test ACE string access rights */
        { "D:(A;;GA;;;WD)",                  SDDL_REVISION_1, TRUE },
        { "D:(A;;GRGWGX;;;WD)",              SDDL_REVISION_1, TRUE },
        { "D:(A;;RCSDWDWO;;;WD)",            SDDL_REVISION_1, TRUE },
        { "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)",  SDDL_REVISION_1, TRUE },
        { "D:(A;;FAFRFWFX;;;WD)",            SDDL_REVISION_1, TRUE },
        { "D:(A;;KAKRKWKX;;;WD)",            SDDL_REVISION_1, TRUE },
        { "D:(A;;0xFFFFFFFF;;;WD)",          SDDL_REVISION_1, TRUE },
        { "S:(AU;;0xFFFFFFFF;;;WD)",         SDDL_REVISION_1, TRUE },
        /* test ACE string access right error case */
        { "D:(A;;ROB;;;WD)",                 SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
        /* test behaviour with empty strings */
        { "",                                SDDL_REVISION_1, TRUE },
        /* test ACE string SID */
3122 3123
        { "D:(D;;GA;;;S-1-0-0)",             SDDL_REVISION_1, TRUE },
        { "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
3124
    };
3125

3126 3127
    if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
    {
3128
        win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3129 3130 3131
        return;
    }

3132 3133 3134
    for (i = 0; i < sizeof(cssd)/sizeof(cssd[0]); i++)
    {
        DWORD GLE;
3135

3136 3137 3138 3139
        SetLastError(0xdeadbeef);
        ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
            cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
        GLE = GetLastError();
3140
        ok(ret == cssd[i].ret, "(%02u) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
3141
        if (!cssd[i].ret)
3142 3143
            ok(GLE == cssd[i].GLE ||
               (cssd[i].altGLE && GLE == cssd[i].altGLE),
3144
               "(%02u) Unexpected last error %d\n", i, GLE);
3145 3146 3147
        if (ret)
            LocalFree(pSD);
    }
3148

3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
    /* test behaviour with NULL parameters */
    SetLastError(0xdeadbeef);
    ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
        NULL, 0xdeadbeef, &pSD, NULL);
    todo_wine
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
        "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
        GetLastError());

    SetLastError(0xdeadbeef);
    ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
        NULL, 0xdeadbeef, &pSD, NULL);
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
        "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
        GetLastError());

    SetLastError(0xdeadbeef);
    ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
        "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
        "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
        GetLastError());

    SetLastError(0xdeadbeef);
    ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
        "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
        "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
        GetLastError());

    /* test behaviour with empty strings */
    SetLastError(0xdeadbeef);
    ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
        Blank, SDDL_REVISION_1, &pSD, NULL);
    ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
3184
    LocalFree(pSD);
3185 3186
}

3187
static void test_ConvertSecurityDescriptorToString(void)
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
{
    SECURITY_DESCRIPTOR desc;
    SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
    LPSTR string;
    DWORD size;
    PSID psid, psid2;
    PACL pacl;
    char sid_buf[256];
    char acl_buf[8192];
    ULONG len;

    if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
    {
3201
        win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
3202 3203
        return;
    }
3204 3205
    if (!pCreateWellKnownSid)
    {
3206
        win_skip("CreateWellKnownSid is not available\n");
3207 3208
        return;
    }
3209

3210
/* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
3211 3212 3213
 * don't replicate this feature so we only test len >= strlen+1. */
#define CHECK_RESULT_AND_FREE(exp_str) \
    ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
3214
    ok(len >= (strlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(exp_str) + 1, len); \
3215 3216
    LocalFree(string);

3217 3218
#define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
    ok(strcmp(string, (exp_str1)) == 0 || strcmp(string, (exp_str2)) == 0, "String mismatch (expected\n\"%s\" or\n\"%s\", got\n\"%s\")\n", (exp_str1), (exp_str2), string); \
3219
    ok(len >= (strlen(exp_str1) + 1) || len >= (strlen(exp_str2) + 1), "Length mismatch (expected %d or %d, got %d)\n", lstrlen(exp_str1) + 1, lstrlen(exp_str2) + 1, len); \
3220 3221
    LocalFree(string);

3222
    InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
3223
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3224 3225 3226
    CHECK_RESULT_AND_FREE("");

    size = 4096;
3227
    pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
3228
    SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
3229
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3230 3231
    CHECK_RESULT_AND_FREE("O:S-1-2-0");

3232
    SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
3233
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3234 3235 3236
    CHECK_RESULT_AND_FREE("O:S-1-2-0");

    size = sizeof(sid_buf);
3237
    pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
3238
    SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
3239
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3240 3241
    CHECK_RESULT_AND_FREE("O:SY");

3242
    pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
3243
    SetSecurityDescriptorGroup(&desc, psid, TRUE);
3244
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3245 3246
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");

3247
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
3248 3249 3250 3251 3252
    CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");

    pacl = (PACL)acl_buf;
    InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
    SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
3253
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3254 3255 3256
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");

    SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
3257
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3258 3259
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");

3260 3261
    pConvertStringSidToSidA("S-1-5-6", &psid2);
    pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
3262
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3263 3264
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");

3265
    pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
3266
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3267 3268
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");

3269
    pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
3270
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3271 3272 3273 3274 3275 3276
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)");


    pacl = (PACL)acl_buf;
    InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
    SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
3277
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3278 3279
    CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");

3280
    /* fails in win2k */
3281
    SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
3282
    pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
3283 3284 3285 3286 3287
    if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
    {
        CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
            "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
    }
3288

3289
    /* fails in win2k */
3290
    pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
3291 3292 3293 3294 3295
    if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
    {
        CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
            "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
    }
3296 3297 3298

    LocalFree(psid2);
    LocalFree(psid);
3299 3300
}

3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
{
    SECURITY_DESCRIPTOR_CONTROL ref;
    SECURITY_DESCRIPTOR_CONTROL test;

    SECURITY_DESCRIPTOR_CONTROL const mutable
        = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
        | SE_DACL_AUTO_INHERITED   | SE_SACL_AUTO_INHERITED
        | SE_DACL_PROTECTED        | SE_SACL_PROTECTED
        | 0x00000040               | 0x00000080        /* not defined in winnt.h */
        ;
    SECURITY_DESCRIPTOR_CONTROL const immutable
        = SE_OWNER_DEFAULTED       | SE_GROUP_DEFAULTED
        | SE_DACL_PRESENT          | SE_DACL_DEFAULTED
        | SE_SACL_PRESENT          | SE_SACL_DEFAULTED
        | SE_RM_CONTROL_VALID      | SE_SELF_RELATIVE
        ;

    int     bit;
    DWORD   dwRevision;
    LPCSTR  fmt = "Expected error %s, got %u\n";

    GetSecurityDescriptorControl (sec, &ref, &dwRevision);

    /* The mutable bits are mutable regardless of the truth of
       SE_DACL_PRESENT and/or SE_SACL_PRESENT */

    /* Check call barfs if any bit-of-interest is immutable */
    for (bit = 0; bit < 16; ++bit)
    {
        SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
        SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;

        SECURITY_DESCRIPTOR_CONTROL ctrl;

        DWORD   dwExpect  = (bitOfInterest & immutable)
                          ?  ERROR_INVALID_PARAMETER  :  0xbebecaca;
        LPCSTR  strExpect = (bitOfInterest & immutable)
                          ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";

        ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
        setOrClear ^= bitOfInterest;
        SetLastError (0xbebecaca);
        pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
        ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
        GetSecurityDescriptorControl(sec, &test, &dwRevision);
        expect_eq(test, ctrl, int, "%x");

        setOrClear ^= bitOfInterest;
        SetLastError (0xbebecaca);
        pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
        ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
        GetSecurityDescriptorControl (sec, &test, &dwRevision);
        expect_eq(test, ref, int, "%x");
    }

    /* Check call barfs if any bit-to-set is immutable
       even when not a bit-of-interest */
    for (bit = 0; bit < 16; ++bit)
    {
        SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
        SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;

        SECURITY_DESCRIPTOR_CONTROL ctrl;

        DWORD   dwExpect  = ((1 << bit) & immutable)
                          ?  ERROR_INVALID_PARAMETER  :  0xbebecaca;
        LPCSTR  strExpect = ((1 << bit) & immutable)
                          ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";

        ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
        setOrClear ^= bitsOfInterest;
        SetLastError (0xbebecaca);
        pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
        ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
        GetSecurityDescriptorControl(sec, &test, &dwRevision);
        expect_eq(test, ctrl, int, "%x");

        ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
        setOrClear ^= bitsOfInterest;
        SetLastError (0xbebecaca);
        pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
        ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
        GetSecurityDescriptorControl(sec, &test, &dwRevision);
        expect_eq(test, ctrl, int, "%x");
    }
}

3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
static void test_PrivateObjectSecurity(void)
{
    SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
    SECURITY_DESCRIPTOR_CONTROL ctrl;
    PSECURITY_DESCRIPTOR sec;
    DWORD dwDescSize;
    DWORD dwRevision;
    DWORD retSize;
    LPSTR string;
    ULONG len;
    PSECURITY_DESCRIPTOR buf;
3400
    BOOL ret;
3401

3402 3403
    if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
    {
3404
        win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3405 3406 3407
        return;
    }

3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
    ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
        "O:SY"
        "G:S-1-5-21-93476-23408-4576"
        "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
          "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
        "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
        SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");

    test_SetSecurityDescriptorControl(sec);

    LocalFree(sec);

    ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
        "O:SY"
        "G:S-1-5-21-93476-23408-4576",
        SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");

    test_SetSecurityDescriptorControl(sec);

    LocalFree(sec);

3429
    ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3430 3431 3432 3433 3434
        "O:SY"
        "G:S-1-5-21-93476-23408-4576"
        "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
        "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
    buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
3435
    pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
3436
    GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
3437
    expect_eq(ctrl, 0x9014, int, "%x");
3438

3439 3440
    ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
    ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3441
    ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3442
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3443 3444 3445 3446
    CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
    GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
    expect_eq(ctrl, 0x8000, int, "%x");

3447 3448
    ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
    ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3449
    ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3450 3451
    ret = pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len);
    ok(ret, "Conversion failed err=%u\n", GetLastError());
3452 3453
    CHECK_ONE_OF_AND_FREE("G:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)",
        "G:S-1-5-21-93476-23408-4576D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"); /* Win7 */
3454
    GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3455
    expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8004, int, "%x");
3456

3457 3458
    ret = GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize);
    ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3459
    ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3460
    ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3461
    CHECK_ONE_OF_AND_FREE("O:SY"
3462 3463
        "G:S-1-5-21-93476-23408-4576"
        "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3464 3465 3466 3467 3468
        "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
      "O:SY"
        "G:S-1-5-21-93476-23408-4576"
        "D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
        "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)"); /* Win7 */
3469
    GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3470
    expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8014, int, "%x");
3471

3472 3473 3474
    SetLastError(0xdeadbeef);
    ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
3475

3476
    LocalFree(sec);
3477
    HeapFree(GetProcessHeap(), 0, buf);
3478
}
3479
#undef CHECK_RESULT_AND_FREE
3480
#undef CHECK_ONE_OF_AND_FREE
3481

3482 3483 3484 3485 3486 3487 3488 3489
static void test_acls(void)
{
    char buffer[256];
    PACL pAcl = (PACL)buffer;
    BOOL ret;

    SetLastError(0xdeadbeef);
    ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
3490 3491
    if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
3492
        win_skip("InitializeAcl is not implemented\n");
3493 3494 3495
        return;
    }

3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
    ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());

    ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
    ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());

    ret = IsValidAcl(pAcl);
    ok(ret, "IsValidAcl failed with error %d\n", GetLastError());

    ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
    ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());

    ret = IsValidAcl(pAcl);
    ok(ret, "IsValidAcl failed with error %d\n", GetLastError());

3518
    SetLastError(0xdeadbeef);
3519
    ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
3520 3521 3522
    if (GetLastError() != ERROR_INVALID_PARAMETER)
    {
        ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
3523

3524 3525 3526 3527 3528
        ret = IsValidAcl(pAcl);
        ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
    }
    else
        win_skip("ACL_REVISION4 is not implemented on NT4\n");
3529 3530 3531 3532 3533 3534

    SetLastError(0xdeadbeef);
    ret = InitializeAcl(pAcl, sizeof(buffer), -1);
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
}

3535 3536 3537 3538 3539 3540 3541 3542
static void test_GetSecurityInfo(void)
{
    HANDLE obj;
    PSECURITY_DESCRIPTOR sd;
    PSID owner, group;
    PACL dacl;
    DWORD ret;

3543 3544 3545 3546 3547 3548
    if (!pGetSecurityInfo)
    {
        win_skip("GetSecurityInfo is not available\n");
        return;
    }

3549 3550 3551
    /* Create something.  Files have lots of associated security info.  */
    obj = CreateFile(myARGV[0], GENERIC_READ, FILE_SHARE_READ, NULL,
                     OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3552
    if (obj == INVALID_HANDLE_VALUE)
3553 3554 3555 3556 3557
    {
        skip("Couldn't create an object for GetSecurityInfo test\n");
        return;
    }

3558
    ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3559 3560
                          OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
                          &owner, &group, &dacl, NULL, &sd);
3561 3562 3563 3564 3565 3566
    if (ret == ERROR_CALL_NOT_IMPLEMENTED)
    {
        win_skip("GetSecurityInfo is not implemented\n");
        CloseHandle(obj);
        return;
    }
3567 3568 3569 3570
    ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
    ok(sd != NULL, "GetSecurityInfo\n");
    ok(owner != NULL, "GetSecurityInfo\n");
    ok(group != NULL, "GetSecurityInfo\n");
3571 3572 3573 3574
    if (dacl != NULL)
        ok(IsValidAcl(dacl), "GetSecurityInfo\n");
    else
        win_skip("No ACL information returned\n");
3575 3576

    LocalFree(sd);
3577

3578 3579 3580 3581 3582 3583 3584
    if (!pCreateWellKnownSid)
    {
        win_skip("NULL parameter test would crash on NT4\n");
        CloseHandle(obj);
        return;
    }

3585 3586
    /* If we don't ask for the security descriptor, Windows will still give us
       the other stuff, leaving us no way to free it.  */
3587
    ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3588 3589 3590 3591 3592
                          OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
                          &owner, &group, &dacl, NULL, NULL);
    ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
    ok(owner != NULL, "GetSecurityInfo\n");
    ok(group != NULL, "GetSecurityInfo\n");
3593 3594 3595 3596
    if (dacl != NULL)
        ok(IsValidAcl(dacl), "GetSecurityInfo\n");
    else
        win_skip("No ACL information returned\n");
3597

3598 3599 3600
    CloseHandle(obj);
}

3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
static void test_GetSidSubAuthority(void)
{
    PSID psid = NULL;

    if (!pGetSidSubAuthority || !pConvertStringSidToSidA || !pIsValidSid || !pGetSidSubAuthorityCount)
    {
        win_skip("Some functions not available\n");
        return;
    }
    /* Note: on windows passing in an invalid index like -1, lets GetSidSubAuthority return 0x05000000 but
             still GetLastError returns ERROR_SUCCESS then. We don't test these unlikely cornercases here for now */
    ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576",&psid),"ConvertStringSidToSidA failed\n");
    ok(pIsValidSid(psid),"Sid is not valid\n");
    SetLastError(0xbebecaca);
    ok(*pGetSidSubAuthorityCount(psid) == 4,"GetSidSubAuthorityCount gave %d expected 4\n",*pGetSidSubAuthorityCount(psid));
    ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
    SetLastError(0xbebecaca);
3618
    ok(*pGetSidSubAuthority(psid,0) == 21,"GetSidSubAuthority gave %d expected 21\n",*pGetSidSubAuthority(psid,0));
3619 3620
    ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
    SetLastError(0xbebecaca);
3621
    ok(*pGetSidSubAuthority(psid,1) == 93476,"GetSidSubAuthority gave %d expected 93476\n",*pGetSidSubAuthority(psid,1));
3622 3623
    ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
    SetLastError(0xbebecaca);
3624
    ok(pGetSidSubAuthority(psid,4) != NULL,"Expected out of bounds GetSidSubAuthority to return a non-NULL pointer\n");
3625 3626 3627 3628
    ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
    LocalFree(psid);
}

3629 3630 3631 3632
static void test_CheckTokenMembership(void)
{
    PTOKEN_GROUPS token_groups;
    DWORD size;
3633
    HANDLE process_token, token;
3634 3635 3636 3637
    BOOL is_member;
    BOOL ret;
    DWORD i;

3638 3639 3640 3641 3642
    if (!pCheckTokenMembership)
    {
        win_skip("CheckTokenMembership is not available\n");
        return;
    }
3643
    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
3644 3645
    ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());

3646 3647 3648
    ret = DuplicateToken(process_token, SecurityImpersonation, &token);
    ok(ret, "DuplicateToken failed with error %d\n", GetLastError());

3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671
    /* groups */
    ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
    ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
        "GetTokenInformation(TokenGroups) %s with error %d\n",
        ret ? "succeeded" : "failed", GetLastError());
    token_groups = HeapAlloc(GetProcessHeap(), 0, size);
    ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
    ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());

    for (i = 0; i < token_groups->GroupCount; i++)
    {
        if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
            break;
    }

    if (i == token_groups->GroupCount)
    {
        HeapFree(GetProcessHeap(), 0, token_groups);
        CloseHandle(token);
        skip("user not a member of any group\n");
        return;
    }

3672
    is_member = FALSE;
3673
    ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
3674
    ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
3675 3676
    ok(is_member, "CheckTokenMembership should have detected sid as member\n");

3677
    is_member = FALSE;
3678 3679 3680 3681
    ret = pCheckTokenMembership(NULL, token_groups->Groups[i].Sid, &is_member);
    ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
    ok(is_member, "CheckTokenMembership should have detected sid as member\n");

3682 3683
    is_member = TRUE;
    SetLastError(0xdeadbeef);
3684 3685 3686 3687 3688
    ret = pCheckTokenMembership(process_token, token_groups->Groups[i].Sid, &is_member);
    ok(!ret && GetLastError() == ERROR_NO_IMPERSONATION_TOKEN,
        "CheckTokenMembership with process token %s with error %d\n",
        ret ? "succeeded" : "failed", GetLastError());
    ok(!is_member, "CheckTokenMembership should have cleared is_member\n");
3689 3690 3691

    HeapFree(GetProcessHeap(), 0, token_groups);
    CloseHandle(token);
3692
    CloseHandle(process_token);
3693 3694
}

3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
static void test_EqualSid(void)
{
    PSID sid1, sid2;
    BOOL ret;
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };

    SetLastError(0xdeadbeef);
    ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid1);
3705 3706 3707 3708 3709
    if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
        win_skip("AllocateAndInitializeSid is not implemented\n");
        return;
    }
3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721
    ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
    ok(GetLastError() == 0xdeadbeef,
       "AllocateAndInitializeSid shouldn't have set last error to %d\n",
       GetLastError());

    ret = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
        0, 0, 0, 0, 0, 0, 0, &sid2);
    ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = EqualSid(sid1, sid2);
    ok(!ret, "World and domain admins sids shouldn't have been equal\n");
3722 3723
    ok(GetLastError() == ERROR_SUCCESS ||
       broken(GetLastError() == 0xdeadbeef), /* NT4 */
3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
       "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
       GetLastError());

    SetLastError(0xdeadbeef);
    sid2 = FreeSid(sid2);
    ok(!sid2, "FreeSid should have returned NULL instead of %p\n", sid2);
    ok(GetLastError() == 0xdeadbeef,
       "FreeSid shouldn't have set last error to %d\n",
       GetLastError());

    ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid2);
    ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = EqualSid(sid1, sid2);
    ok(ret, "Same sids should have been equal\n");
3741 3742
    ok(GetLastError() == ERROR_SUCCESS ||
       broken(GetLastError() == 0xdeadbeef), /* NT4 */
3743 3744 3745 3746 3747 3748 3749
       "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
       GetLastError());

    ((SID *)sid2)->Revision = 2;
    SetLastError(0xdeadbeef);
    ret = EqualSid(sid1, sid2);
    ok(!ret, "EqualSid with invalid sid should have returned FALSE\n");
3750 3751
    ok(GetLastError() == ERROR_SUCCESS ||
       broken(GetLastError() == 0xdeadbeef), /* NT4 */
3752 3753 3754 3755 3756 3757 3758 3759
       "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
       GetLastError());
    ((SID *)sid2)->Revision = SID_REVISION;

    FreeSid(sid1);
    FreeSid(sid2);
}

3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
static void test_GetUserNameA(void)
{
    char buffer[UNLEN + 1], filler[UNLEN + 1];
    DWORD required_len, buffer_len;
    BOOL ret;

    /* Test crashes on Windows. */
    if (0)
    {
        SetLastError(0xdeadbeef);
        GetUserNameA(NULL, NULL);
    }

    SetLastError(0xdeadbeef);
    required_len = 0;
    ret = GetUserNameA(NULL, &required_len);
    ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
    ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    required_len = 1;
    ret = GetUserNameA(NULL, &required_len);
    ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
    ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());

    /* Tests crashes on Windows. */
    if (0)
    {
        SetLastError(0xdeadbeef);
        required_len = UNLEN + 1;
        GetUserNameA(NULL, &required_len);

        SetLastError(0xdeadbeef);
        GetUserNameA(buffer, NULL);
    }

    memset(filler, 'x', sizeof(filler));

    /* Note that GetUserNameA on XP and newer outputs the number of bytes
     * required for a Unicode string, which affects a test in the next block. */
    SetLastError(0xdeadbeef);
    memcpy(buffer, filler, sizeof(filler));
    required_len = 0;
    ret = GetUserNameA(buffer, &required_len);
    ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
    ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
    ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    memcpy(buffer, filler, sizeof(filler));
    buffer_len = required_len;
    ret = GetUserNameA(buffer, &buffer_len);
    ok(ret == TRUE, "GetUserNameA returned %d, last error %u\n", ret, GetLastError());
    ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
    ok(buffer_len == required_len ||
       broken(buffer_len == required_len / sizeof(WCHAR)), /* XP+ */
       "Outputted buffer length was %u\n", buffer_len);

    /* Use the reported buffer size from the last GetUserNameA call and pass
     * a length that is one less than the required value. */
    SetLastError(0xdeadbeef);
    memcpy(buffer, filler, sizeof(filler));
    buffer_len--;
    ret = GetUserNameA(buffer, &buffer_len);
    ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
    ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was untouched\n");
    ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
}

static void test_GetUserNameW(void)
{
    WCHAR buffer[UNLEN + 1], filler[UNLEN + 1];
    DWORD required_len, buffer_len;
    BOOL ret;

    /* Test crashes on Windows. */
    if (0)
    {
        SetLastError(0xdeadbeef);
        GetUserNameW(NULL, NULL);
    }

    SetLastError(0xdeadbeef);
    required_len = 0;
    ret = GetUserNameW(NULL, &required_len);
    ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
    ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    required_len = 1;
    ret = GetUserNameW(NULL, &required_len);
    ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
    ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());

    /* Tests crash on Windows. */
    if (0)
    {
        SetLastError(0xdeadbeef);
        required_len = UNLEN + 1;
        GetUserNameW(NULL, &required_len);

        SetLastError(0xdeadbeef);
        GetUserNameW(buffer, NULL);
    }

    memset(filler, 'x', sizeof(filler));

    SetLastError(0xdeadbeef);
    memcpy(buffer, filler, sizeof(filler));
    required_len = 0;
    ret = GetUserNameW(buffer, &required_len);
    ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
    ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
    ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    memcpy(buffer, filler, sizeof(filler));
    buffer_len = required_len;
    ret = GetUserNameW(buffer, &buffer_len);
    ok(ret == TRUE, "GetUserNameW returned %d, last error %u\n", ret, GetLastError());
    ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
    ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);

    /* GetUserNameW on XP and newer writes a truncated portion of the username string to the buffer. */
    SetLastError(0xdeadbeef);
    memcpy(buffer, filler, sizeof(filler));
    buffer_len--;
    ret = GetUserNameW(buffer, &buffer_len);
    ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
    ok(!memcmp(buffer, filler, sizeof(filler)) ||
       broken(memcmp(buffer, filler, sizeof(filler)) != 0), /* XP+ */
       "Output buffer was altered\n");
    ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
}

3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955
static void test_CreateRestrictedToken(void)
{
    HANDLE process_token, token, r_token;
    PTOKEN_GROUPS token_groups, groups2;
    SID_AND_ATTRIBUTES sattr;
    BOOL is_member;
    DWORD size;
    BOOL ret;
    DWORD i, j;

    if (!pCreateRestrictedToken)
    {
        win_skip("CreateRestrictedToken is not available\n");
        return;
    }

    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
    ok(ret, "got error %d\n", GetLastError());

    ret = DuplicateTokenEx(process_token, TOKEN_DUPLICATE|TOKEN_ADJUST_GROUPS|TOKEN_QUERY,
        NULL, SecurityImpersonation, TokenImpersonation, &token);
    ok(ret, "got error %d\n", GetLastError());

    /* groups */
    ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
    ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
        "got %d with error %d\n", ret, GetLastError());
    token_groups = HeapAlloc(GetProcessHeap(), 0, size);
    ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
    ok(ret, "got error %d\n", GetLastError());

    for (i = 0; i < token_groups->GroupCount; i++)
    {
        if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
            break;
    }

    if (i == token_groups->GroupCount)
    {
        HeapFree(GetProcessHeap(), 0, token_groups);
        CloseHandle(token);
        skip("User not a member of any group\n");
        return;
    }

    is_member = FALSE;
    ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
    ok(ret, "got error %d\n", GetLastError());
    ok(is_member, "not a member\n");

    /* disable a SID in new token */
    sattr.Sid = token_groups->Groups[i].Sid;
    sattr.Attributes = 0;
3956
    r_token = NULL;
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994
    ret = pCreateRestrictedToken(token, 0, 1, &sattr, 0, NULL, 0, NULL, &r_token);
    todo_wine ok(ret, "got error %d\n", GetLastError());

    if (ret)
    {
        /* check if a SID is enabled */
        is_member = TRUE;
        ret = pCheckTokenMembership(r_token, token_groups->Groups[i].Sid, &is_member);
        ok(ret, "got error %d\n", GetLastError());
        ok(!is_member, "not a member\n");

        ret = GetTokenInformation(r_token, TokenGroups, NULL, 0, &size);
        ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d with error %d\n",
            ret, GetLastError());
        groups2 = HeapAlloc(GetProcessHeap(), 0, size);
        ret = GetTokenInformation(r_token, TokenGroups, groups2, size, &size);
        ok(ret, "got error %d\n", GetLastError());

        for (j = 0; j < groups2->GroupCount; j++)
        {
            if (EqualSid(groups2->Groups[j].Sid, token_groups->Groups[i].Sid))
                break;
        }

        ok(groups2->Groups[j].Attributes & SE_GROUP_USE_FOR_DENY_ONLY,
            "got wrong attributes\n");
        ok((groups2->Groups[j].Attributes & SE_GROUP_ENABLED) == 0,
            "got wrong attributes\n");

        HeapFree(GetProcessHeap(), 0, groups2);
    }

    HeapFree(GetProcessHeap(), 0, token_groups);
    CloseHandle(r_token);
    CloseHandle(token);
    CloseHandle(process_token);
}

3995 3996 3997 3998 3999 4000
static void validate_default_security_descriptor(SECURITY_DESCRIPTOR *sd)
{
    BOOL ret, present, defaulted;
    ACL *acl;
    void *sid;

4001 4002 4003
    ret = IsValidSecurityDescriptor(sd);
    ok(ret, "security descriptor is not valid\n");

4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
    present = -1;
    defaulted = -1;
    acl = (void *)0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
    ok(ret, "GetSecurityDescriptorDacl error %d\n", GetLastError());
todo_wine
    ok(present == 1, "acl is not present\n");
todo_wine
    ok(acl != (void *)0xdeadbeef && acl != NULL, "acl pointer is not set\n");
    ok(defaulted == 0, "defaulted is set to TRUE\n");

    defaulted = -1;
    sid = (void *)0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetSecurityDescriptorOwner(sd, &sid, &defaulted);
    ok(ret, "GetSecurityDescriptorOwner error %d\n", GetLastError());
todo_wine
    ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
    ok(defaulted == 0, "defaulted is set to TRUE\n");

    defaulted = -1;
    sid = (void *)0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetSecurityDescriptorGroup(sd, &sid, &defaulted);
    ok(ret, "GetSecurityDescriptorGroup error %d\n", GetLastError());
todo_wine
    ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
    ok(defaulted == 0, "defaulted is set to TRUE\n");
}

static void test_default_handle_security(HANDLE token, HANDLE handle, GENERIC_MAPPING *mapping)
{
    DWORD ret, length, needed, granted, priv_set_len;
    BOOL status;
    PRIVILEGE_SET priv_set;
    SECURITY_DESCRIPTOR *sd;

    needed = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
                                  NULL, 0, &needed);
    ok(!ret, "GetKernelObjectSecurity should fail\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(needed != 0xdeadbeef, "GetKernelObjectSecurity should return required buffer length\n");

    length = needed;
    sd = HeapAlloc(GetProcessHeap(), 0, length);

4053
    needed = 0xdeadbeef;
4054 4055 4056 4057
    SetLastError(0xdeadbeef);
    ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
                                  sd, length, &needed);
    ok(ret, "GetKernelObjectSecurity error %d\n", GetLastError());
4058
    ok(needed == length || needed == 0 /* file, pipe */, "GetKernelObjectSecurity should return %u instead of %u\n", length, needed);
4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069

    validate_default_security_descriptor(sd);

    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = AccessCheck(sd, token, MAXIMUM_ALLOWED, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
    ok(ret, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
4070
    ok(granted == mapping->GenericAll, "expected all access %#x, got %#x\n", mapping->GenericAll, granted);
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090
}
    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = AccessCheck(sd, token, 0, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
    ok(ret, "AccessCheck error %d\n", GetLastError());
    ok(status == 0 || broken(status == 1) /* NT4 */, "expected 0, got %d\n", status);
    ok(granted == 0 || broken(granted == mapping->GenericRead) /* NT4 */, "expected 0, got %#x\n", granted);
}
    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = AccessCheck(sd, token, ACCESS_SYSTEM_SECURITY, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
    ok(ret, "AccessCheck error %d\n", GetLastError());
    ok(status == 0, "expected 0, got %d\n", status);
    ok(granted == 0, "expected 0, got %#x\n", granted);
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120
}
    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = AccessCheck(sd, token, mapping->GenericRead, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
    ok(ret, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == mapping->GenericRead, "expected read access %#x, got %#x\n", mapping->GenericRead, granted);
}
    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = AccessCheck(sd, token, mapping->GenericWrite, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
    ok(ret, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == mapping->GenericWrite, "expected write access %#x, got %#x\n", mapping->GenericWrite, granted);
}
    priv_set_len = sizeof(priv_set);
    granted = 0xdeadbeef;
    status = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = AccessCheck(sd, token, mapping->GenericExecute, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
    ok(ret, "AccessCheck error %d\n", GetLastError());
    ok(status == 1, "expected 1, got %d\n", status);
    ok(granted == mapping->GenericExecute, "expected execute access %#x, got %#x\n", mapping->GenericExecute, granted);
4121 4122 4123 4124 4125 4126 4127
}
    HeapFree(GetProcessHeap(), 0, sd);
}

static void test_mutex_security(HANDLE token)
{
    HANDLE mutex;
4128 4129
    GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE | SYNCHRONIZE,
                                STANDARD_RIGHTS_WRITE | MUTEX_MODIFY_STATE | SYNCHRONIZE,
4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
                                STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
                                STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS };

    SetLastError(0xdeadbeef);
    mutex = OpenMutex(0, FALSE, "WineTestMutex");
    ok(!mutex, "mutex should not exist\n");
    ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    mutex = CreateMutex(NULL, FALSE, "WineTestMutex");
    ok(mutex != 0, "CreateMutex error %d\n", GetLastError());

    test_default_handle_security(token, mutex, &mapping);

    CloseHandle (mutex);
}

4147 4148 4149
static void test_event_security(HANDLE token)
{
    HANDLE event;
4150 4151
    GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | EVENT_QUERY_STATE | SYNCHRONIZE,
                                STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE | SYNCHRONIZE,
4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
                                STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
                                STANDARD_RIGHTS_ALL | EVENT_ALL_ACCESS };

    SetLastError(0xdeadbeef);
    event = OpenEvent(0, FALSE, "WineTestEvent");
    ok(!event, "event should not exist\n");
    ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    event = CreateEvent(NULL, FALSE, FALSE, "WineTestEvent");
    ok(event != 0, "CreateEvent error %d\n", GetLastError());

    test_default_handle_security(token, event, &mapping);

    CloseHandle(event);
}

4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198
#define WINE_TEST_PIPE "\\\\.\\pipe\\WineTestPipe"
static void test_named_pipe_security(HANDLE token)
{
    HANDLE pipe, file;
    GENERIC_MAPPING mapping = { FILE_GENERIC_READ,
                                FILE_GENERIC_WRITE,
                                FILE_GENERIC_EXECUTE,
                                STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS };

    SetLastError(0xdeadbeef);
    pipe = CreateNamedPipe(WINE_TEST_PIPE, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
                           PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES,
                           0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL);
    ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe error %d\n", GetLastError());

    test_default_handle_security(token, pipe, &mapping);

    SetLastError(0xdeadbeef);
    file = CreateFile(WINE_TEST_PIPE, FILE_ALL_ACCESS, 0, NULL, OPEN_EXISTING, 0, 0);
    ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
    CloseHandle(file);

    CloseHandle(pipe);

    SetLastError(0xdeadbeef);
    file = CreateFile("\\\\.\\pipe\\", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
    ok(file != INVALID_HANDLE_VALUE || broken(file == INVALID_HANDLE_VALUE) /* before Vista */, "CreateFile error %d\n", GetLastError());
    CloseHandle(file);
}

4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
static BOOL validate_impersonation_token(HANDLE token, DWORD *token_type)
{
    DWORD ret, needed;
    TOKEN_TYPE type;
    SECURITY_IMPERSONATION_LEVEL sil;

    type = 0xdeadbeef;
    needed = 0;
    SetLastError(0xdeadbeef);
    ret = GetTokenInformation(token, TokenType, &type, sizeof(type), &needed);
    ok(ret, "GetTokenInformation error %d\n", GetLastError());
    ok(needed == sizeof(type), "GetTokenInformation should return required buffer length\n");
    ok(type == TokenPrimary || type == TokenImpersonation, "expected TokenPrimary or TokenImpersonation, got %d\n", type);

    *token_type = type;
    if (type != TokenImpersonation) return FALSE;

    needed = 0;
    SetLastError(0xdeadbeef);
    ret = GetTokenInformation(token, TokenImpersonationLevel, &sil, sizeof(sil), &needed);
    ok(ret, "GetTokenInformation error %d\n", GetLastError());
    ok(needed == sizeof(sil), "GetTokenInformation should return required buffer length\n");
    ok(sil == SecurityImpersonation, "expected SecurityImpersonation, got %d\n", sil);

    needed = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &needed);
    ok(!ret, "GetTokenInformation should fail\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
    ok(needed > sizeof(TOKEN_DEFAULT_DACL), "GetTokenInformation returned empty default DACL\n");

    needed = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetTokenInformation(token, TokenOwner, NULL, 0, &needed);
    ok(!ret, "GetTokenInformation should fail\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
    ok(needed > sizeof(TOKEN_OWNER), "GetTokenInformation returned empty token owner\n");

    needed = 0xdeadbeef;
    SetLastError(0xdeadbeef);
    ret = GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &needed);
    ok(!ret, "GetTokenInformation should fail\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
    ok(needed > sizeof(TOKEN_PRIMARY_GROUP), "GetTokenInformation returned empty token primary group\n");

    return TRUE;
}

static void test_kernel_objects_security(void)
{
    HANDLE token, process_token;
    DWORD ret, token_type;

    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process_token);
    ok(ret, "OpenProcessToken error %d\n", GetLastError());

    ret = validate_impersonation_token(process_token, &token_type);
    ok(token_type == TokenPrimary, "expected TokenPrimary, got %d\n", token_type);
    ok(!ret, "access token should not be an impersonation token\n");

    ret = DuplicateToken(process_token, SecurityImpersonation, &token);
    ok(ret, "DuplicateToken error %d\n", GetLastError());

    ret = validate_impersonation_token(token, &token_type);
    ok(ret, "access token should be a valid impersonation token\n");
    ok(token_type == TokenImpersonation, "expected TokenImpersonation, got %d\n", token_type);

    test_mutex_security(token);
4270
    test_event_security(token);
4271
    test_named_pipe_security(token);
4272 4273 4274 4275 4276 4277
    /* FIXME: test other kernel object types */

    CloseHandle(process_token);
    CloseHandle(token);
}

4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327
static void test_TokenIntegrityLevel(void)
{
    TOKEN_MANDATORY_LABEL *tml;
    BYTE buffer[64];        /* using max. 28 byte in win7 x64 */
    HANDLE token;
    DWORD size;
    DWORD res;
    char *sidname = NULL;
    static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
                                                    {SECURITY_MANDATORY_HIGH_RID}};
    static SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
                                                    {SECURITY_MANDATORY_MEDIUM_RID}};

    SetLastError(0xdeadbeef);
    res = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
    ok(res, "got %d with %d (expected TRUE)\n", res, GetLastError());

    SetLastError(0xdeadbeef);
    res = GetTokenInformation(token, TokenIntegrityLevel, buffer, sizeof(buffer), &size);

    /* not supported before Vista */
    if (!res && (GetLastError() == ERROR_INVALID_PARAMETER))
    {
        win_skip("TokenIntegrityLevel not supported\n");
        CloseHandle(token);
        return;
    }

    ok(res, "got %u with %u (expected TRUE)\n", res, GetLastError());
    if (!res)
    {
        CloseHandle(token);
        return;
    }

    tml = (TOKEN_MANDATORY_LABEL*) buffer;
    ok(tml->Label.Attributes == (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED),
        "got 0x%x (expected 0x%x)\n", tml->Label.Attributes, (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED));

    SetLastError(0xdeadbeef);
    res = pConvertSidToStringSidA(tml->Label.Sid, &sidname);
    ok(res, "got %u and %u\n", res, GetLastError());

    ok(EqualSid(tml->Label.Sid, &medium_level) || EqualSid(tml->Label.Sid, &high_level),
        "got %s (expected 'S-1-16-8192' or 'S-1-16-12288')\n", sidname);

    LocalFree(sidname);
    CloseHandle(token);
}

4328 4329
START_TEST(security)
{
4330 4331
    init();
    if (!hmod) return;
4332 4333 4334 4335 4336 4337

    if (myARGC >= 3)
    {
        test_process_security_child();
        return;
    }
4338
    test_kernel_objects_security();
4339
    test_sid();
4340
    test_trustee();
4341
    test_luid();
4342
    test_CreateWellKnownSid();
4343
    test_FileSecurity();
4344
    test_AccessCheck();
4345
    test_token_attr();
4346
    test_LookupAccountSid();
4347
    test_LookupAccountName();
4348
    test_security_descriptor();
4349
    test_process_security();
4350
    test_impersonation_level();
4351 4352
    test_SetEntriesInAclW();
    test_SetEntriesInAclA();
4353
    test_GetNamedSecurityInfoA();
4354
    test_ConvertStringSecurityDescriptor();
4355
    test_ConvertSecurityDescriptorToString();
4356
    test_PrivateObjectSecurity();
4357
    test_acls();
4358
    test_GetSecurityInfo();
4359
    test_GetSidSubAuthority();
4360
    test_CheckTokenMembership();
4361
    test_EqualSid();
4362 4363
    test_GetUserNameA();
    test_GetUserNameW();
4364
    test_CreateRestrictedToken();
4365
    test_TokenIntegrityLevel();
4366
}