2 * Unit tests for security functions
4 * Copyright (c) 2004 Mike McCormack
5 * Copyright (c) 2011 Dmitry Timoshkov
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * 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
26 #define WIN32_NO_STATUS
36 #include "wine/test.h"
38 /* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
39 #define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)
41 #ifndef EVENT_QUERY_STATE
42 #define EVENT_QUERY_STATE 0x0001
45 /* copied from Wine winternl.h - not included in the Windows SDK */
46 typedef enum _OBJECT_INFORMATION_CLASS {
47 ObjectBasicInformation,
48 ObjectNameInformation,
49 ObjectTypeInformation,
52 } OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;
54 typedef struct _OBJECT_BASIC_INFORMATION {
56 ACCESS_MASK GrantedAccess;
60 ULONG NonPagedPoolUsage;
62 ULONG NameInformationLength;
63 ULONG TypeInformationLength;
64 ULONG SecurityDescriptorLength;
65 LARGE_INTEGER CreateTime;
66 } OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;
68 #define expect_eq(expr, value, type, format) { type ret_ = expr; ok((value) == ret_, #expr " expected " format " got " format "\n", (value), (ret_)); }
70 static BOOL (WINAPI *pAddAccessAllowedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
71 static BOOL (WINAPI *pAddAccessDeniedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
72 static BOOL (WINAPI *pAddAuditAccessAceEx)(PACL, DWORD, DWORD, DWORD, PSID, BOOL, BOOL);
73 static VOID (WINAPI *pBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
74 static VOID (WINAPI *pBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
75 static VOID (WINAPI *pBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
76 POBJECTS_AND_NAME_A pObjName,
77 SE_OBJECT_TYPE ObjectType,
79 LPSTR InheritedObjectTypeName,
81 static VOID (WINAPI *pBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
82 POBJECTS_AND_SID pObjSid,
84 GUID* pInheritedObjectGuid,
86 static LPSTR (WINAPI *pGetTrusteeNameA)( PTRUSTEEA pTrustee );
87 static BOOL (WINAPI *pMakeSelfRelativeSD)( PSECURITY_DESCRIPTOR, PSECURITY_DESCRIPTOR, LPDWORD );
88 static BOOL (WINAPI *pConvertSidToStringSidA)( PSID pSid, LPSTR *str );
89 static BOOL (WINAPI *pConvertStringSidToSidA)( LPCSTR str, PSID pSid );
90 static BOOL (WINAPI *pCheckTokenMembership)(HANDLE, PSID, PBOOL);
91 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
92 PSECURITY_DESCRIPTOR*, PULONG );
93 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorW)(LPCWSTR, DWORD,
94 PSECURITY_DESCRIPTOR*, PULONG );
95 static BOOL (WINAPI *pConvertSecurityDescriptorToStringSecurityDescriptorA)(PSECURITY_DESCRIPTOR, DWORD,
96 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 static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
102 PSID*, PSID*, PACL*, PACL*,
103 PSECURITY_DESCRIPTOR*);
104 static DWORD (WINAPI *pSetNamedSecurityInfoA)(LPTSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
105 PSID, PSID, PACL, PACL);
106 static PDWORD (WINAPI *pGetSidSubAuthority)(PSID, DWORD);
107 static PUCHAR (WINAPI *pGetSidSubAuthorityCount)(PSID);
108 static BOOL (WINAPI *pIsValidSid)(PSID);
109 static DWORD (WINAPI *pRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
110 static BOOL (WINAPI *pCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
111 static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
112 SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
114 static NTSTATUS (WINAPI *pLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
115 static NTSTATUS (WINAPI *pLsaClose)(LSA_HANDLE);
116 static NTSTATUS (WINAPI *pLsaFreeMemory)(PVOID);
117 static NTSTATUS (WINAPI *pLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
118 static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
119 static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
120 static DWORD (WINAPI *pSetEntriesInAclA)(ULONG, PEXPLICIT_ACCESSA, PACL, PACL*);
121 static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
122 SECURITY_DESCRIPTOR_CONTROL);
123 static DWORD (WINAPI *pGetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
124 PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
125 static DWORD (WINAPI *pSetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
126 PSID, PSID, PACL, PACL);
127 static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
128 PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
129 static BOOL (WINAPI *pCreateRestrictedToken)(HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD,
130 PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
131 static BOOL (WINAPI *pGetAclInformation)(PACL,LPVOID,DWORD,ACL_INFORMATION_CLASS);
132 static BOOL (WINAPI *pGetAce)(PACL,DWORD,LPVOID*);
136 static char** myARGV;
148 SID_IDENTIFIER_AUTHORITY auth;
152 static void init(void)
156 hntdll = GetModuleHandleA("ntdll.dll");
157 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
158 pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
160 hmod = GetModuleHandle("advapi32.dll");
161 pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
162 pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
163 pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
164 pCheckTokenMembership = (void *)GetProcAddress(hmod, "CheckTokenMembership");
165 pConvertStringSecurityDescriptorToSecurityDescriptorA =
166 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
167 pConvertStringSecurityDescriptorToSecurityDescriptorW =
168 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
169 pConvertSecurityDescriptorToStringSecurityDescriptorA =
170 (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
171 pGetFileSecurityA = (void *)GetProcAddress(hmod, "GetFileSecurityA" );
172 pSetFileSecurityA = (void *)GetProcAddress(hmod, "SetFileSecurityA" );
173 pCreateWellKnownSid = (void *)GetProcAddress( hmod, "CreateWellKnownSid" );
174 pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
175 pSetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "SetNamedSecurityInfoA");
176 pGetSidSubAuthority = (void *)GetProcAddress(hmod, "GetSidSubAuthority");
177 pGetSidSubAuthorityCount = (void *)GetProcAddress(hmod, "GetSidSubAuthorityCount");
178 pIsValidSid = (void *)GetProcAddress(hmod, "IsValidSid");
179 pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
180 pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
181 pSetEntriesInAclA = (void *)GetProcAddress(hmod, "SetEntriesInAclA");
182 pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
183 pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
184 pSetSecurityInfo = (void *)GetProcAddress(hmod, "SetSecurityInfo");
185 pCreateRestrictedToken = (void *)GetProcAddress(hmod, "CreateRestrictedToken");
186 pConvertSidToStringSidA = (void *)GetProcAddress(hmod, "ConvertSidToStringSidA");
187 pConvertStringSidToSidA = (void *)GetProcAddress(hmod, "ConvertStringSidToSidA");
188 pGetAclInformation = (void *)GetProcAddress(hmod, "GetAclInformation");
189 pGetAce = (void *)GetProcAddress(hmod, "GetAce");
191 myARGC = winetest_get_mainargs( &myARGV );
194 static void test_sid(void)
196 struct sidRef refs[] = {
197 { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
198 { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
199 { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
200 { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
201 { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
202 { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
204 struct strsid_entry strsid_table[] = {
205 {"AO", STRSID_OK}, {"RU", STRSID_OK}, {"AN", STRSID_OK}, {"AU", STRSID_OK},
206 {"BA", STRSID_OK}, {"BG", STRSID_OK}, {"BO", STRSID_OK}, {"BU", STRSID_OK},
207 {"CA", STRSID_OPT}, {"CG", STRSID_OK}, {"CO", STRSID_OK}, {"DA", STRSID_OPT},
208 {"DC", STRSID_OPT}, {"DD", STRSID_OPT}, {"DG", STRSID_OPT}, {"DU", STRSID_OPT},
209 {"EA", STRSID_OPT}, {"ED", STRSID_OK}, {"WD", STRSID_OK}, {"PA", STRSID_OPT},
210 {"IU", STRSID_OK}, {"LA", STRSID_OK}, {"LG", STRSID_OK}, {"LS", STRSID_OK},
211 {"SY", STRSID_OK}, {"NU", STRSID_OK}, {"NO", STRSID_OK}, {"NS", STRSID_OK},
212 {"PO", STRSID_OK}, {"PS", STRSID_OK}, {"PU", STRSID_OK}, {"RS", STRSID_OPT},
213 {"RD", STRSID_OK}, {"RE", STRSID_OK}, {"RC", STRSID_OK}, {"SA", STRSID_OPT},
214 {"SO", STRSID_OK}, {"SU", STRSID_OK}};
216 const char noSubAuthStr[] = "S-1-5";
223 if( !pConvertSidToStringSidA || !pConvertStringSidToSidA )
225 win_skip("ConvertSidToStringSidA or ConvertStringSidToSidA not available\n");
229 r = pConvertStringSidToSidA( NULL, NULL );
230 ok( !r, "expected failure with NULL parameters\n" );
231 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
233 ok( GetLastError() == ERROR_INVALID_PARAMETER,
234 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
237 r = pConvertStringSidToSidA( refs[0].refStr, NULL );
238 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
239 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
242 r = pConvertStringSidToSidA( NULL, &str );
243 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
244 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
247 r = pConvertStringSidToSidA( noSubAuthStr, &psid );
249 "expected failure with no sub authorities\n" );
250 ok( GetLastError() == ERROR_INVALID_SID,
251 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
254 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
256 ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
257 ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expected 21, got %d\n", pisid->SubAuthority[0]);
258 ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expected 4576, got %d\n", pisid->SubAuthority[3]);
262 for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
264 r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
266 ok( r, "failed to allocate sid\n" );
267 r = pConvertSidToStringSidA( psid, &str );
268 ok( r, "failed to convert sid\n" );
271 ok( !strcmp( str, refs[i].refStr ),
272 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
278 r = pConvertStringSidToSidA( refs[i].refStr, &psid );
279 ok( r, "failed to parse sid string\n" );
282 !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
283 sizeof(refs[i].auth) ),
284 "string sid %s didn't parse to expected value\n"
285 "(got 0x%04x%08x, expected 0x%04x%08x)\n",
287 MAKEWORD( pisid->IdentifierAuthority.Value[1],
288 pisid->IdentifierAuthority.Value[0] ),
289 MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
290 pisid->IdentifierAuthority.Value[4] ),
291 MAKEWORD( pisid->IdentifierAuthority.Value[3],
292 pisid->IdentifierAuthority.Value[2] ) ),
293 MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
294 MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
295 MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
300 /* string constant format not supported before XP */
301 r = pConvertStringSidToSidA(strsid_table[0].str, &psid);
304 win_skip("String constant format not supported\n");
309 for(i = 0; i < sizeof(strsid_table) / sizeof(strsid_table[0]); i++)
313 SetLastError(0xdeadbeef);
314 r = pConvertStringSidToSidA(strsid_table[i].str, &psid);
316 if (!(strsid_table[i].flags & STRSID_OPT))
318 ok(r, "%s: got %u\n", strsid_table[i].str, GetLastError());
323 if ((winetest_debug > 1) && (pConvertSidToStringSidA(psid, &temp)))
325 trace(" %s: %s\n", strsid_table[i].str, temp);
332 if (GetLastError() != ERROR_INVALID_SID)
333 trace(" %s: couldn't be converted, returned %d\n", strsid_table[i].str, GetLastError());
335 trace(" %s: couldn't be converted\n", strsid_table[i].str);
340 static void test_trustee(void)
342 GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
343 GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
345 OBJECTS_AND_NAME_ oan;
349 char szObjectTypeName[] = "ObjectTypeName";
350 char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
351 char szTrusteeName[] = "szTrusteeName";
352 SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
354 memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
356 pBuildTrusteeWithSidA = (void *)GetProcAddress( hmod, "BuildTrusteeWithSidA" );
357 pBuildTrusteeWithNameA = (void *)GetProcAddress( hmod, "BuildTrusteeWithNameA" );
358 pBuildTrusteeWithObjectsAndNameA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
359 pBuildTrusteeWithObjectsAndSidA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
360 pGetTrusteeNameA = (void *)GetProcAddress (hmod, "GetTrusteeNameA" );
361 if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
362 !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
366 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
368 trace( "failed to init SID\n" );
372 /* test BuildTrusteeWithSidA */
373 memset( &trustee, 0xff, sizeof trustee );
374 pBuildTrusteeWithSidA( &trustee, psid );
376 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
377 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
378 "MultipleTrusteeOperation wrong\n");
379 ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
380 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
381 ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
383 /* test BuildTrusteeWithObjectsAndSidA (test 1) */
384 memset( &trustee, 0xff, sizeof trustee );
385 memset( &oas, 0xff, sizeof(oas) );
386 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
387 &InheritedObjectType, psid);
389 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
390 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
391 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
392 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
393 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
395 ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
396 ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
397 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
398 ok(oas.pSid == psid, "pSid wrong\n");
400 /* test GetTrusteeNameA */
401 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
403 /* test BuildTrusteeWithObjectsAndSidA (test 2) */
404 memset( &trustee, 0xff, sizeof trustee );
405 memset( &oas, 0xff, sizeof(oas) );
406 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
407 &InheritedObjectType, psid);
409 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
410 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
411 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
412 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
413 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
415 ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
416 ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
417 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
418 ok(oas.pSid == psid, "pSid wrong\n");
422 /* test BuildTrusteeWithNameA */
423 memset( &trustee, 0xff, sizeof trustee );
424 pBuildTrusteeWithNameA( &trustee, szTrusteeName );
426 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
427 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
428 "MultipleTrusteeOperation wrong\n");
429 ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
430 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
431 ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
433 /* test BuildTrusteeWithObjectsAndNameA (test 1) */
434 memset( &trustee, 0xff, sizeof trustee );
435 memset( &oan, 0xff, sizeof(oan) );
436 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
437 szInheritedObjectTypeName, szTrusteeName);
439 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
440 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
441 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
442 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
443 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
445 ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
446 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
447 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
448 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
450 /* test GetTrusteeNameA */
451 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
453 /* test BuildTrusteeWithObjectsAndNameA (test 2) */
454 memset( &trustee, 0xff, sizeof trustee );
455 memset( &oan, 0xff, sizeof(oan) );
456 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
457 szInheritedObjectTypeName, szTrusteeName);
459 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
460 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
461 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
462 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
463 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
465 ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
466 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
467 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
468 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
470 /* test BuildTrusteeWithObjectsAndNameA (test 3) */
471 memset( &trustee, 0xff, sizeof trustee );
472 memset( &oan, 0xff, sizeof(oan) );
473 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
474 NULL, szTrusteeName);
476 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
477 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
478 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
479 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
480 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
482 ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
483 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
484 ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
485 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
488 /* If the first isn't defined, assume none is */
489 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
490 #define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
491 #define SE_CREATE_TOKEN_PRIVILEGE 2L
492 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
493 #define SE_LOCK_MEMORY_PRIVILEGE 4L
494 #define SE_INCREASE_QUOTA_PRIVILEGE 5L
495 #define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
496 #define SE_TCB_PRIVILEGE 7L
497 #define SE_SECURITY_PRIVILEGE 8L
498 #define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
499 #define SE_LOAD_DRIVER_PRIVILEGE 10L
500 #define SE_SYSTEM_PROFILE_PRIVILEGE 11L
501 #define SE_SYSTEMTIME_PRIVILEGE 12L
502 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
503 #define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
504 #define SE_CREATE_PAGEFILE_PRIVILEGE 15L
505 #define SE_CREATE_PERMANENT_PRIVILEGE 16L
506 #define SE_BACKUP_PRIVILEGE 17L
507 #define SE_RESTORE_PRIVILEGE 18L
508 #define SE_SHUTDOWN_PRIVILEGE 19L
509 #define SE_DEBUG_PRIVILEGE 20L
510 #define SE_AUDIT_PRIVILEGE 21L
511 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
512 #define SE_CHANGE_NOTIFY_PRIVILEGE 23L
513 #define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
514 #define SE_UNDOCK_PRIVILEGE 25L
515 #define SE_SYNC_AGENT_PRIVILEGE 26L
516 #define SE_ENABLE_DELEGATION_PRIVILEGE 27L
517 #define SE_MANAGE_VOLUME_PRIVILEGE 28L
518 #define SE_IMPERSONATE_PRIVILEGE 29L
519 #define SE_CREATE_GLOBAL_PRIVILEGE 30L
520 #define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
521 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
523 static void test_allocateLuid(void)
525 BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
529 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
530 if (!pAllocateLocallyUniqueId) return;
532 ret = pAllocateLocallyUniqueId(&luid1);
533 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
537 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
538 ret = pAllocateLocallyUniqueId(&luid2);
540 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
541 ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
542 "AllocateLocallyUniqueId returned a well-known LUID\n");
543 ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
544 "AllocateLocallyUniqueId returned non-unique LUIDs\n");
545 ret = pAllocateLocallyUniqueId(NULL);
546 ok( !ret && GetLastError() == ERROR_NOACCESS,
547 "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
551 static void test_lookupPrivilegeName(void)
553 BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
554 char buf[MAX_PATH]; /* arbitrary, seems long enough */
555 DWORD cchName = sizeof(buf);
556 LUID luid = { 0, 0 };
560 /* check whether it's available first */
561 pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
562 if (!pLookupPrivilegeNameA) return;
563 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
564 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
565 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
568 /* check with a short buffer */
570 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
571 ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
572 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
573 "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
575 ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
576 "LookupPrivilegeNameA returned an incorrect required length for\n"
577 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
578 lstrlenA("SeCreateTokenPrivilege") + 1);
579 /* check a known value and its returned length on success */
580 cchName = sizeof(buf);
581 ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
582 cchName == strlen("SeCreateTokenPrivilege"),
583 "LookupPrivilegeNameA returned an incorrect output length for\n"
584 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
585 (int)strlen("SeCreateTokenPrivilege"));
586 /* check known values */
587 for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
590 cchName = sizeof(buf);
591 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
592 ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
593 "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
595 /* check a bogus LUID */
596 luid.LowPart = 0xdeadbeef;
597 cchName = sizeof(buf);
598 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
599 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
600 "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
602 /* check on a bogus system */
603 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
604 cchName = sizeof(buf);
605 ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
606 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
607 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
608 "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
618 static void test_lookupPrivilegeValue(void)
620 static const struct NameToLUID privs[] = {
621 { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
622 { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
623 { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
624 { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
625 { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
626 { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
627 { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
628 { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
629 { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
630 { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
631 { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
632 { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
633 { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
634 { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
635 { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
636 { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
637 { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
638 { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
639 { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
640 { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
641 { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
642 { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
643 { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
644 { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
645 { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
646 { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
647 { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
648 { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
649 { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
651 BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
656 /* check whether it's available first */
657 pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
658 if (!pLookupPrivilegeValueA) return;
659 ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
660 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
663 /* check a bogus system name */
664 ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
665 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
666 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
667 "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
669 /* check a NULL string */
670 ret = pLookupPrivilegeValueA(NULL, 0, &luid);
671 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
672 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
674 /* check a bogus privilege name */
675 ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
676 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
677 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
679 /* check case insensitive */
680 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
682 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
684 for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
686 /* Not all privileges are implemented on all Windows versions, so
687 * don't worry if the call fails
689 if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
691 ok(luid.LowPart == privs[i].lowPart,
692 "LookupPrivilegeValueA returned an invalid LUID for %s\n",
698 static void test_luid(void)
701 test_lookupPrivilegeName();
702 test_lookupPrivilegeValue();
705 static void test_FileSecurity(void)
707 char wintmpdir [MAX_PATH];
708 char path [MAX_PATH];
709 char file [MAX_PATH];
711 DWORD sdSize, retSize, rc, granted, priv_set_len;
712 PRIVILEGE_SET priv_set;
715 GENERIC_MAPPING mapping = { FILE_READ_DATA, FILE_WRITE_DATA, FILE_EXECUTE, FILE_ALL_ACCESS };
716 const SECURITY_INFORMATION request = OWNER_SECURITY_INFORMATION
717 | GROUP_SECURITY_INFORMATION
718 | DACL_SECURITY_INFORMATION;
720 if (!pGetFileSecurityA) {
721 win_skip ("GetFileSecurity is not available\n");
725 if (!pSetFileSecurityA) {
726 win_skip ("SetFileSecurity is not available\n");
730 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
731 win_skip ("GetTempPathA failed\n");
735 /* Create a temporary directory and in it a temporary file */
736 strcat (strcpy (path, wintmpdir), "rary");
737 SetLastError(0xdeadbeef);
738 rc = CreateDirectoryA (path, NULL);
739 ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
740 "failed for '%s' with %d\n", path, GetLastError());
742 strcat (strcpy (file, path), "\\ess");
743 SetLastError(0xdeadbeef);
744 fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
745 ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
746 "failed for '%s' with %d\n", file, GetLastError());
749 /* For the temporary file ... */
751 /* Get size needed */
753 SetLastError(0xdeadbeef);
754 rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
755 if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
756 win_skip("GetFileSecurityA is not implemented\n");
759 ok (!rc, "GetFileSecurityA "
760 "was expected to fail for '%s'\n", file);
761 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
762 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
763 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
766 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
768 /* Get security descriptor for real */
770 SetLastError(0xdeadbeef);
771 rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
772 ok (rc, "GetFileSecurityA "
773 "was not expected to fail '%s': %d\n", file, GetLastError());
774 ok (retSize == sdSize ||
775 broken(retSize == 0), /* NT4 */
776 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
778 /* Use it to set security descriptor */
779 SetLastError(0xdeadbeef);
780 rc = pSetFileSecurityA (file, request, sd);
781 ok (rc, "SetFileSecurityA "
782 "was not expected to fail '%s': %d\n", file, GetLastError());
784 HeapFree (GetProcessHeap (), 0, sd);
786 /* Repeat for the temporary directory ... */
788 /* Get size needed */
790 SetLastError(0xdeadbeef);
791 rc = pGetFileSecurityA (path, request, NULL, 0, &retSize);
792 ok (!rc, "GetFileSecurityA "
793 "was expected to fail for '%s'\n", path);
794 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
795 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
796 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
799 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
801 /* Get security descriptor for real */
803 SetLastError(0xdeadbeef);
804 rc = pGetFileSecurityA (path, request, sd, sdSize, &retSize);
805 ok (rc, "GetFileSecurityA "
806 "was not expected to fail '%s': %d\n", path, GetLastError());
807 ok (retSize == sdSize ||
808 broken(retSize == 0), /* NT4 */
809 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
811 /* Use it to set security descriptor */
812 SetLastError(0xdeadbeef);
813 rc = pSetFileSecurityA (path, request, sd);
814 ok (rc, "SetFileSecurityA "
815 "was not expected to fail '%s': %d\n", path, GetLastError());
816 HeapFree (GetProcessHeap (), 0, sd);
819 strcpy (wintmpdir, "\\Should not exist");
820 SetLastError(0xdeadbeef);
821 rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
822 ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
823 ok (GetLastError() == ERROR_FILE_NOT_FOUND,
824 "last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());
827 /* Remove temporary file and directory */
829 RemoveDirectoryA(path);
831 /* Test file access permissions for a file with FILE_ATTRIBUTE_ARCHIVE */
832 SetLastError(0xdeadbeef);
833 rc = GetTempPath(sizeof(wintmpdir), wintmpdir);
834 ok(rc, "GetTempPath error %d\n", GetLastError());
836 SetLastError(0xdeadbeef);
837 rc = GetTempFileName(wintmpdir, "tmp", 0, file);
838 ok(rc, "GetTempFileName error %d\n", GetLastError());
840 rc = GetFileAttributes(file);
841 rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
842 ok(rc == FILE_ATTRIBUTE_ARCHIVE, "expected FILE_ATTRIBUTE_ARCHIVE got %#x\n", rc);
844 retSize = 0xdeadbeef;
845 rc = GetFileSecurity(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
847 ok(!rc, "GetFileSecurity should fail\n");
848 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
849 "expected ERROR_INSUFFICIENT_BUFFER got %d\n", GetLastError());
850 ok(sdSize > sizeof(SECURITY_DESCRIPTOR), "got sd size %d\n", sdSize);
852 sd = HeapAlloc(GetProcessHeap (), 0, sdSize);
853 retSize = 0xdeadbeef;
854 SetLastError(0xdeadbeef);
855 rc = GetFileSecurity(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
856 sd, sdSize, &retSize);
857 ok(rc, "GetFileSecurity error %d\n", GetLastError());
858 ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
860 SetLastError(0xdeadbeef);
861 rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
862 ok(!rc, "OpenThreadToken should fail\n");
863 ok(GetLastError() == ERROR_NO_TOKEN, "expected ERROR_NO_TOKEN, got %d\n", GetLastError());
865 SetLastError(0xdeadbeef);
866 rc = ImpersonateSelf(SecurityIdentification);
867 ok(rc, "ImpersonateSelf error %d\n", GetLastError());
869 SetLastError(0xdeadbeef);
870 rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
871 ok(rc, "OpenThreadToken error %d\n", GetLastError());
873 SetLastError(0xdeadbeef);
875 ok(rc, "RevertToSelf error %d\n", GetLastError());
877 priv_set_len = sizeof(priv_set);
878 granted = 0xdeadbeef;
880 SetLastError(0xdeadbeef);
881 rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
882 ok(rc, "AccessCheck error %d\n", GetLastError());
883 ok(status == 1, "expected 1, got %d\n", status);
884 ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
886 granted = 0xdeadbeef;
888 SetLastError(0xdeadbeef);
889 rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
890 ok(rc, "AccessCheck error %d\n", GetLastError());
891 ok(status == 1, "expected 1, got %d\n", status);
892 ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
894 granted = 0xdeadbeef;
896 SetLastError(0xdeadbeef);
897 rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
898 ok(rc, "AccessCheck error %d\n", GetLastError());
899 ok(status == 1, "expected 1, got %d\n", status);
900 ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
902 granted = 0xdeadbeef;
904 SetLastError(0xdeadbeef);
905 rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
906 ok(rc, "AccessCheck error %d\n", GetLastError());
907 ok(status == 1, "expected 1, got %d\n", status);
908 ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
910 granted = 0xdeadbeef;
912 SetLastError(0xdeadbeef);
913 rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
914 ok(rc, "AccessCheck error %d\n", GetLastError());
915 ok(status == 1, "expected 1, got %d\n", status);
916 ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
918 granted = 0xdeadbeef;
920 SetLastError(0xdeadbeef);
921 rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
922 ok(rc, "AccessCheck error %d\n", GetLastError());
923 ok(status == 1, "expected 1, got %d\n", status);
924 ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
926 granted = 0xdeadbeef;
928 SetLastError(0xdeadbeef);
929 rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
930 ok(rc, "AccessCheck error %d\n", GetLastError());
931 ok(status == 1, "expected 1, got %d\n", status);
932 ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
934 SetLastError(0xdeadbeef);
935 rc = AccessCheck(sd, token, 0xffffffff, &mapping, &priv_set, &priv_set_len, &granted, &status);
936 ok(!rc, "AccessCheck should fail\n");
937 ok(GetLastError() == ERROR_GENERIC_NOT_MAPPED, "expected ERROR_GENERIC_NOT_MAPPED, got %d\n", GetLastError());
939 /* Test file access permissions for a file with FILE_ATTRIBUTE_READONLY */
940 SetLastError(0xdeadbeef);
941 fh = CreateFile(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
942 ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
943 retSize = 0xdeadbeef;
944 SetLastError(0xdeadbeef);
945 rc = WriteFile(fh, "1", 1, &retSize, NULL);
946 ok(!rc, "WriteFile should fail\n");
947 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
948 ok(retSize == 0, "expected 0, got %d\n", retSize);
951 rc = GetFileAttributes(file);
952 rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
954 ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
955 "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
957 SetLastError(0xdeadbeef);
958 rc = SetFileAttributes(file, FILE_ATTRIBUTE_ARCHIVE);
959 ok(rc, "SetFileAttributes error %d\n", GetLastError());
960 SetLastError(0xdeadbeef);
961 rc = DeleteFile(file);
962 ok(rc, "DeleteFile error %d\n", GetLastError());
964 SetLastError(0xdeadbeef);
965 fh = CreateFile(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
966 ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
967 retSize = 0xdeadbeef;
968 SetLastError(0xdeadbeef);
969 rc = WriteFile(fh, "1", 1, &retSize, NULL);
970 ok(!rc, "WriteFile should fail\n");
971 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
972 ok(retSize == 0, "expected 0, got %d\n", retSize);
975 rc = GetFileAttributes(file);
976 rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
977 ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
978 "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
980 retSize = 0xdeadbeef;
981 SetLastError(0xdeadbeef);
982 rc = GetFileSecurity(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
983 sd, sdSize, &retSize);
984 ok(rc, "GetFileSecurity error %d\n", GetLastError());
985 ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
987 priv_set_len = sizeof(priv_set);
988 granted = 0xdeadbeef;
990 SetLastError(0xdeadbeef);
991 rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
992 ok(rc, "AccessCheck error %d\n", GetLastError());
993 ok(status == 1, "expected 1, got %d\n", status);
994 ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
996 granted = 0xdeadbeef;
998 SetLastError(0xdeadbeef);
999 rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1000 ok(rc, "AccessCheck error %d\n", GetLastError());
1002 ok(status == 1, "expected 1, got %d\n", status);
1003 ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
1005 granted = 0xdeadbeef;
1006 status = 0xdeadbeef;
1007 SetLastError(0xdeadbeef);
1008 rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1009 ok(rc, "AccessCheck error %d\n", GetLastError());
1010 ok(status == 1, "expected 1, got %d\n", status);
1011 ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
1013 granted = 0xdeadbeef;
1014 status = 0xdeadbeef;
1015 SetLastError(0xdeadbeef);
1016 rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1017 ok(rc, "AccessCheck error %d\n", GetLastError());
1019 ok(status == 1, "expected 1, got %d\n", status);
1020 ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
1022 granted = 0xdeadbeef;
1023 status = 0xdeadbeef;
1024 SetLastError(0xdeadbeef);
1025 rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
1026 ok(rc, "AccessCheck error %d\n", GetLastError());
1028 ok(status == 1, "expected 1, got %d\n", status);
1029 ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
1031 granted = 0xdeadbeef;
1032 status = 0xdeadbeef;
1033 SetLastError(0xdeadbeef);
1034 rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
1035 ok(rc, "AccessCheck error %d\n", GetLastError());
1037 ok(status == 1, "expected 1, got %d\n", status);
1038 ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
1040 granted = 0xdeadbeef;
1041 status = 0xdeadbeef;
1042 SetLastError(0xdeadbeef);
1043 rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
1044 ok(rc, "AccessCheck error %d\n", GetLastError());
1046 ok(status == 1, "expected 1, got %d\n", status);
1047 ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
1049 SetLastError(0xdeadbeef);
1050 rc = DeleteFile(file);
1051 ok(!rc, "DeleteFile should fail\n");
1052 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1053 SetLastError(0xdeadbeef);
1054 rc = SetFileAttributes(file, FILE_ATTRIBUTE_ARCHIVE);
1055 ok(rc, "SetFileAttributes error %d\n", GetLastError());
1056 SetLastError(0xdeadbeef);
1057 rc = DeleteFile(file);
1058 ok(rc, "DeleteFile error %d\n", GetLastError());
1061 HeapFree(GetProcessHeap(), 0, sd);
1064 static void test_AccessCheck(void)
1066 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
1068 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
1069 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
1070 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1071 GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
1075 HANDLE ProcessToken;
1078 PRIVILEGE_SET *PrivSet;
1080 HMODULE NtDllModule;
1083 NTSTATUS ntret, ntAccessStatus;
1085 NtDllModule = GetModuleHandle("ntdll.dll");
1088 skip("not running on NT, skipping test\n");
1091 pRtlAdjustPrivilege = (void *)GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
1092 if (!pRtlAdjustPrivilege)
1094 win_skip("missing RtlAdjustPrivilege, skipping test\n");
1098 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
1099 res = InitializeAcl(Acl, 256, ACL_REVISION);
1100 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1102 skip("ACLs not implemented - skipping tests\n");
1103 HeapFree(GetProcessHeap(), 0, Acl);
1106 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
1108 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
1109 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1111 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1112 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
1113 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1115 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1116 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
1117 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1119 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
1121 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1122 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
1124 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1125 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1127 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1128 PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
1129 PrivSet->PrivilegeCount = 16;
1131 res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
1132 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
1134 pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
1136 res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
1137 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1139 /* SD without owner/group */
1140 SetLastError(0xdeadbeef);
1141 Access = AccessStatus = 0x1abe11ed;
1142 ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
1143 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1144 err = GetLastError();
1145 ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
1146 "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
1147 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1148 "Access and/or AccessStatus were changed!\n");
1150 /* Set owner and group */
1151 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
1152 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
1153 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
1154 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
1156 /* Generic access mask */
1157 SetLastError(0xdeadbeef);
1158 Access = AccessStatus = 0x1abe11ed;
1159 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1160 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1161 err = GetLastError();
1162 ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
1163 "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
1164 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1165 "Access and/or AccessStatus were changed!\n");
1167 /* Generic access mask - no privilegeset buffer */
1168 SetLastError(0xdeadbeef);
1169 Access = AccessStatus = 0x1abe11ed;
1170 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1171 NULL, &PrivSetLen, &Access, &AccessStatus);
1172 err = GetLastError();
1173 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1174 "with ERROR_NOACCESS, instead of %d\n", err);
1175 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1176 "Access and/or AccessStatus were changed!\n");
1178 /* Generic access mask - no returnlength */
1179 SetLastError(0xdeadbeef);
1180 Access = AccessStatus = 0x1abe11ed;
1181 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1182 PrivSet, NULL, &Access, &AccessStatus);
1183 err = GetLastError();
1184 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1185 "with ERROR_NOACCESS, instead of %d\n", err);
1186 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1187 "Access and/or AccessStatus were changed!\n");
1189 /* Generic access mask - no privilegeset buffer, no returnlength */
1190 SetLastError(0xdeadbeef);
1191 Access = AccessStatus = 0x1abe11ed;
1192 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1193 NULL, NULL, &Access, &AccessStatus);
1194 err = GetLastError();
1195 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1196 "with ERROR_NOACCESS, instead of %d\n", err);
1197 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1198 "Access and/or AccessStatus were changed!\n");
1200 /* sd with no dacl present */
1201 Access = AccessStatus = 0x1abe11ed;
1202 ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
1203 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1204 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1205 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1206 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1207 ok(AccessStatus && (Access == KEY_READ),
1208 "AccessCheck failed to grant access with error %d\n",
1211 /* sd with no dacl present - no privilegeset buffer */
1212 SetLastError(0xdeadbeef);
1213 Access = AccessStatus = 0x1abe11ed;
1214 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1215 NULL, &PrivSetLen, &Access, &AccessStatus);
1216 err = GetLastError();
1217 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1218 "with ERROR_NOACCESS, instead of %d\n", err);
1219 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1220 "Access and/or AccessStatus were changed!\n");
1224 /* Generic access mask - no privilegeset buffer */
1225 SetLastError(0xdeadbeef);
1226 Access = ntAccessStatus = 0x1abe11ed;
1227 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1228 NULL, &PrivSetLen, &Access, &ntAccessStatus);
1229 err = GetLastError();
1230 ok(ntret == STATUS_ACCESS_VIOLATION,
1231 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1232 ok(err == 0xdeadbeef,
1233 "NtAccessCheck shouldn't set last error, got %d\n", err);
1234 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1235 "Access and/or AccessStatus were changed!\n");
1237 /* Generic access mask - no returnlength */
1238 SetLastError(0xdeadbeef);
1239 Access = ntAccessStatus = 0x1abe11ed;
1240 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1241 PrivSet, NULL, &Access, &ntAccessStatus);
1242 err = GetLastError();
1243 ok(ntret == STATUS_ACCESS_VIOLATION,
1244 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1245 ok(err == 0xdeadbeef,
1246 "NtAccessCheck shouldn't set last error, got %d\n", err);
1247 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1248 "Access and/or AccessStatus were changed!\n");
1250 /* Generic access mask - no privilegeset buffer, no returnlength */
1251 SetLastError(0xdeadbeef);
1252 Access = ntAccessStatus = 0x1abe11ed;
1253 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1254 NULL, NULL, &Access, &ntAccessStatus);
1255 err = GetLastError();
1256 ok(ntret == STATUS_ACCESS_VIOLATION,
1257 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1258 ok(err == 0xdeadbeef,
1259 "NtAccessCheck shouldn't set last error, got %d\n", err);
1260 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1261 "Access and/or AccessStatus were changed!\n");
1264 win_skip("NtAccessCheck unavailable. Skipping.\n");
1266 /* sd with NULL dacl */
1267 Access = AccessStatus = 0x1abe11ed;
1268 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
1269 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1270 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1271 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1272 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1273 ok(AccessStatus && (Access == KEY_READ),
1274 "AccessCheck failed to grant access with error %d\n",
1277 /* sd with blank dacl */
1278 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1279 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1280 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1281 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1282 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1283 err = GetLastError();
1284 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1285 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1286 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1288 res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
1289 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1291 res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
1292 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1295 Access = AccessStatus = 0x1abe11ed;
1296 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1297 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1298 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1299 ok(AccessStatus && (Access == KEY_READ),
1300 "AccessCheck failed to grant access with error %d\n",
1303 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1304 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1305 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1307 "AccessCheck failed to grant any access with error %d\n",
1309 trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
1311 /* Access denied by SD */
1312 SetLastError(0xdeadbeef);
1313 Access = AccessStatus = 0x1abe11ed;
1314 ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
1315 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1316 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1317 err = GetLastError();
1318 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1319 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1320 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1323 PrivSet->PrivilegeCount = 16;
1324 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1325 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1326 ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
1327 "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
1330 ret = ImpersonateLoggedOnUser(Token);
1331 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1332 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
1336 PrivSet->PrivilegeCount = 16;
1337 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1338 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1339 ok(ret && AccessStatus && GetLastError() == 0,
1340 "AccessCheck should have succeeded, error %d\n",
1342 ok(Access == ACCESS_SYSTEM_SECURITY,
1343 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1347 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1349 ret = RevertToSelf();
1350 ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1352 /* test INHERIT_ONLY_ACE */
1353 ret = InitializeAcl(Acl, 256, ACL_REVISION);
1354 ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
1356 /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
1359 if (pAddAccessAllowedAceEx)
1361 ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
1362 ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1365 win_skip("AddAccessAllowedAceEx is not available\n");
1367 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1368 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1369 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1370 err = GetLastError();
1371 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1372 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1373 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1377 res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
1378 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1380 SetLastError(0xdeadbeef);
1381 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1382 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1383 err = GetLastError();
1384 ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
1385 "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
1389 SetLastError(0xdeadbeef);
1390 ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
1391 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1392 err = GetLastError();
1393 ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
1394 "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
1396 CloseHandle(ProcessToken);
1399 FreeSid(EveryoneSid);
1404 HeapFree(GetProcessHeap(), 0, Acl);
1405 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1406 HeapFree(GetProcessHeap(), 0, PrivSet);
1409 /* test GetTokenInformation for the various attributes */
1410 static void test_token_attr(void)
1412 HANDLE Token, ImpersonationToken;
1414 TOKEN_PRIVILEGES *Privileges;
1415 TOKEN_GROUPS *Groups;
1417 TOKEN_DEFAULT_DACL *Dacl;
1421 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1424 /* cygwin-like use case */
1425 SetLastError(0xdeadbeef);
1426 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1427 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1429 win_skip("OpenProcessToken is not implemented\n");
1432 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1435 DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1437 ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1438 ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1439 Size = sizeof(ImpersonationLevel);
1440 ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1441 GLE = GetLastError();
1442 ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1446 if(!pConvertSidToStringSidA)
1448 win_skip("ConvertSidToStringSidA is not available\n");
1452 SetLastError(0xdeadbeef);
1453 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1454 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1457 /* insufficient buffer length */
1458 SetLastError(0xdeadbeef);
1460 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size2);
1461 ok(Size2 > 1, "got %d\n", Size2);
1462 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1463 "%d with error %d\n", ret, GetLastError());
1465 Groups = HeapAlloc(GetProcessHeap(), 0, Size2);
1466 memset(Groups, 0xcc, Size2);
1468 ret = GetTokenInformation(Token, TokenGroups, Groups, Size2, &Size);
1469 ok(Size > 1, "got %d\n", Size);
1470 ok((!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER) || broken(ret) /* wow64 */,
1471 "%d with error %d\n", ret, GetLastError());
1473 ok(*((BYTE*)Groups) == 0xcc, "buffer altered\n");
1475 HeapFree(GetProcessHeap(), 0, Groups);
1477 SetLastError(0xdeadbeef);
1478 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1479 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1480 "GetTokenInformation(TokenGroups) %s with error %d\n",
1481 ret ? "succeeded" : "failed", GetLastError());
1482 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1483 SetLastError(0xdeadbeef);
1484 ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1485 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1486 ok(GetLastError() == 0xdeadbeef,
1487 "GetTokenInformation shouldn't have set last error to %d\n",
1489 trace("TokenGroups:\n");
1490 for (i = 0; i < Groups->GroupCount; i++)
1492 DWORD NameLength = 255;
1494 DWORD DomainLength = 255;
1496 SID_NAME_USE SidNameUse;
1499 ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1502 pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1503 trace("%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
1504 LocalFree(SidString);
1506 else trace("attr: 0x%08x LookupAccountSid failed with error %d\n", Groups->Groups[i].Attributes, GetLastError());
1508 HeapFree(GetProcessHeap(), 0, Groups);
1511 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1512 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1513 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1514 User = HeapAlloc(GetProcessHeap(), 0, Size);
1515 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1517 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1519 pConvertSidToStringSidA(User->User.Sid, &SidString);
1520 trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1521 LocalFree(SidString);
1522 HeapFree(GetProcessHeap(), 0, User);
1525 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1526 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1527 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1528 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1529 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1531 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1532 trace("TokenPrivileges:\n");
1533 for (i = 0; i < Privileges->PrivilegeCount; i++)
1536 DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
1537 LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1538 trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1540 HeapFree(GetProcessHeap(), 0, Privileges);
1542 ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
1543 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1545 Size = sizeof(ImpersonationLevel);
1546 ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1547 ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1548 ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
1550 CloseHandle(ImpersonationToken);
1553 ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
1554 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1555 "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1557 Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
1558 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
1559 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1561 SetLastError(0xdeadbeef);
1562 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
1563 GLE = GetLastError();
1564 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1565 ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);
1567 SetLastError(0xdeadbeef);
1568 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
1569 GLE = GetLastError();
1570 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1571 ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);
1573 acl = Dacl->DefaultDacl;
1574 Dacl->DefaultDacl = NULL;
1576 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1577 ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1580 Dacl->DefaultDacl = (ACL *)0xdeadbeef;
1581 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1582 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1583 ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
1584 ok(Size2 == sizeof(TOKEN_DEFAULT_DACL) || broken(Size2 == 2*sizeof(TOKEN_DEFAULT_DACL)), /* WoW64 */
1585 "got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
1587 Dacl->DefaultDacl = acl;
1588 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1589 ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1591 if (Size2 == sizeof(TOKEN_DEFAULT_DACL)) {
1592 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1593 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1595 win_skip("TOKEN_DEFAULT_DACL size too small on WoW64\n");
1597 HeapFree(GetProcessHeap(), 0, Dacl);
1601 typedef union _MAX_SID
1604 char max[SECURITY_MAX_SID_SIZE];
1607 static void test_sid_str(PSID * sid)
1610 BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
1611 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
1614 char account[MAX_PATH], domain[MAX_PATH];
1616 DWORD acc_size = MAX_PATH;
1617 DWORD dom_size = MAX_PATH;
1618 ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
1619 ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
1620 "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
1622 trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
1623 else if (GetLastError() == ERROR_NONE_MAPPED)
1624 trace(" %s couldn't be mapped\n", str_sid);
1629 static const struct well_known_sid_value
1631 BOOL without_domain;
1632 const char *sid_string;
1633 } well_known_sid_values[] = {
1634 /* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
1635 /* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
1636 /* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
1637 /* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
1638 /* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
1639 /* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
1640 /* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
1641 /* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
1642 /* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
1643 /* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
1644 /* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
1645 /* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
1646 /* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
1647 /* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
1648 /* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
1649 /* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
1650 /* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
1651 /* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
1652 /* Added in Windows Server 2003 */
1653 /* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
1654 /* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
1655 /* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
1656 /* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
1657 /* Added in Windows Vista: */
1658 /* 62 */ {TRUE, "S-1-5-32-568"},
1659 /* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
1660 /* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
1661 /* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
1662 /* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
1663 /* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"},
1664 /* 77 */ {FALSE, "S-1-5-21-12-23-34-45-56-498"}, {TRUE, "S-1-5-32-574"}, {TRUE, "S-1-16-8448"}
1667 static void test_CreateWellKnownSid(void)
1669 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1670 PSID domainsid, sid;
1675 if (!pCreateWellKnownSid)
1677 win_skip("CreateWellKnownSid not available\n");
1682 SetLastError(0xdeadbeef);
1683 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
1684 error = GetLastError();
1685 ok(!ret, "CreateWellKnownSid succeeded\n");
1686 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
1687 ok(size, "expected size > 0\n");
1689 SetLastError(0xdeadbeef);
1690 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
1691 error = GetLastError();
1692 ok(!ret, "CreateWellKnownSid succeeded\n");
1693 ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);
1695 sid = HeapAlloc(GetProcessHeap(), 0, size);
1696 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
1697 ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
1698 HeapFree(GetProcessHeap(), 0, sid);
1700 /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
1701 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
1703 for (i = 0; i < sizeof(well_known_sid_values)/sizeof(well_known_sid_values[0]); i++)
1705 const struct well_known_sid_value *value = &well_known_sid_values[i];
1706 char sid_buffer[SECURITY_MAX_SID_SIZE];
1710 if (value->sid_string == NULL)
1713 if (i > WinAccountRasAndIasServersSid)
1715 /* These SIDs aren't implemented by all Windows versions - detect it and break the loop */
1716 cb = sizeof(sid_buffer);
1717 if (!pCreateWellKnownSid(i, domainsid, sid_buffer, &cb))
1719 skip("Well known SIDs starting from %u are not implemented\n", i);
1724 cb = sizeof(sid_buffer);
1725 ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %u\n", i);
1726 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1727 ok(IsValidSid(sid_buffer), "The sid is not valid\n");
1728 ok(pConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
1729 ok(strcmp(str, value->sid_string) == 0, "%d: SID mismatch - expected %s, got %s\n", i,
1730 value->sid_string, str);
1733 if (value->without_domain)
1735 char buf2[SECURITY_MAX_SID_SIZE];
1737 ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %u with optional domain\n", i);
1738 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1739 ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%u)\n", i);
1746 static void test_LookupAccountSid(void)
1748 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1749 CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
1750 DWORD acc_sizeA, dom_sizeA, user_sizeA;
1751 DWORD real_acc_sizeA, real_dom_sizeA;
1752 WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
1753 DWORD acc_sizeW, dom_sizeW;
1754 DWORD real_acc_sizeW, real_dom_sizeW;
1755 PSID pUsersSid = NULL;
1758 DWORD error, size, cbti = 0;
1763 PTOKEN_USER ptiUser = NULL;
1765 /* native windows crashes if account size, domain size, or name use is NULL */
1767 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1768 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
1769 ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
1770 "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1772 /* not running on NT so give up */
1773 if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1776 real_acc_sizeA = MAX_PATH;
1777 real_dom_sizeA = MAX_PATH;
1778 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1779 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1781 /* try NULL account */
1782 acc_sizeA = MAX_PATH;
1783 dom_sizeA = MAX_PATH;
1784 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1785 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1787 /* try NULL domain */
1788 acc_sizeA = MAX_PATH;
1789 dom_sizeA = MAX_PATH;
1790 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1791 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1793 /* try a small account buffer */
1795 dom_sizeA = MAX_PATH;
1797 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1798 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1799 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1800 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1802 /* try a 0 sized account buffer */
1804 dom_sizeA = MAX_PATH;
1806 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1807 /* this can fail or succeed depending on OS version but the size will always be returned */
1808 ok(acc_sizeA == real_acc_sizeA + 1,
1809 "LookupAccountSidA() Expected acc_size = %u, got %u\n",
1810 real_acc_sizeA + 1, acc_sizeA);
1812 /* try a 0 sized account buffer */
1814 dom_sizeA = MAX_PATH;
1815 LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1816 /* this can fail or succeed depending on OS version but the size will always be returned */
1817 ok(acc_sizeA == real_acc_sizeA + 1,
1818 "LookupAccountSid() Expected acc_size = %u, got %u\n",
1819 real_acc_sizeA + 1, acc_sizeA);
1821 /* try a small domain buffer */
1823 acc_sizeA = MAX_PATH;
1825 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1826 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1827 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1828 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1830 /* try a 0 sized domain buffer */
1832 acc_sizeA = MAX_PATH;
1834 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1835 /* this can fail or succeed depending on OS version but the size will always be returned */
1836 ok(dom_sizeA == real_dom_sizeA + 1,
1837 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1838 real_dom_sizeA + 1, dom_sizeA);
1840 /* try a 0 sized domain buffer */
1842 acc_sizeA = MAX_PATH;
1843 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1844 /* this can fail or succeed depending on OS version but the size will always be returned */
1845 ok(dom_sizeA == real_dom_sizeA + 1,
1846 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1847 real_dom_sizeA + 1, dom_sizeA);
1849 real_acc_sizeW = MAX_PATH;
1850 real_dom_sizeW = MAX_PATH;
1851 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
1852 ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
1854 /* try an invalid system name */
1855 real_acc_sizeA = MAX_PATH;
1856 real_dom_sizeA = MAX_PATH;
1857 ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1858 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1859 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
1860 "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
1862 /* native windows crashes if domainW or accountW is NULL */
1864 /* try a small account buffer */
1866 dom_sizeW = MAX_PATH;
1868 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1869 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1870 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1871 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1873 /* try a 0 sized account buffer */
1875 dom_sizeW = MAX_PATH;
1877 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1878 /* this can fail or succeed depending on OS version but the size will always be returned */
1879 ok(acc_sizeW == real_acc_sizeW + 1,
1880 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1881 real_acc_sizeW + 1, acc_sizeW);
1883 /* try a 0 sized account buffer */
1885 dom_sizeW = MAX_PATH;
1886 LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1887 /* this can fail or succeed depending on OS version but the size will always be returned */
1888 ok(acc_sizeW == real_acc_sizeW + 1,
1889 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1890 real_acc_sizeW + 1, acc_sizeW);
1892 /* try a small domain buffer */
1894 acc_sizeW = MAX_PATH;
1896 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1897 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1898 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1899 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1901 /* try a 0 sized domain buffer */
1903 acc_sizeW = MAX_PATH;
1905 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1906 /* this can fail or succeed depending on OS version but the size will always be returned */
1907 ok(dom_sizeW == real_dom_sizeW + 1,
1908 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1909 real_dom_sizeW + 1, dom_sizeW);
1911 /* try a 0 sized domain buffer */
1913 acc_sizeW = MAX_PATH;
1914 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1915 /* this can fail or succeed depending on OS version but the size will always be returned */
1916 ok(dom_sizeW == real_dom_sizeW + 1,
1917 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1918 real_dom_sizeW + 1, dom_sizeW);
1920 acc_sizeW = dom_sizeW = use = 0;
1921 SetLastError(0xdeadbeef);
1922 ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, NULL, &dom_sizeW, &use);
1923 error = GetLastError();
1924 ok(!ret, "LookupAccountSidW failed %u\n", GetLastError());
1925 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
1926 ok(acc_sizeW, "expected non-zero account size\n");
1927 ok(dom_sizeW, "expected non-zero domain size\n");
1928 ok(!use, "expected zero use %u\n", use);
1932 /* Test LookupAccountSid with Sid retrieved from token information.
1933 This assumes this process is running under the account of the current user.*/
1934 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
1935 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1936 ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
1937 ok(!ret, "GetTokenInformation failed with error %d\n", GetLastError());
1938 ptiUser = HeapAlloc(GetProcessHeap(), 0, cbti);
1939 if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
1941 acc_sizeA = dom_sizeA = MAX_PATH;
1942 ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1943 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1944 user_sizeA = MAX_PATH;
1945 ret = GetUserNameA(usernameA , &user_sizeA);
1946 ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
1947 ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
1949 HeapFree(GetProcessHeap(), 0, ptiUser);
1951 if (pCreateWellKnownSid && pConvertSidToStringSidA)
1953 trace("Well Known SIDs:\n");
1954 for (i = 0; i <= 60; i++)
1956 size = SECURITY_MAX_SID_SIZE;
1957 if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
1959 if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1961 acc_sizeA = MAX_PATH;
1962 dom_sizeA = MAX_PATH;
1963 if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
1964 trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
1965 LocalFree(str_sidA);
1970 if (GetLastError() != ERROR_INVALID_PARAMETER)
1971 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1973 trace(" %d: not supported\n", i);
1977 pLsaQueryInformationPolicy = (void *)GetProcAddress( hmod, "LsaQueryInformationPolicy");
1978 pLsaOpenPolicy = (void *)GetProcAddress( hmod, "LsaOpenPolicy");
1979 pLsaFreeMemory = (void *)GetProcAddress( hmod, "LsaFreeMemory");
1980 pLsaClose = (void *)GetProcAddress( hmod, "LsaClose");
1982 if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
1986 LSA_OBJECT_ATTRIBUTES object_attributes;
1988 ZeroMemory(&object_attributes, sizeof(object_attributes));
1989 object_attributes.Length = sizeof(object_attributes);
1991 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1992 ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1993 "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1995 /* try a more restricted access mask if necessary */
1996 if (status == STATUS_ACCESS_DENIED) {
1997 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
1998 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1999 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
2002 if (status == STATUS_SUCCESS)
2004 PPOLICY_ACCOUNT_DOMAIN_INFO info;
2005 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
2006 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
2007 if (status == STATUS_SUCCESS)
2009 ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
2010 if (info->DomainSid)
2012 int count = *GetSidSubAuthorityCount(info->DomainSid);
2013 CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
2014 test_sid_str((PSID)&max_sid.sid);
2015 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
2016 max_sid.sid.SubAuthorityCount = count + 1;
2017 test_sid_str((PSID)&max_sid.sid);
2018 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
2019 test_sid_str((PSID)&max_sid.sid);
2020 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
2021 test_sid_str((PSID)&max_sid.sid);
2022 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
2023 test_sid_str((PSID)&max_sid.sid);
2024 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
2025 test_sid_str((PSID)&max_sid.sid);
2026 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
2027 test_sid_str((PSID)&max_sid.sid);
2028 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
2029 test_sid_str((PSID)&max_sid.sid);
2030 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
2031 test_sid_str((PSID)&max_sid.sid);
2032 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
2033 test_sid_str((PSID)&max_sid.sid);
2034 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
2035 test_sid_str((PSID)&max_sid.sid);
2036 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
2037 test_sid_str((PSID)&max_sid.sid);
2038 max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
2039 test_sid_str((PSID)&max_sid.sid);
2040 max_sid.sid.SubAuthority[count] = 1000; /* first user account */
2041 test_sid_str((PSID)&max_sid.sid);
2044 pLsaFreeMemory((LPVOID)info);
2047 status = pLsaClose(handle);
2048 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
2054 static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
2056 static CHAR account[UNLEN + 1];
2057 static CHAR domain[UNLEN + 1];
2058 DWORD size, dom_size;
2064 size = dom_size = UNLEN + 1;
2067 SetLastError(0xdeadbeef);
2068 return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
2071 static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
2073 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
2074 PSID domainsid = NULL;
2075 char wk_sid[SECURITY_MAX_SID_SIZE];
2078 DWORD sid_size, domain_size;
2079 SID_NAME_USE sid_use;
2080 LPSTR domain, account, sid_domain, wk_domain, wk_account;
2086 ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2087 ok(!ret, " %s Should have failed to lookup account name\n", name);
2088 psid = HeapAlloc(GetProcessHeap(),0,sid_size);
2089 domain = HeapAlloc(GetProcessHeap(),0,domain_size);
2090 ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);
2094 ok(!ret, " %s Should have failed to lookup account name\n",name);
2098 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
2099 cb = sizeof(wk_sid);
2100 if (!pCreateWellKnownSid(result, domainsid, wk_sid, &cb))
2102 win_skip("SID %i is not available on the system\n",result);
2106 ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
2107 if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
2109 win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
2113 get_sid_info(psid, &account, &sid_domain);
2115 ok(ret, "Failed to lookup account name %s\n",name);
2116 ok(sid_size != 0, "sid_size was zero\n");
2118 ok(EqualSid(psid,wk_sid),"(%s) Sids fail to match well known sid!\n",name);
2120 ok(!lstrcmp(account, wk_account), "Expected %s , got %s\n", account, wk_account);
2121 ok(!lstrcmp(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
2122 ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
2126 HeapFree(GetProcessHeap(),0,psid);
2127 HeapFree(GetProcessHeap(),0,domain);
2130 static void test_LookupAccountName(void)
2132 DWORD sid_size, domain_size, user_size;
2133 DWORD sid_save, domain_save;
2134 CHAR user_name[UNLEN + 1];
2135 CHAR computer_name[UNLEN + 1];
2136 SID_NAME_USE sid_use;
2137 LPSTR domain, account, sid_dom;
2141 /* native crashes if (assuming all other parameters correct):
2143 * - Sid is NULL and cbSid is > 0
2144 * - cbSid or cchReferencedDomainName are NULL
2145 * - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
2148 user_size = UNLEN + 1;
2149 SetLastError(0xdeadbeef);
2150 ret = GetUserNameA(user_name, &user_size);
2151 ok(ret, "Failed to get user name : %d\n", GetLastError());
2156 sid_use = 0xcafebabe;
2157 SetLastError(0xdeadbeef);
2158 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2159 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2161 win_skip("LookupAccountNameA is not implemented\n");
2164 ok(!ret, "Expected 0, got %d\n", ret);
2165 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2166 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2167 ok(sid_size != 0, "Expected non-zero sid size\n");
2168 ok(domain_size != 0, "Expected non-zero domain size\n");
2169 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2171 sid_save = sid_size;
2172 domain_save = domain_size;
2174 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2175 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2177 /* try valid account name */
2178 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
2179 get_sid_info(psid, &account, &sid_dom);
2180 ok(ret, "Failed to lookup account name\n");
2181 ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
2182 ok(!lstrcmp(account, user_name), "Expected %s, got %s\n", user_name, account);
2183 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2184 ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
2185 ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
2186 ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
2187 domain_size = domain_save;
2188 sid_size = sid_save;
2190 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2192 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2196 ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
2197 get_sid_info(psid, &account, &sid_dom);
2198 ok(ret, "Failed to lookup account name\n");
2199 ok(sid_size != 0, "sid_size was zero\n");
2200 ok(!lstrcmp(account, "Everyone"), "Expected Everyone, got %s\n", account);
2201 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2202 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2203 ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
2204 ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
2205 domain_size = domain_save;
2208 /* NULL Sid with zero sid size */
2209 SetLastError(0xdeadbeef);
2211 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
2212 ok(!ret, "Expected 0, got %d\n", ret);
2213 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2214 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2215 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2216 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2218 /* try cchReferencedDomainName - 1 */
2219 SetLastError(0xdeadbeef);
2221 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
2222 ok(!ret, "Expected 0, got %d\n", ret);
2223 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2224 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2225 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2226 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2228 /* NULL ReferencedDomainName with zero domain name size */
2229 SetLastError(0xdeadbeef);
2231 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
2232 ok(!ret, "Expected 0, got %d\n", ret);
2233 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2234 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2235 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2236 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2238 HeapFree(GetProcessHeap(), 0, psid);
2239 HeapFree(GetProcessHeap(), 0, domain);
2241 /* get sizes for NULL account name */
2244 sid_use = 0xcafebabe;
2245 SetLastError(0xdeadbeef);
2246 ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2247 if (!ret && GetLastError() == ERROR_NONE_MAPPED)
2248 win_skip("NULL account name doesn't work on NT4\n");
2251 ok(!ret, "Expected 0, got %d\n", ret);
2252 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2253 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2254 ok(sid_size != 0, "Expected non-zero sid size\n");
2255 ok(domain_size != 0, "Expected non-zero domain size\n");
2256 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2258 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2259 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2261 /* try NULL account name */
2262 ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
2263 get_sid_info(psid, &account, &sid_dom);
2264 ok(ret, "Failed to lookup account name\n");
2265 /* Using a fixed string will not work on different locales */
2266 ok(!lstrcmp(account, domain),
2267 "Got %s for account and %s for domain, these should be the same\n",
2269 ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
2271 HeapFree(GetProcessHeap(), 0, psid);
2272 HeapFree(GetProcessHeap(), 0, domain);
2275 /* try an invalid account name */
2276 SetLastError(0xdeadbeef);
2279 ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
2280 ok(!ret, "Expected 0, got %d\n", ret);
2281 ok(GetLastError() == ERROR_NONE_MAPPED ||
2282 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
2283 "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
2284 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2285 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2287 /* try an invalid system name */
2288 SetLastError(0xdeadbeef);
2291 ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2292 ok(!ret, "Expected 0, got %d\n", ret);
2293 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2294 "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
2295 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2296 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2298 /* try with the computer name as the account name */
2299 domain_size = sizeof(computer_name);
2300 GetComputerNameA(computer_name, &domain_size);
2303 ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2304 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
2305 GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
2306 broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
2307 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
2308 "LookupAccountNameA failed: %d\n", GetLastError());
2309 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2311 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2312 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2313 ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
2314 ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
2315 ok(sid_use == SidTypeDomain ||
2316 (sid_use == SidTypeUser && ! strcmp(computer_name, user_name)), "expected SidTypeDomain for %s, got %d\n", computer_name, sid_use);
2317 HeapFree(GetProcessHeap(), 0, domain);
2318 HeapFree(GetProcessHeap(), 0, psid);
2321 /* Well Known names */
2322 if (!pCreateWellKnownSid)
2324 win_skip("CreateWellKnownSid not available\n");
2328 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2330 skip("Non-English locale (skipping well known name creation tests)\n");
2334 check_wellknown_name("LocalService", WinLocalServiceSid);
2335 check_wellknown_name("Local Service", WinLocalServiceSid);
2337 check_wellknown_name("Local Service", 0);
2338 check_wellknown_name("NetworkService", WinNetworkServiceSid);
2339 check_wellknown_name("Network Service", WinNetworkServiceSid);
2341 /* example of some names where the spaces are not optional */
2342 check_wellknown_name("Terminal Server User", WinTerminalServerSid);
2343 check_wellknown_name("TerminalServer User", 0);
2344 check_wellknown_name("TerminalServerUser", 0);
2345 check_wellknown_name("Terminal ServerUser", 0);
2347 check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
2348 check_wellknown_name("enterprisedomain controllers", 0);
2349 check_wellknown_name("enterprise domaincontrollers", 0);
2350 check_wellknown_name("enterprisedomaincontrollers", 0);
2352 /* case insensitivity */
2353 check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
2355 /* fully qualified account names */
2356 check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
2357 check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
2358 check_wellknown_name("nt authority test\\Network Service", 0);
2359 check_wellknown_name("Dummy\\Network Service", 0);
2360 check_wellknown_name("ntauthority\\Network Service", 0);
2363 static void test_security_descriptor(void)
2365 SECURITY_DESCRIPTOR sd;
2368 BOOL isDefault, isPresent, ret;
2372 SetLastError(0xdeadbeef);
2373 ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
2374 if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2376 win_skip("InitializeSecurityDescriptor is not implemented\n");
2380 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2381 expect_eq(psid, NULL, PSID, "%p");
2382 expect_eq(isDefault, FALSE, BOOL, "%d");
2383 sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
2385 SetLastError(0xdeadbeef);
2387 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
2388 expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
2389 ok(size > 5, "Size not increased\n");
2392 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
2393 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2394 expect_eq(psid, NULL, PSID, "%p");
2395 expect_eq(isDefault, FALSE, BOOL, "%d");
2396 ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
2397 expect_eq(psid, NULL, PSID, "%p");
2398 expect_eq(isDefault, FALSE, BOOL, "%d");
2399 ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
2400 expect_eq(isPresent, TRUE, BOOL, "%d");
2401 expect_eq(psid, NULL, PSID, "%p");
2402 expect_eq(isDefault, FALSE, BOOL, "%d");
2403 ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
2404 expect_eq(isPresent, TRUE, BOOL, "%d");
2405 expect_eq(psid, NULL, PSID, "%p");
2406 expect_eq(isDefault, FALSE, BOOL, "%d");
2410 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
2411 #define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
2412 static void test_granted_access(HANDLE handle, ACCESS_MASK access,
2413 ACCESS_MASK alt, int line)
2415 OBJECT_BASIC_INFORMATION obj_info;
2418 if (!pNtQueryObject)
2420 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
2424 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
2425 sizeof(obj_info), NULL );
2426 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2428 ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
2429 obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
2430 "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
2432 ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
2433 "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
2436 #define CHECK_SET_SECURITY(o,i,e) \
2440 SetLastError( 0xdeadbeef ); \
2441 res_ = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
2442 err = GetLastError(); \
2443 if (e == ERROR_SUCCESS) \
2444 ok(res_, "SetKernelObjectSecurity failed with %d\n", err); \
2446 ok(!res_ && err == e, "SetKernelObjectSecurity should have failed " \
2447 "with %s, instead of %d\n", #e, err); \
2450 static void test_process_security(void)
2454 PTOKEN_PRIMARY_GROUP group;
2455 PSID AdminSid = NULL, UsersSid = NULL;
2457 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
2458 char buffer[MAX_PATH];
2459 PROCESS_INFORMATION info;
2460 STARTUPINFOA startup;
2461 SECURITY_ATTRIBUTES psa;
2462 HANDLE token, event;
2465 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
2466 res = InitializeAcl(Acl, 256, ACL_REVISION);
2467 if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2469 win_skip("ACLs not implemented - skipping tests\n");
2470 HeapFree(GetProcessHeap(), 0, Acl);
2473 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2475 /* get owner from the token we might be running as a user not admin */
2476 res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
2477 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
2480 HeapFree(GetProcessHeap(), 0, Acl);
2484 res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
2485 ok(!res, "Expected failure, got %d\n", res);
2486 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2487 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2489 owner = HeapAlloc(GetProcessHeap(), 0, size);
2490 res = GetTokenInformation( token, TokenOwner, owner, size, &size );
2491 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2492 AdminSid = ((TOKEN_OWNER*)owner)->Owner;
2494 res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
2495 ok(!res, "Expected failure, got %d\n", res);
2496 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2497 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2499 group = HeapAlloc(GetProcessHeap(), 0, size);
2500 res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
2501 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2502 UsersSid = ((TOKEN_PRIMARY_GROUP*)group)->PrimaryGroup;
2504 CloseHandle( token );
2507 HeapFree(GetProcessHeap(), 0, group);
2508 HeapFree(GetProcessHeap(), 0, owner);
2509 HeapFree(GetProcessHeap(), 0, Acl);
2513 res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
2514 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
2515 res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
2516 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2518 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
2519 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
2520 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
2522 event = CreateEvent( NULL, TRUE, TRUE, "test_event" );
2523 ok(event != NULL, "CreateEvent %d\n", GetLastError());
2525 SecurityDescriptor->Revision = 0;
2526 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
2527 SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
2529 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2530 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2531 CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
2532 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2533 /* NULL DACL is valid and means default DACL from token */
2534 SecurityDescriptor->Control |= SE_DACL_PRESENT;
2535 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2537 /* Set owner and group and dacl */
2538 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
2539 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2540 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
2541 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
2542 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2543 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
2544 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
2545 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
2546 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2548 sprintf(buffer, "%s tests/security.c test", myARGV[0]);
2549 memset(&startup, 0, sizeof(startup));
2550 startup.cb = sizeof(startup);
2551 startup.dwFlags = STARTF_USESHOWWINDOW;
2552 startup.wShowWindow = SW_SHOWNORMAL;
2554 psa.nLength = sizeof(psa);
2555 psa.lpSecurityDescriptor = SecurityDescriptor;
2556 psa.bInheritHandle = TRUE;
2558 /* Doesn't matter what ACL say we should get full access for ourselves */
2559 res = CreateProcessA( NULL, buffer, &psa, NULL, FALSE, 0, NULL, NULL, &startup, &info );
2560 ok(res, "CreateProcess with err:%d\n", GetLastError());
2561 TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS_NT4,
2562 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2563 winetest_wait_child_process( info.hProcess );
2565 CloseHandle( info.hProcess );
2566 CloseHandle( info.hThread );
2567 CloseHandle( event );
2568 HeapFree(GetProcessHeap(), 0, group);
2569 HeapFree(GetProcessHeap(), 0, owner);
2570 HeapFree(GetProcessHeap(), 0, Acl);
2571 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
2574 static void test_process_security_child(void)
2576 HANDLE handle, handle1;
2580 handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
2581 ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
2582 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
2584 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2585 &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS );
2586 ok(ret, "duplicating handle err:%d\n", GetLastError());
2587 TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
2589 CloseHandle( handle1 );
2591 SetLastError( 0xdeadbeef );
2592 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2593 &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
2594 err = GetLastError();
2596 ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
2597 "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
2599 CloseHandle( handle );
2601 /* These two should fail - they are denied by ACL */
2602 handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
2604 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
2605 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
2607 ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
2609 /* Documented privilege elevation */
2610 ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
2611 &handle, 0, TRUE, DUPLICATE_SAME_ACCESS );
2612 ok(ret, "duplicating handle err:%d\n", GetLastError());
2613 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
2614 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2616 CloseHandle( handle );
2618 /* Same only explicitly asking for all access rights */
2619 ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
2620 &handle, PROCESS_ALL_ACCESS, TRUE, 0 );
2621 ok(ret, "duplicating handle err:%d\n", GetLastError());
2622 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
2623 PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
2624 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2625 &handle1, PROCESS_VM_READ, TRUE, 0 );
2626 ok(ret, "duplicating handle err:%d\n", GetLastError());
2627 TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
2628 CloseHandle( handle1 );
2629 CloseHandle( handle );
2632 static void test_impersonation_level(void)
2634 HANDLE Token, ProcessToken;
2637 TOKEN_PRIVILEGES *Privileges;
2639 PRIVILEGE_SET *PrivilegeSet;
2645 pDuplicateTokenEx = (void *)GetProcAddress(hmod, "DuplicateTokenEx");
2646 if( !pDuplicateTokenEx ) {
2647 win_skip("DuplicateTokenEx is not available\n");
2650 SetLastError(0xdeadbeef);
2651 ret = ImpersonateSelf(SecurityAnonymous);
2652 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2654 win_skip("ImpersonateSelf is not implemented\n");
2657 ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
2658 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2659 ok(!ret, "OpenThreadToken should have failed\n");
2660 error = GetLastError();
2661 ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2662 /* can't perform access check when opening object against an anonymous impersonation token */
2664 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2665 ok(error == ERROR_INVALID_HANDLE || error == ERROR_CANT_OPEN_ANONYMOUS,
2666 "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE or ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2670 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
2671 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
2673 ret = pDuplicateTokenEx(ProcessToken,
2674 TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
2675 SecurityAnonymous, TokenImpersonation, &Token);
2676 ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
2677 /* can't increase the impersonation level */
2678 ret = DuplicateToken(Token, SecurityIdentification, &Token2);
2679 error = GetLastError();
2680 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
2681 "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2682 /* we can query anything from an anonymous token, including the user */
2683 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
2684 error = GetLastError();
2685 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2686 User = HeapAlloc(GetProcessHeap(), 0, Size);
2687 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
2688 ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
2689 HeapFree(GetProcessHeap(), 0, User);
2691 /* PrivilegeCheck fails with SecurityAnonymous level */
2692 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
2693 error = GetLastError();
2694 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2695 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
2696 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
2697 ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
2699 PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
2700 PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
2701 memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
2702 PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
2703 HeapFree(GetProcessHeap(), 0, Privileges);
2705 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2706 error = GetLastError();
2707 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2711 ret = ImpersonateSelf(SecurityIdentification);
2712 ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
2713 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2714 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2716 /* can't perform access check when opening object against an identification impersonation token */
2717 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2719 ok(error == ERROR_INVALID_HANDLE || error == ERROR_BAD_IMPERSONATION_LEVEL,
2720 "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE or ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2722 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2723 ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
2727 ret = ImpersonateSelf(SecurityImpersonation);
2728 ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
2729 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2730 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2731 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2732 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
2734 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2735 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
2739 CloseHandle(ProcessToken);
2741 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
2744 static void test_SetEntriesInAclW(void)
2747 PSID EveryoneSid = NULL, UsersSid = NULL;
2748 PACL OldAcl = NULL, NewAcl;
2749 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2750 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2751 EXPLICIT_ACCESSW ExplicitAccess;
2752 static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
2753 static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
2755 if (!pSetEntriesInAclW)
2757 win_skip("SetEntriesInAclW is not available\n");
2761 NewAcl = (PACL)0xdeadbeef;
2762 res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
2763 if(res == ERROR_CALL_NOT_IMPLEMENTED)
2765 win_skip("SetEntriesInAclW is not implemented\n");
2768 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2769 ok(NewAcl == NULL ||
2770 broken(NewAcl != NULL), /* NT4 */
2771 "NewAcl=%p, expected NULL\n", NewAcl);
2774 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
2775 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
2776 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2778 win_skip("ACLs not implemented - skipping tests\n");
2779 HeapFree(GetProcessHeap(), 0, OldAcl);
2782 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2784 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2785 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2787 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2788 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
2789 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2791 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
2792 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2794 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
2795 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
2796 ExplicitAccess.grfInheritance = NO_INHERITANCE;
2797 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
2798 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2799 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
2800 ExplicitAccess.Trustee.MultipleTrusteeOperation = 0xDEADBEEF;
2801 ExplicitAccess.Trustee.pMultipleTrustee = (PVOID)0xDEADBEEF;
2802 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2803 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2804 ok(NewAcl != NULL, "returned acl was NULL\n");
2807 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
2808 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2809 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2810 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2811 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2812 ok(NewAcl != NULL, "returned acl was NULL\n");
2815 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2817 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2821 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2822 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
2823 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2824 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2825 ok(NewAcl != NULL, "returned acl was NULL\n");
2828 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
2829 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2830 ok(res == ERROR_INVALID_PARAMETER ||
2831 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2832 "SetEntriesInAclW failed: %u\n", res);
2833 ok(NewAcl == NULL ||
2834 broken(NewAcl != NULL), /* NT4 */
2835 "returned acl wasn't NULL: %p\n", NewAcl);
2837 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2838 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
2839 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2840 ok(res == ERROR_INVALID_PARAMETER ||
2841 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2842 "SetEntriesInAclW failed: %u\n", res);
2843 ok(NewAcl == NULL ||
2844 broken(NewAcl != NULL), /* NT4 */
2845 "returned acl wasn't NULL: %p\n", NewAcl);
2847 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2848 ExplicitAccess.grfAccessMode = SET_ACCESS;
2849 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2850 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2851 ok(NewAcl != NULL, "returned acl was NULL\n");
2855 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2856 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
2857 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2858 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2859 ok(NewAcl != NULL, "returned acl was NULL\n");
2862 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
2863 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2864 ExplicitAccess.Trustee.ptstrName = UsersSid;
2865 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2866 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2867 ok(NewAcl != NULL, "returned acl was NULL\n");
2871 FreeSid(EveryoneSid);
2872 HeapFree(GetProcessHeap(), 0, OldAcl);
2875 static void test_SetEntriesInAclA(void)
2878 PSID EveryoneSid = NULL, UsersSid = NULL;
2879 PACL OldAcl = NULL, NewAcl;
2880 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2881 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2882 EXPLICIT_ACCESS ExplicitAccess;
2883 static const CHAR szEveryone[] = {'E','v','e','r','y','o','n','e',0};
2884 static const CHAR szCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
2886 if (!pSetEntriesInAclA)
2888 win_skip("SetEntriesInAclA is not available\n");
2892 NewAcl = (PACL)0xdeadbeef;
2893 res = pSetEntriesInAclA(0, NULL, NULL, &NewAcl);
2894 if(res == ERROR_CALL_NOT_IMPLEMENTED)
2896 win_skip("SetEntriesInAclA is not implemented\n");
2899 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2900 ok(NewAcl == NULL ||
2901 broken(NewAcl != NULL), /* NT4 */
2902 "NewAcl=%p, expected NULL\n", NewAcl);
2905 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
2906 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
2907 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2909 win_skip("ACLs not implemented - skipping tests\n");
2910 HeapFree(GetProcessHeap(), 0, OldAcl);
2913 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2915 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2916 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2918 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2919 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
2920 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2922 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
2923 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2925 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
2926 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
2927 ExplicitAccess.grfInheritance = NO_INHERITANCE;
2928 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
2929 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2930 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
2931 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2932 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2933 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2934 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2935 ok(NewAcl != NULL, "returned acl was NULL\n");
2938 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
2939 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2940 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2941 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2942 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2943 ok(NewAcl != NULL, "returned acl was NULL\n");
2946 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2948 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2952 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2953 ExplicitAccess.Trustee.ptstrName = (LPSTR)szEveryone;
2954 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2955 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2956 ok(NewAcl != NULL, "returned acl was NULL\n");
2959 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
2960 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2961 ok(res == ERROR_INVALID_PARAMETER ||
2962 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2963 "SetEntriesInAclA failed: %u\n", res);
2964 ok(NewAcl == NULL ||
2965 broken(NewAcl != NULL), /* NT4 */
2966 "returned acl wasn't NULL: %p\n", NewAcl);
2968 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2969 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
2970 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2971 ok(res == ERROR_INVALID_PARAMETER ||
2972 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2973 "SetEntriesInAclA failed: %u\n", res);
2974 ok(NewAcl == NULL ||
2975 broken(NewAcl != NULL), /* NT4 */
2976 "returned acl wasn't NULL: %p\n", NewAcl);
2978 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2979 ExplicitAccess.grfAccessMode = SET_ACCESS;
2980 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2981 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2982 ok(NewAcl != NULL, "returned acl was NULL\n");
2986 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
2987 ExplicitAccess.Trustee.ptstrName = (LPSTR)szCurrentUser;
2988 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2989 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2990 ok(NewAcl != NULL, "returned acl was NULL\n");
2993 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
2994 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2995 ExplicitAccess.Trustee.ptstrName = UsersSid;
2996 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
2997 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
2998 ok(NewAcl != NULL, "returned acl was NULL\n");
3002 FreeSid(EveryoneSid);
3003 HeapFree(GetProcessHeap(), 0, OldAcl);
3006 static void test_GetNamedSecurityInfoA(void)
3008 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], dacl[100], *user;
3009 DWORD sid_size = sizeof(admin_ptr), user_size;
3010 char invalid_path[] = "/an invalid file path";
3011 PSID admin_sid = (PSID) admin_ptr, user_sid;
3012 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3013 SECURITY_DESCRIPTOR_CONTROL control;
3014 ACL_SIZE_INFORMATION acl_size;
3015 CHAR windows_dir[MAX_PATH];
3016 PSECURITY_DESCRIPTOR pSD;
3017 ACCESS_ALLOWED_ACE *ace;
3018 BOOL bret = TRUE, isNT4;
3019 char tmpfile[MAX_PATH];
3020 DWORD error, revision;
3021 BOOL owner_defaulted;
3022 BOOL group_defaulted;
3023 HANDLE token, hTemp;
3027 if (!pSetNamedSecurityInfoA || !pGetNamedSecurityInfoA || !pCreateWellKnownSid)
3029 win_skip("Required functions are not available\n");
3033 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3035 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3036 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3040 win_skip("Failed to get current user token\n");
3043 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3044 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3045 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3046 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3047 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3048 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3049 CloseHandle( token );
3050 user_sid = ((TOKEN_USER *)user)->User.Sid;
3052 bret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
3053 ok(bret, "GetWindowsDirectory failed with error %d\n", GetLastError());
3055 SetLastError(0xdeadbeef);
3056 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
3057 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
3058 NULL, NULL, NULL, NULL, &pSD);
3059 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3061 win_skip("GetNamedSecurityInfoA is not implemented\n");
3062 HeapFree(GetProcessHeap(), 0, user);
3065 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3067 bret = GetSecurityDescriptorControl(pSD, &control, &revision);
3068 ok(bret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
3069 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
3070 broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
3071 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
3072 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
3074 isNT4 = (control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT;
3076 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
3077 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3078 ok(owner != NULL, "owner should not be NULL\n");
3080 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
3081 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3082 ok(group != NULL, "group should not be NULL\n");
3086 /* NULL descriptor tests */
3089 win_skip("NT4 does not support GetNamedSecutityInfo with a NULL descriptor\n");
3090 HeapFree(GetProcessHeap(), 0, user);
3094 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3095 NULL, NULL, NULL, NULL, NULL);
3096 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3098 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3099 NULL, NULL, &pDacl, NULL, NULL);
3100 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3101 ok(pDacl != NULL, "DACL should not be NULL\n");
3103 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,
3104 NULL, NULL, &pDacl, NULL, NULL);
3105 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3107 /* Test behavior of SetNamedSecurityInfo with an invalid path */
3108 SetLastError(0xdeadbeef);
3109 error = pSetNamedSecurityInfoA(invalid_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3111 ok(error == ERROR_FILE_NOT_FOUND, "Unexpected error returned: 0x%x\n", error);
3112 ok(GetLastError() == 0xdeadbeef, "Expected last error to remain unchanged.\n");
3114 /* Create security descriptor information and test that it comes back the same */
3116 pDacl = (PACL)&dacl;
3117 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3118 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3119 bret = InitializeAcl(pDacl, sizeof(dacl), ACL_REVISION);
3120 ok(bret, "Failed to initialize ACL.\n");
3121 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
3122 HeapFree(GetProcessHeap(), 0, user);
3123 ok(bret, "Failed to add Current User to ACL.\n");
3124 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
3125 ok(bret, "Failed to add Administrator Group to ACL.\n");
3126 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3127 ok(bret, "Failed to add ACL to security desciptor.\n");
3128 GetTempFileNameA(".", "foo", 0, tmpfile);
3129 hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING,
3130 FILE_FLAG_DELETE_ON_CLOSE, NULL);
3131 SetLastError(0xdeadbeef);
3132 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3134 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3136 win_skip("SetNamedSecurityInfoA is not implemented\n");
3140 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
3141 SetLastError(0xdeadbeef);
3142 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3143 NULL, NULL, &pDacl, NULL, &pSD);
3144 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3146 win_skip("GetNamedSecurityInfoA is not implemented\n");
3149 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3151 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3152 ok(bret, "GetAclInformation failed\n");
3153 if (acl_size.AceCount > 0)
3155 bret = pGetAce(pDacl, 0, (VOID **)&ace);
3156 ok(bret, "Failed to get Current User ACE.\n");
3157 bret = EqualSid(&ace->SidStart, user_sid);
3158 todo_wine ok(bret, "Current User ACE != Current User SID.\n");
3159 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3160 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3161 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3164 if (acl_size.AceCount > 1)
3166 bret = pGetAce(pDacl, 1, (VOID **)&ace);
3167 ok(bret, "Failed to get Administators Group ACE.\n");
3168 bret = EqualSid(&ace->SidStart, admin_sid);
3169 todo_wine ok(bret || broken(!bret) /* win2k */,
3170 "Administators Group ACE != Administators Group SID.\n");
3171 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3172 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3173 ok(ace->Mask == 0x1f01ff || broken(ace->Mask == GENERIC_ALL) /* win2k */,
3174 "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n", ace->Mask);
3180 static void test_ConvertStringSecurityDescriptor(void)
3183 PSECURITY_DESCRIPTOR pSD;
3184 static const WCHAR Blank[] = { 0 };
3188 const char *sidstring;
3195 { "D:(A;;GA;;;WD)", 0xdeadbeef, FALSE, ERROR_UNKNOWN_REVISION },
3196 /* test ACE string type */
3197 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3198 { "D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3199 { "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
3200 /* test ACE string with spaces */
3201 { " D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3202 { "D: (D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3203 { "D:( D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3204 { "D:(D ;;GA;;;WD)", SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
3205 { "D:(D; ;GA;;;WD)", SDDL_REVISION_1, TRUE },
3206 { "D:(D;; GA;;;WD)", SDDL_REVISION_1, TRUE },
3207 { "D:(D;;GA ;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
3208 { "D:(D;;GA; ;;WD)", SDDL_REVISION_1, TRUE },
3209 { "D:(D;;GA;; ;WD)", SDDL_REVISION_1, TRUE },
3210 { "D:(D;;GA;;; WD)", SDDL_REVISION_1, TRUE },
3211 { "D:(D;;GA;;;WD )", SDDL_REVISION_1, TRUE },
3212 /* test ACE string access rights */
3213 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3214 { "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, TRUE },
3215 { "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, TRUE },
3216 { "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, TRUE },
3217 { "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, TRUE },
3218 { "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, TRUE },
3219 { "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
3220 { "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
3221 /* test ACE string access right error case */
3222 { "D:(A;;ROB;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
3223 /* test behaviour with empty strings */
3224 { "", SDDL_REVISION_1, TRUE },
3225 /* test ACE string SID */
3226 { "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, TRUE },
3227 { "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
3230 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
3232 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3236 for (i = 0; i < sizeof(cssd)/sizeof(cssd[0]); i++)
3240 SetLastError(0xdeadbeef);
3241 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3242 cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
3243 GLE = GetLastError();
3244 ok(ret == cssd[i].ret, "(%02u) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
3246 ok(GLE == cssd[i].GLE ||
3247 (cssd[i].altGLE && GLE == cssd[i].altGLE),
3248 "(%02u) Unexpected last error %d\n", i, GLE);
3253 /* test behaviour with NULL parameters */
3254 SetLastError(0xdeadbeef);
3255 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3256 NULL, 0xdeadbeef, &pSD, NULL);
3258 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3259 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3262 SetLastError(0xdeadbeef);
3263 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
3264 NULL, 0xdeadbeef, &pSD, NULL);
3265 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3266 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3269 SetLastError(0xdeadbeef);
3270 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3271 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
3272 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3273 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3276 SetLastError(0xdeadbeef);
3277 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3278 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
3279 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3280 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3283 /* test behaviour with empty strings */
3284 SetLastError(0xdeadbeef);
3285 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
3286 Blank, SDDL_REVISION_1, &pSD, NULL);
3287 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
3291 static void test_ConvertSecurityDescriptorToString(void)
3293 SECURITY_DESCRIPTOR desc;
3294 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
3303 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
3305 win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
3308 if (!pCreateWellKnownSid)
3310 win_skip("CreateWellKnownSid is not available\n");
3314 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
3315 * don't replicate this feature so we only test len >= strlen+1. */
3316 #define CHECK_RESULT_AND_FREE(exp_str) \
3317 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
3318 ok(len >= (strlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(exp_str) + 1, len); \
3321 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
3322 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); \
3323 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); \
3326 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
3327 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3328 CHECK_RESULT_AND_FREE("");
3331 pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
3332 SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
3333 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3334 CHECK_RESULT_AND_FREE("O:S-1-2-0");
3336 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
3337 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3338 CHECK_RESULT_AND_FREE("O:S-1-2-0");
3340 size = sizeof(sid_buf);
3341 pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
3342 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
3343 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3344 CHECK_RESULT_AND_FREE("O:SY");
3346 pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
3347 SetSecurityDescriptorGroup(&desc, psid, TRUE);
3348 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3349 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
3351 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
3352 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
3354 pacl = (PACL)acl_buf;
3355 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
3356 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
3357 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3358 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
3360 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
3361 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3362 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
3364 pConvertStringSidToSidA("S-1-5-6", &psid2);
3365 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
3366 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3367 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
3369 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
3370 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3371 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
3373 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
3374 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3375 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)");
3378 pacl = (PACL)acl_buf;
3379 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
3380 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
3381 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3382 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
3384 /* fails in win2k */
3385 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
3386 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
3387 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
3389 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
3390 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
3393 /* fails in win2k */
3394 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
3395 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
3397 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
3398 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
3405 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
3407 SECURITY_DESCRIPTOR_CONTROL ref;
3408 SECURITY_DESCRIPTOR_CONTROL test;
3410 SECURITY_DESCRIPTOR_CONTROL const mutable
3411 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
3412 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
3413 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
3414 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
3416 SECURITY_DESCRIPTOR_CONTROL const immutable
3417 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
3418 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
3419 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
3420 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
3425 LPCSTR fmt = "Expected error %s, got %u\n";
3427 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
3429 /* The mutable bits are mutable regardless of the truth of
3430 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
3432 /* Check call barfs if any bit-of-interest is immutable */
3433 for (bit = 0; bit < 16; ++bit)
3435 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
3436 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
3438 SECURITY_DESCRIPTOR_CONTROL ctrl;
3440 DWORD dwExpect = (bitOfInterest & immutable)
3441 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
3442 LPCSTR strExpect = (bitOfInterest & immutable)
3443 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
3445 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
3446 setOrClear ^= bitOfInterest;
3447 SetLastError (0xbebecaca);
3448 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
3449 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3450 GetSecurityDescriptorControl(sec, &test, &dwRevision);
3451 expect_eq(test, ctrl, int, "%x");
3453 setOrClear ^= bitOfInterest;
3454 SetLastError (0xbebecaca);
3455 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
3456 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3457 GetSecurityDescriptorControl (sec, &test, &dwRevision);
3458 expect_eq(test, ref, int, "%x");
3461 /* Check call barfs if any bit-to-set is immutable
3462 even when not a bit-of-interest */
3463 for (bit = 0; bit < 16; ++bit)
3465 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
3466 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
3468 SECURITY_DESCRIPTOR_CONTROL ctrl;
3470 DWORD dwExpect = ((1 << bit) & immutable)
3471 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
3472 LPCSTR strExpect = ((1 << bit) & immutable)
3473 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
3475 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
3476 setOrClear ^= bitsOfInterest;
3477 SetLastError (0xbebecaca);
3478 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
3479 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3480 GetSecurityDescriptorControl(sec, &test, &dwRevision);
3481 expect_eq(test, ctrl, int, "%x");
3483 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
3484 setOrClear ^= bitsOfInterest;
3485 SetLastError (0xbebecaca);
3486 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
3487 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3488 GetSecurityDescriptorControl(sec, &test, &dwRevision);
3489 expect_eq(test, ctrl, int, "%x");
3493 static void test_PrivateObjectSecurity(void)
3495 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
3496 SECURITY_DESCRIPTOR_CONTROL ctrl;
3497 PSECURITY_DESCRIPTOR sec;
3503 PSECURITY_DESCRIPTOR buf;
3506 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
3508 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3512 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3514 "G:S-1-5-21-93476-23408-4576"
3515 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
3516 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3517 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
3518 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3520 test_SetSecurityDescriptorControl(sec);
3524 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3526 "G:S-1-5-21-93476-23408-4576",
3527 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3529 test_SetSecurityDescriptorControl(sec);
3533 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3535 "G:S-1-5-21-93476-23408-4576"
3536 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3537 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3538 buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
3539 pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
3540 GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
3541 expect_eq(ctrl, 0x9014, int, "%x");
3543 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
3544 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3545 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3546 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3547 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
3548 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3549 expect_eq(ctrl, 0x8000, int, "%x");
3551 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
3552 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3553 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3554 ret = pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len);
3555 ok(ret, "Conversion failed err=%u\n", GetLastError());
3556 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)",
3557 "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 */
3558 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3559 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8004, int, "%x");
3561 ret = GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize);
3562 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3563 ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3564 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3565 CHECK_ONE_OF_AND_FREE("O:SY"
3566 "G:S-1-5-21-93476-23408-4576"
3567 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3568 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
3570 "G:S-1-5-21-93476-23408-4576"
3571 "D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3572 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)"); /* Win7 */
3573 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3574 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8014, int, "%x");
3576 SetLastError(0xdeadbeef);
3577 ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
3578 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
3581 HeapFree(GetProcessHeap(), 0, buf);
3583 #undef CHECK_RESULT_AND_FREE
3584 #undef CHECK_ONE_OF_AND_FREE
3586 static void test_acls(void)
3589 PACL pAcl = (PACL)buffer;
3592 SetLastError(0xdeadbeef);
3593 ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
3594 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3596 win_skip("InitializeAcl is not implemented\n");
3600 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
3602 SetLastError(0xdeadbeef);
3603 ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
3604 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
3606 SetLastError(0xdeadbeef);
3607 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
3608 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
3610 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
3611 ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
3613 ret = IsValidAcl(pAcl);
3614 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3616 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
3617 ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
3619 ret = IsValidAcl(pAcl);
3620 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3622 SetLastError(0xdeadbeef);
3623 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
3624 if (GetLastError() != ERROR_INVALID_PARAMETER)
3626 ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
3628 ret = IsValidAcl(pAcl);
3629 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3632 win_skip("ACL_REVISION4 is not implemented on NT4\n");
3634 SetLastError(0xdeadbeef);
3635 ret = InitializeAcl(pAcl, sizeof(buffer), -1);
3636 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
3639 static void test_GetSecurityInfo(void)
3641 char b[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
3642 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], dacl[100];
3643 DWORD sid_size = sizeof(admin_ptr), l = sizeof(b);
3644 PSID admin_sid = (PSID) admin_ptr, user_sid;
3645 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3646 ACL_SIZE_INFORMATION acl_size;
3647 PSECURITY_DESCRIPTOR pSD;
3648 ACCESS_ALLOWED_ACE *ace;
3655 if (!pGetSecurityInfo || !pSetSecurityInfo)
3657 win_skip("[Get|Set]SecurityInfo is not available\n");
3661 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3663 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3664 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3668 win_skip("Failed to get current user token\n");
3671 GetTokenInformation(token, TokenUser, b, l, &l);
3672 CloseHandle( token );
3673 user_sid = ((TOKEN_USER *)b)->User.Sid;
3675 /* Create something. Files have lots of associated security info. */
3676 obj = CreateFile(myARGV[0], GENERIC_READ|WRITE_DAC, FILE_SHARE_READ, NULL,
3677 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3678 if (obj == INVALID_HANDLE_VALUE)
3680 skip("Couldn't create an object for GetSecurityInfo test\n");
3684 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3685 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3686 &owner, &group, &pDacl, NULL, &pSD);
3687 if (ret == ERROR_CALL_NOT_IMPLEMENTED)
3689 win_skip("GetSecurityInfo is not implemented\n");
3693 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3694 ok(pSD != NULL, "GetSecurityInfo\n");
3695 ok(owner != NULL, "GetSecurityInfo\n");
3696 ok(group != NULL, "GetSecurityInfo\n");
3698 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
3700 win_skip("No ACL information returned\n");
3704 if (!pCreateWellKnownSid)
3706 win_skip("NULL parameter test would crash on NT4\n");
3711 /* If we don't ask for the security descriptor, Windows will still give us
3712 the other stuff, leaving us no way to free it. */
3713 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3714 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3715 &owner, &group, &pDacl, NULL, NULL);
3716 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3717 ok(owner != NULL, "GetSecurityInfo\n");
3718 ok(group != NULL, "GetSecurityInfo\n");
3720 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
3722 win_skip("No ACL information returned\n");
3724 /* Create security descriptor information and test that it comes back the same */
3726 pDacl = (PACL)&dacl;
3727 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3728 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3729 bret = InitializeAcl(pDacl, sizeof(dacl), ACL_REVISION);
3730 ok(bret, "Failed to initialize ACL.\n");
3731 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
3732 ok(bret, "Failed to add Current User to ACL.\n");
3733 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
3734 ok(bret, "Failed to add Administrator Group to ACL.\n");
3735 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3736 ok(bret, "Failed to add ACL to security desciptor.\n");
3737 ret = pSetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3738 NULL, NULL, pDacl, NULL);
3739 ok(ret == ERROR_SUCCESS, "SetSecurityInfo returned %d\n", ret);
3740 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3741 NULL, NULL, &pDacl, NULL, NULL);
3742 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3743 ok(pDacl && IsValidAcl(pDacl), "GetSecurityInfo returned invalid DACL.\n");
3744 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3745 ok(bret, "GetAclInformation failed\n");
3746 if (acl_size.AceCount > 0)
3748 bret = pGetAce(pDacl, 0, (VOID **)&ace);
3749 ok(bret, "Failed to get Current User ACE.\n");
3750 bret = EqualSid(&ace->SidStart, user_sid);
3751 todo_wine ok(bret, "Current User ACE != Current User SID.\n");
3752 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3753 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3754 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3757 if (acl_size.AceCount > 1)
3759 bret = pGetAce(pDacl, 1, (VOID **)&ace);
3760 ok(bret, "Failed to get Administators Group ACE.\n");
3761 bret = EqualSid(&ace->SidStart, admin_sid);
3762 todo_wine ok(bret, "Administators Group ACE != Administators Group SID.\n");
3763 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3764 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3765 ok(ace->Mask == 0x1f01ff, "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3771 static void test_GetSidSubAuthority(void)
3775 if (!pGetSidSubAuthority || !pConvertStringSidToSidA || !pIsValidSid || !pGetSidSubAuthorityCount)
3777 win_skip("Some functions not available\n");
3780 /* Note: on windows passing in an invalid index like -1, lets GetSidSubAuthority return 0x05000000 but
3781 still GetLastError returns ERROR_SUCCESS then. We don't test these unlikely cornercases here for now */
3782 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576",&psid),"ConvertStringSidToSidA failed\n");
3783 ok(pIsValidSid(psid),"Sid is not valid\n");
3784 SetLastError(0xbebecaca);
3785 ok(*pGetSidSubAuthorityCount(psid) == 4,"GetSidSubAuthorityCount gave %d expected 4\n",*pGetSidSubAuthorityCount(psid));
3786 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3787 SetLastError(0xbebecaca);
3788 ok(*pGetSidSubAuthority(psid,0) == 21,"GetSidSubAuthority gave %d expected 21\n",*pGetSidSubAuthority(psid,0));
3789 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3790 SetLastError(0xbebecaca);
3791 ok(*pGetSidSubAuthority(psid,1) == 93476,"GetSidSubAuthority gave %d expected 93476\n",*pGetSidSubAuthority(psid,1));
3792 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3793 SetLastError(0xbebecaca);
3794 ok(pGetSidSubAuthority(psid,4) != NULL,"Expected out of bounds GetSidSubAuthority to return a non-NULL pointer\n");
3795 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3799 static void test_CheckTokenMembership(void)
3801 PTOKEN_GROUPS token_groups;
3803 HANDLE process_token, token;
3808 if (!pCheckTokenMembership)
3810 win_skip("CheckTokenMembership is not available\n");
3813 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
3814 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
3816 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
3817 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
3820 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
3821 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
3822 "GetTokenInformation(TokenGroups) %s with error %d\n",
3823 ret ? "succeeded" : "failed", GetLastError());
3824 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
3825 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
3826 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
3828 for (i = 0; i < token_groups->GroupCount; i++)
3830 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
3834 if (i == token_groups->GroupCount)
3836 HeapFree(GetProcessHeap(), 0, token_groups);
3838 skip("user not a member of any group\n");
3843 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
3844 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
3845 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
3848 ret = pCheckTokenMembership(NULL, token_groups->Groups[i].Sid, &is_member);
3849 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
3850 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
3853 SetLastError(0xdeadbeef);
3854 ret = pCheckTokenMembership(process_token, token_groups->Groups[i].Sid, &is_member);
3855 ok(!ret && GetLastError() == ERROR_NO_IMPERSONATION_TOKEN,
3856 "CheckTokenMembership with process token %s with error %d\n",
3857 ret ? "succeeded" : "failed", GetLastError());
3858 ok(!is_member, "CheckTokenMembership should have cleared is_member\n");
3860 HeapFree(GetProcessHeap(), 0, token_groups);
3862 CloseHandle(process_token);
3865 static void test_EqualSid(void)
3869 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
3870 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3872 SetLastError(0xdeadbeef);
3873 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
3874 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid1);
3875 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3877 win_skip("AllocateAndInitializeSid is not implemented\n");
3880 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3881 ok(GetLastError() == 0xdeadbeef,
3882 "AllocateAndInitializeSid shouldn't have set last error to %d\n",
3885 ret = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
3886 0, 0, 0, 0, 0, 0, 0, &sid2);
3887 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3889 SetLastError(0xdeadbeef);
3890 ret = EqualSid(sid1, sid2);
3891 ok(!ret, "World and domain admins sids shouldn't have been equal\n");
3892 ok(GetLastError() == ERROR_SUCCESS ||
3893 broken(GetLastError() == 0xdeadbeef), /* NT4 */
3894 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
3897 SetLastError(0xdeadbeef);
3898 sid2 = FreeSid(sid2);
3899 ok(!sid2, "FreeSid should have returned NULL instead of %p\n", sid2);
3900 ok(GetLastError() == 0xdeadbeef,
3901 "FreeSid shouldn't have set last error to %d\n",
3904 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
3905 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid2);
3906 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3908 SetLastError(0xdeadbeef);
3909 ret = EqualSid(sid1, sid2);
3910 ok(ret, "Same sids should have been equal\n");
3911 ok(GetLastError() == ERROR_SUCCESS ||
3912 broken(GetLastError() == 0xdeadbeef), /* NT4 */
3913 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
3916 ((SID *)sid2)->Revision = 2;
3917 SetLastError(0xdeadbeef);
3918 ret = EqualSid(sid1, sid2);
3919 ok(!ret, "EqualSid with invalid sid should have returned FALSE\n");
3920 ok(GetLastError() == ERROR_SUCCESS ||
3921 broken(GetLastError() == 0xdeadbeef), /* NT4 */
3922 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
3924 ((SID *)sid2)->Revision = SID_REVISION;
3930 static void test_GetUserNameA(void)
3932 char buffer[UNLEN + 1], filler[UNLEN + 1];
3933 DWORD required_len, buffer_len;
3936 /* Test crashes on Windows. */
3939 SetLastError(0xdeadbeef);
3940 GetUserNameA(NULL, NULL);
3943 SetLastError(0xdeadbeef);
3945 ret = GetUserNameA(NULL, &required_len);
3946 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
3947 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
3948 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
3950 SetLastError(0xdeadbeef);
3952 ret = GetUserNameA(NULL, &required_len);
3953 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
3954 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
3955 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
3957 /* Tests crashes on Windows. */
3960 SetLastError(0xdeadbeef);
3961 required_len = UNLEN + 1;
3962 GetUserNameA(NULL, &required_len);
3964 SetLastError(0xdeadbeef);
3965 GetUserNameA(buffer, NULL);
3968 memset(filler, 'x', sizeof(filler));
3970 /* Note that GetUserNameA on XP and newer outputs the number of bytes
3971 * required for a Unicode string, which affects a test in the next block. */
3972 SetLastError(0xdeadbeef);
3973 memcpy(buffer, filler, sizeof(filler));
3975 ret = GetUserNameA(buffer, &required_len);
3976 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
3977 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
3978 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
3979 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
3981 SetLastError(0xdeadbeef);
3982 memcpy(buffer, filler, sizeof(filler));
3983 buffer_len = required_len;
3984 ret = GetUserNameA(buffer, &buffer_len);
3985 ok(ret == TRUE, "GetUserNameA returned %d, last error %u\n", ret, GetLastError());
3986 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
3987 ok(buffer_len == required_len ||
3988 broken(buffer_len == required_len / sizeof(WCHAR)), /* XP+ */
3989 "Outputted buffer length was %u\n", buffer_len);
3991 /* Use the reported buffer size from the last GetUserNameA call and pass
3992 * a length that is one less than the required value. */
3993 SetLastError(0xdeadbeef);
3994 memcpy(buffer, filler, sizeof(filler));
3996 ret = GetUserNameA(buffer, &buffer_len);
3997 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
3998 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was untouched\n");
3999 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
4000 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4003 static void test_GetUserNameW(void)
4005 WCHAR buffer[UNLEN + 1], filler[UNLEN + 1];
4006 DWORD required_len, buffer_len;
4009 /* Test crashes on Windows. */
4012 SetLastError(0xdeadbeef);
4013 GetUserNameW(NULL, NULL);
4016 SetLastError(0xdeadbeef);
4018 ret = GetUserNameW(NULL, &required_len);
4019 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4020 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
4021 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4023 SetLastError(0xdeadbeef);
4025 ret = GetUserNameW(NULL, &required_len);
4026 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4027 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
4028 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4030 /* Tests crash on Windows. */
4033 SetLastError(0xdeadbeef);
4034 required_len = UNLEN + 1;
4035 GetUserNameW(NULL, &required_len);
4037 SetLastError(0xdeadbeef);
4038 GetUserNameW(buffer, NULL);
4041 memset(filler, 'x', sizeof(filler));
4043 SetLastError(0xdeadbeef);
4044 memcpy(buffer, filler, sizeof(filler));
4046 ret = GetUserNameW(buffer, &required_len);
4047 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4048 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
4049 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
4050 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4052 SetLastError(0xdeadbeef);
4053 memcpy(buffer, filler, sizeof(filler));
4054 buffer_len = required_len;
4055 ret = GetUserNameW(buffer, &buffer_len);
4056 ok(ret == TRUE, "GetUserNameW returned %d, last error %u\n", ret, GetLastError());
4057 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
4058 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
4060 /* GetUserNameW on XP and newer writes a truncated portion of the username string to the buffer. */
4061 SetLastError(0xdeadbeef);
4062 memcpy(buffer, filler, sizeof(filler));
4064 ret = GetUserNameW(buffer, &buffer_len);
4065 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4066 ok(!memcmp(buffer, filler, sizeof(filler)) ||
4067 broken(memcmp(buffer, filler, sizeof(filler)) != 0), /* XP+ */
4068 "Output buffer was altered\n");
4069 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
4070 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4073 static void test_CreateRestrictedToken(void)
4075 HANDLE process_token, token, r_token;
4076 PTOKEN_GROUPS token_groups, groups2;
4077 SID_AND_ATTRIBUTES sattr;
4083 if (!pCreateRestrictedToken)
4085 win_skip("CreateRestrictedToken is not available\n");
4089 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
4090 ok(ret, "got error %d\n", GetLastError());
4092 ret = DuplicateTokenEx(process_token, TOKEN_DUPLICATE|TOKEN_ADJUST_GROUPS|TOKEN_QUERY,
4093 NULL, SecurityImpersonation, TokenImpersonation, &token);
4094 ok(ret, "got error %d\n", GetLastError());
4097 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
4098 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
4099 "got %d with error %d\n", ret, GetLastError());
4100 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
4101 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
4102 ok(ret, "got error %d\n", GetLastError());
4104 for (i = 0; i < token_groups->GroupCount; i++)
4106 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
4110 if (i == token_groups->GroupCount)
4112 HeapFree(GetProcessHeap(), 0, token_groups);
4114 skip("User not a member of any group\n");
4119 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
4120 ok(ret, "got error %d\n", GetLastError());
4121 ok(is_member, "not a member\n");
4123 /* disable a SID in new token */
4124 sattr.Sid = token_groups->Groups[i].Sid;
4125 sattr.Attributes = 0;
4127 ret = pCreateRestrictedToken(token, 0, 1, &sattr, 0, NULL, 0, NULL, &r_token);
4128 todo_wine ok(ret, "got error %d\n", GetLastError());
4132 /* check if a SID is enabled */
4134 ret = pCheckTokenMembership(r_token, token_groups->Groups[i].Sid, &is_member);
4135 ok(ret, "got error %d\n", GetLastError());
4136 ok(!is_member, "not a member\n");
4138 ret = GetTokenInformation(r_token, TokenGroups, NULL, 0, &size);
4139 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d with error %d\n",
4140 ret, GetLastError());
4141 groups2 = HeapAlloc(GetProcessHeap(), 0, size);
4142 ret = GetTokenInformation(r_token, TokenGroups, groups2, size, &size);
4143 ok(ret, "got error %d\n", GetLastError());
4145 for (j = 0; j < groups2->GroupCount; j++)
4147 if (EqualSid(groups2->Groups[j].Sid, token_groups->Groups[i].Sid))
4151 ok(groups2->Groups[j].Attributes & SE_GROUP_USE_FOR_DENY_ONLY,
4152 "got wrong attributes\n");
4153 ok((groups2->Groups[j].Attributes & SE_GROUP_ENABLED) == 0,
4154 "got wrong attributes\n");
4156 HeapFree(GetProcessHeap(), 0, groups2);
4159 HeapFree(GetProcessHeap(), 0, token_groups);
4160 CloseHandle(r_token);
4162 CloseHandle(process_token);
4165 static void validate_default_security_descriptor(SECURITY_DESCRIPTOR *sd)
4167 BOOL ret, present, defaulted;
4171 ret = IsValidSecurityDescriptor(sd);
4172 ok(ret, "security descriptor is not valid\n");
4176 acl = (void *)0xdeadbeef;
4177 SetLastError(0xdeadbeef);
4178 ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
4179 ok(ret, "GetSecurityDescriptorDacl error %d\n", GetLastError());
4181 ok(present == 1, "acl is not present\n");
4183 ok(acl != (void *)0xdeadbeef && acl != NULL, "acl pointer is not set\n");
4184 ok(defaulted == 0, "defaulted is set to TRUE\n");
4187 sid = (void *)0xdeadbeef;
4188 SetLastError(0xdeadbeef);
4189 ret = GetSecurityDescriptorOwner(sd, &sid, &defaulted);
4190 ok(ret, "GetSecurityDescriptorOwner error %d\n", GetLastError());
4192 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
4193 ok(defaulted == 0, "defaulted is set to TRUE\n");
4196 sid = (void *)0xdeadbeef;
4197 SetLastError(0xdeadbeef);
4198 ret = GetSecurityDescriptorGroup(sd, &sid, &defaulted);
4199 ok(ret, "GetSecurityDescriptorGroup error %d\n", GetLastError());
4201 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
4202 ok(defaulted == 0, "defaulted is set to TRUE\n");
4205 static void test_default_handle_security(HANDLE token, HANDLE handle, GENERIC_MAPPING *mapping)
4207 DWORD ret, length, needed, granted, priv_set_len;
4209 PRIVILEGE_SET priv_set;
4210 SECURITY_DESCRIPTOR *sd;
4212 needed = 0xdeadbeef;
4213 SetLastError(0xdeadbeef);
4214 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4216 ok(!ret, "GetKernelObjectSecurity should fail\n");
4217 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4218 ok(needed != 0xdeadbeef, "GetKernelObjectSecurity should return required buffer length\n");
4221 sd = HeapAlloc(GetProcessHeap(), 0, length);
4223 needed = 0xdeadbeef;
4224 SetLastError(0xdeadbeef);
4225 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4226 sd, length, &needed);
4227 ok(ret, "GetKernelObjectSecurity error %d\n", GetLastError());
4228 ok(needed == length || needed == 0 /* file, pipe */, "GetKernelObjectSecurity should return %u instead of %u\n", length, needed);
4230 validate_default_security_descriptor(sd);
4232 priv_set_len = sizeof(priv_set);
4233 granted = 0xdeadbeef;
4234 status = 0xdeadbeef;
4235 SetLastError(0xdeadbeef);
4236 ret = AccessCheck(sd, token, MAXIMUM_ALLOWED, mapping, &priv_set, &priv_set_len, &granted, &status);
4238 ok(ret, "AccessCheck error %d\n", GetLastError());
4239 ok(status == 1, "expected 1, got %d\n", status);
4240 ok(granted == mapping->GenericAll, "expected all access %#x, got %#x\n", mapping->GenericAll, granted);
4242 priv_set_len = sizeof(priv_set);
4243 granted = 0xdeadbeef;
4244 status = 0xdeadbeef;
4245 SetLastError(0xdeadbeef);
4246 ret = AccessCheck(sd, token, 0, mapping, &priv_set, &priv_set_len, &granted, &status);
4248 ok(ret, "AccessCheck error %d\n", GetLastError());
4249 ok(status == 0 || broken(status == 1) /* NT4 */, "expected 0, got %d\n", status);
4250 ok(granted == 0 || broken(granted == mapping->GenericRead) /* NT4 */, "expected 0, got %#x\n", granted);
4252 priv_set_len = sizeof(priv_set);
4253 granted = 0xdeadbeef;
4254 status = 0xdeadbeef;
4255 SetLastError(0xdeadbeef);
4256 ret = AccessCheck(sd, token, ACCESS_SYSTEM_SECURITY, mapping, &priv_set, &priv_set_len, &granted, &status);
4258 ok(ret, "AccessCheck error %d\n", GetLastError());
4259 ok(status == 0, "expected 0, got %d\n", status);
4260 ok(granted == 0, "expected 0, got %#x\n", granted);
4262 priv_set_len = sizeof(priv_set);
4263 granted = 0xdeadbeef;
4264 status = 0xdeadbeef;
4265 SetLastError(0xdeadbeef);
4266 ret = AccessCheck(sd, token, mapping->GenericRead, mapping, &priv_set, &priv_set_len, &granted, &status);
4268 ok(ret, "AccessCheck error %d\n", GetLastError());
4269 ok(status == 1, "expected 1, got %d\n", status);
4270 ok(granted == mapping->GenericRead, "expected read access %#x, got %#x\n", mapping->GenericRead, granted);
4272 priv_set_len = sizeof(priv_set);
4273 granted = 0xdeadbeef;
4274 status = 0xdeadbeef;
4275 SetLastError(0xdeadbeef);
4276 ret = AccessCheck(sd, token, mapping->GenericWrite, mapping, &priv_set, &priv_set_len, &granted, &status);
4278 ok(ret, "AccessCheck error %d\n", GetLastError());
4279 ok(status == 1, "expected 1, got %d\n", status);
4280 ok(granted == mapping->GenericWrite, "expected write access %#x, got %#x\n", mapping->GenericWrite, granted);
4282 priv_set_len = sizeof(priv_set);
4283 granted = 0xdeadbeef;
4284 status = 0xdeadbeef;
4285 SetLastError(0xdeadbeef);
4286 ret = AccessCheck(sd, token, mapping->GenericExecute, mapping, &priv_set, &priv_set_len, &granted, &status);
4288 ok(ret, "AccessCheck error %d\n", GetLastError());
4289 ok(status == 1, "expected 1, got %d\n", status);
4290 ok(granted == mapping->GenericExecute, "expected execute access %#x, got %#x\n", mapping->GenericExecute, granted);
4292 HeapFree(GetProcessHeap(), 0, sd);
4295 static void test_mutex_security(HANDLE token)
4298 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE | SYNCHRONIZE,
4299 STANDARD_RIGHTS_WRITE | MUTEX_MODIFY_STATE | SYNCHRONIZE,
4300 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
4301 STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS };
4303 SetLastError(0xdeadbeef);
4304 mutex = OpenMutex(0, FALSE, "WineTestMutex");
4305 ok(!mutex, "mutex should not exist\n");
4306 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
4308 SetLastError(0xdeadbeef);
4309 mutex = CreateMutex(NULL, FALSE, "WineTestMutex");
4310 ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
4312 test_default_handle_security(token, mutex, &mapping);
4314 CloseHandle (mutex);
4317 static void test_event_security(HANDLE token)
4320 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | EVENT_QUERY_STATE | SYNCHRONIZE,
4321 STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE | SYNCHRONIZE,
4322 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
4323 STANDARD_RIGHTS_ALL | EVENT_ALL_ACCESS };
4325 SetLastError(0xdeadbeef);
4326 event = OpenEvent(0, FALSE, "WineTestEvent");
4327 ok(!event, "event should not exist\n");
4328 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
4330 SetLastError(0xdeadbeef);
4331 event = CreateEvent(NULL, FALSE, FALSE, "WineTestEvent");
4332 ok(event != 0, "CreateEvent error %d\n", GetLastError());
4334 test_default_handle_security(token, event, &mapping);
4339 #define WINE_TEST_PIPE "\\\\.\\pipe\\WineTestPipe"
4340 static void test_named_pipe_security(HANDLE token)
4343 GENERIC_MAPPING mapping = { FILE_GENERIC_READ,
4345 FILE_GENERIC_EXECUTE,
4346 STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS };
4348 SetLastError(0xdeadbeef);
4349 pipe = CreateNamedPipe(WINE_TEST_PIPE, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
4350 PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES,
4351 0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL);
4352 ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe error %d\n", GetLastError());
4354 test_default_handle_security(token, pipe, &mapping);
4356 SetLastError(0xdeadbeef);
4357 file = CreateFile(WINE_TEST_PIPE, FILE_ALL_ACCESS, 0, NULL, OPEN_EXISTING, 0, 0);
4358 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4363 SetLastError(0xdeadbeef);
4364 file = CreateFile("\\\\.\\pipe\\", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
4365 ok(file != INVALID_HANDLE_VALUE || broken(file == INVALID_HANDLE_VALUE) /* before Vista */, "CreateFile error %d\n", GetLastError());
4369 static BOOL validate_impersonation_token(HANDLE token, DWORD *token_type)
4373 SECURITY_IMPERSONATION_LEVEL sil;
4377 SetLastError(0xdeadbeef);
4378 ret = GetTokenInformation(token, TokenType, &type, sizeof(type), &needed);
4379 ok(ret, "GetTokenInformation error %d\n", GetLastError());
4380 ok(needed == sizeof(type), "GetTokenInformation should return required buffer length\n");
4381 ok(type == TokenPrimary || type == TokenImpersonation, "expected TokenPrimary or TokenImpersonation, got %d\n", type);
4384 if (type != TokenImpersonation) return FALSE;
4387 SetLastError(0xdeadbeef);
4388 ret = GetTokenInformation(token, TokenImpersonationLevel, &sil, sizeof(sil), &needed);
4389 ok(ret, "GetTokenInformation error %d\n", GetLastError());
4390 ok(needed == sizeof(sil), "GetTokenInformation should return required buffer length\n");
4391 ok(sil == SecurityImpersonation, "expected SecurityImpersonation, got %d\n", sil);
4393 needed = 0xdeadbeef;
4394 SetLastError(0xdeadbeef);
4395 ret = GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &needed);
4396 ok(!ret, "GetTokenInformation should fail\n");
4397 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4398 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
4399 ok(needed > sizeof(TOKEN_DEFAULT_DACL), "GetTokenInformation returned empty default DACL\n");
4401 needed = 0xdeadbeef;
4402 SetLastError(0xdeadbeef);
4403 ret = GetTokenInformation(token, TokenOwner, NULL, 0, &needed);
4404 ok(!ret, "GetTokenInformation should fail\n");
4405 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4406 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
4407 ok(needed > sizeof(TOKEN_OWNER), "GetTokenInformation returned empty token owner\n");
4409 needed = 0xdeadbeef;
4410 SetLastError(0xdeadbeef);
4411 ret = GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &needed);
4412 ok(!ret, "GetTokenInformation should fail\n");
4413 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4414 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
4415 ok(needed > sizeof(TOKEN_PRIMARY_GROUP), "GetTokenInformation returned empty token primary group\n");
4420 static void test_kernel_objects_security(void)
4422 HANDLE token, process_token;
4423 DWORD ret, token_type;
4425 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process_token);
4426 ok(ret, "OpenProcessToken error %d\n", GetLastError());
4428 ret = validate_impersonation_token(process_token, &token_type);
4429 ok(token_type == TokenPrimary, "expected TokenPrimary, got %d\n", token_type);
4430 ok(!ret, "access token should not be an impersonation token\n");
4432 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
4433 ok(ret, "DuplicateToken error %d\n", GetLastError());
4435 ret = validate_impersonation_token(token, &token_type);
4436 ok(ret, "access token should be a valid impersonation token\n");
4437 ok(token_type == TokenImpersonation, "expected TokenImpersonation, got %d\n", token_type);
4439 test_mutex_security(token);
4440 test_event_security(token);
4441 test_named_pipe_security(token);
4442 /* FIXME: test other kernel object types */
4444 CloseHandle(process_token);
4448 static void test_TokenIntegrityLevel(void)
4450 TOKEN_MANDATORY_LABEL *tml;
4451 BYTE buffer[64]; /* using max. 28 byte in win7 x64 */
4455 char *sidname = NULL;
4456 static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
4457 {SECURITY_MANDATORY_HIGH_RID}};
4458 static SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
4459 {SECURITY_MANDATORY_MEDIUM_RID}};
4461 SetLastError(0xdeadbeef);
4462 res = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
4463 ok(res, "got %d with %d (expected TRUE)\n", res, GetLastError());
4465 SetLastError(0xdeadbeef);
4466 res = GetTokenInformation(token, TokenIntegrityLevel, buffer, sizeof(buffer), &size);
4468 /* not supported before Vista */
4469 if (!res && ((GetLastError() == ERROR_INVALID_PARAMETER) || GetLastError() == ERROR_INVALID_FUNCTION))
4471 win_skip("TokenIntegrityLevel not supported\n");
4476 ok(res, "got %u with %u (expected TRUE)\n", res, GetLastError());
4483 tml = (TOKEN_MANDATORY_LABEL*) buffer;
4484 ok(tml->Label.Attributes == (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED),
4485 "got 0x%x (expected 0x%x)\n", tml->Label.Attributes, (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED));
4487 SetLastError(0xdeadbeef);
4488 res = pConvertSidToStringSidA(tml->Label.Sid, &sidname);
4489 ok(res, "got %u and %u\n", res, GetLastError());
4491 ok(EqualSid(tml->Label.Sid, &medium_level) || EqualSid(tml->Label.Sid, &high_level),
4492 "got %s (expected 'S-1-16-8192' or 'S-1-16-12288')\n", sidname);
4498 START_TEST(security)
4505 test_process_security_child();
4508 test_kernel_objects_security();
4512 test_CreateWellKnownSid();
4513 test_FileSecurity();
4516 test_LookupAccountSid();
4517 test_LookupAccountName();
4518 test_security_descriptor();
4519 test_process_security();
4520 test_impersonation_level();
4521 test_SetEntriesInAclW();
4522 test_SetEntriesInAclA();
4523 test_GetNamedSecurityInfoA();
4524 test_ConvertStringSecurityDescriptor();
4525 test_ConvertSecurityDescriptorToString();
4526 test_PrivateObjectSecurity();
4528 test_GetSecurityInfo();
4529 test_GetSidSubAuthority();
4530 test_CheckTokenMembership();
4532 test_GetUserNameA();
4533 test_GetUserNameW();
4534 test_CreateRestrictedToken();
4535 test_TokenIntegrityLevel();