advapi32/tests: Add tests for creating directories with specific security attributes.
[wine/multimedia.git] / dlls / advapi32 / tests / security.c
blob4de623dfc78e3b455f8066659c15a25976d55c15
1 /*
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
22 #include <stdarg.h>
23 #include <stdio.h>
25 #include "ntstatus.h"
26 #define WIN32_NO_STATUS
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "aclapi.h"
31 #include "winnt.h"
32 #include "sddl.h"
33 #include "ntsecapi.h"
34 #include "lmcons.h"
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
43 #endif
45 /* copied from Wine winternl.h - not included in the Windows SDK */
46 typedef enum _OBJECT_INFORMATION_CLASS {
47 ObjectBasicInformation,
48 ObjectNameInformation,
49 ObjectTypeInformation,
50 ObjectAllInformation,
51 ObjectDataInformation
52 } OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;
54 typedef struct _OBJECT_BASIC_INFORMATION {
55 ULONG Attributes;
56 ACCESS_MASK GrantedAccess;
57 ULONG HandleCount;
58 ULONG PointerCount;
59 ULONG PagedPoolUsage;
60 ULONG NonPagedPoolUsage;
61 ULONG Reserved[3];
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,
78 LPSTR ObjectTypeName,
79 LPSTR InheritedObjectTypeName,
80 LPSTR Name );
81 static VOID (WINAPI *pBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
82 POBJECTS_AND_SID pObjSid,
83 GUID* pObjectGuid,
84 GUID* pInheritedObjectGuid,
85 PSID pSid );
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)(LPSTR, 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*);
134 static HMODULE hmod;
135 static int myARGC;
136 static char** myARGV;
138 struct strsid_entry
140 const char *str;
141 DWORD flags;
143 #define STRSID_OK 0
144 #define STRSID_OPT 1
146 struct sidRef
148 SID_IDENTIFIER_AUTHORITY auth;
149 const char *refStr;
152 static void init(void)
154 HMODULE hntdll;
156 hntdll = GetModuleHandleA("ntdll.dll");
157 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
158 pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
160 hmod = GetModuleHandleA("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";
217 unsigned int i;
218 PSID psid = NULL;
219 SID *pisid;
220 BOOL r;
221 LPSTR str = NULL;
223 if( !pConvertSidToStringSidA || !pConvertStringSidToSidA )
225 win_skip("ConvertSidToStringSidA or ConvertStringSidToSidA not available\n");
226 return;
229 r = pConvertStringSidToSidA( NULL, NULL );
230 ok( !r, "expected failure with NULL parameters\n" );
231 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
232 return;
233 ok( GetLastError() == ERROR_INVALID_PARAMETER,
234 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
235 GetLastError() );
237 r = pConvertStringSidToSidA( refs[0].refStr, NULL );
238 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
239 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
240 GetLastError() );
242 r = pConvertStringSidToSidA( NULL, &str );
243 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
244 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
245 GetLastError() );
247 r = pConvertStringSidToSidA( noSubAuthStr, &psid );
248 ok( !r,
249 "expected failure with no sub authorities\n" );
250 ok( GetLastError() == ERROR_INVALID_SID,
251 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
252 GetLastError() );
254 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
255 pisid = psid;
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]);
259 LocalFree(str);
260 LocalFree(psid);
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,
265 &psid );
266 ok( r, "failed to allocate sid\n" );
267 r = pConvertSidToStringSidA( psid, &str );
268 ok( r, "failed to convert sid\n" );
269 if (r)
271 ok( !strcmp( str, refs[i].refStr ),
272 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
273 LocalFree( str );
275 if( psid )
276 FreeSid( psid );
278 r = pConvertStringSidToSidA( refs[i].refStr, &psid );
279 ok( r, "failed to parse sid string\n" );
280 pisid = psid;
281 ok( pisid &&
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",
286 refs[i].refStr,
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] ) ) );
296 if( psid )
297 LocalFree( psid );
300 /* string constant format not supported before XP */
301 r = pConvertStringSidToSidA(strsid_table[0].str, &psid);
302 if(!r)
304 win_skip("String constant format not supported\n");
305 return;
307 LocalFree(psid);
309 for(i = 0; i < sizeof(strsid_table) / sizeof(strsid_table[0]); i++)
311 char *temp;
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());
321 if (r)
323 if ((winetest_debug > 1) && (pConvertSidToStringSidA(psid, &temp)))
325 trace(" %s: %s\n", strsid_table[i].str, temp);
326 LocalFree(temp);
328 LocalFree(psid);
330 else
332 if (GetLastError() != ERROR_INVALID_SID)
333 trace(" %s: couldn't be converted, returned %d\n", strsid_table[i].str, GetLastError());
334 else
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}};
344 GUID ZeroGuid;
345 OBJECTS_AND_NAME_A oan;
346 OBJECTS_AND_SID oas;
347 TRUSTEEA trustee;
348 PSID psid;
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 ||
363 !pGetTrusteeNameA )
364 return;
366 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
368 trace( "failed to init SID\n" );
369 return;
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");
420 FreeSid( psid );
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 == (LPSTR)&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 == (LPSTR)&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);
526 LUID luid1, luid2;
527 BOOL ret;
529 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
530 if (!pAllocateLocallyUniqueId) return;
532 ret = pAllocateLocallyUniqueId(&luid1);
533 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
534 return;
536 ok(ret,
537 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
538 ret = pAllocateLocallyUniqueId(&luid2);
539 ok( ret,
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",
548 GetLastError());
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 };
557 LONG i;
558 BOOL ret;
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)
566 return;
568 /* check with a short buffer */
569 cchName = 0;
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",
574 GetLastError());
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++)
589 luid.LowPart = 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",
601 GetLastError());
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",
609 GetLastError());
612 struct NameToLUID
614 const char *name;
615 DWORD lowPart;
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);
652 unsigned int i;
653 LUID luid;
654 BOOL ret;
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)
661 return;
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",
668 GetLastError());
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",
673 GetLastError());
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",
678 GetLastError());
679 /* check case insensitive */
680 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
681 ok( ret,
682 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
683 GetLastError());
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",
693 privs[i].name);
698 static void test_luid(void)
700 test_allocateLuid();
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];
710 HANDLE fh, token;
711 DWORD sdSize, retSize, rc, granted, priv_set_len;
712 PRIVILEGE_SET priv_set;
713 BOOL status;
714 BYTE *sd;
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");
722 return;
725 if (!pSetFileSecurityA) {
726 win_skip ("SetFileSecurity is not available\n");
727 return;
730 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
731 win_skip ("GetTempPathA failed\n");
732 return;
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());
747 CloseHandle (fh);
749 /* For the temporary file ... */
751 /* Get size needed */
752 retSize = 0;
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");
757 goto cleanup;
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);
765 sdSize = retSize;
766 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
768 /* Get security descriptor for real */
769 retSize = -1;
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 */
789 retSize = 0;
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);
798 sdSize = retSize;
799 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
801 /* Get security descriptor for real */
802 retSize = -1;
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);
818 /* Old test */
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());
826 cleanup:
827 /* Remove temporary file and directory */
828 DeleteFileA(file);
829 RemoveDirectoryA(path);
831 /* Test file access permissions for a file with FILE_ATTRIBUTE_ARCHIVE */
832 SetLastError(0xdeadbeef);
833 rc = GetTempPathA(sizeof(wintmpdir), wintmpdir);
834 ok(rc, "GetTempPath error %d\n", GetLastError());
836 SetLastError(0xdeadbeef);
837 rc = GetTempFileNameA(wintmpdir, "tmp", 0, file);
838 ok(rc, "GetTempFileName error %d\n", GetLastError());
840 rc = GetFileAttributesA(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 = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
846 NULL, 0, &sdSize);
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 = GetFileSecurityA(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);
874 rc = RevertToSelf();
875 ok(rc, "RevertToSelf error %d\n", GetLastError());
877 priv_set_len = sizeof(priv_set);
878 granted = 0xdeadbeef;
879 status = 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;
887 status = 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;
895 status = 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;
903 status = 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;
911 status = 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;
919 status = 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;
927 status = 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 = CreateFileA(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);
949 CloseHandle(fh);
951 rc = GetFileAttributesA(file);
952 rc &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
953 todo_wine
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 = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
959 ok(rc, "SetFileAttributes error %d\n", GetLastError());
960 SetLastError(0xdeadbeef);
961 rc = DeleteFileA(file);
962 ok(rc, "DeleteFile error %d\n", GetLastError());
964 SetLastError(0xdeadbeef);
965 fh = CreateFileA(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);
973 CloseHandle(fh);
975 rc = GetFileAttributesA(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 = GetFileSecurityA(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;
989 status = 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;
997 status = 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());
1001 todo_wine {
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());
1018 todo_wine {
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());
1027 todo_wine {
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());
1036 todo_wine {
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());
1045 todo_wine {
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 = DeleteFileA(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 = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
1055 ok(rc, "SetFileAttributes error %d\n", GetLastError());
1056 SetLastError(0xdeadbeef);
1057 rc = DeleteFileA(file);
1058 ok(rc, "DeleteFile error %d\n", GetLastError());
1060 CloseHandle(token);
1061 HeapFree(GetProcessHeap(), 0, sd);
1064 static void test_AccessCheck(void)
1066 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
1067 PACL Acl = 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 };
1072 ACCESS_MASK Access;
1073 BOOL AccessStatus;
1074 HANDLE Token;
1075 HANDLE ProcessToken;
1076 BOOL ret;
1077 DWORD PrivSetLen;
1078 PRIVILEGE_SET *PrivSet;
1079 BOOL res;
1080 HMODULE NtDllModule;
1081 BOOLEAN Enabled;
1082 DWORD err;
1083 NTSTATUS ntret, ntAccessStatus;
1085 NtDllModule = GetModuleHandleA("ntdll.dll");
1086 if (!NtDllModule)
1088 skip("not running on NT, skipping test\n");
1089 return;
1091 pRtlAdjustPrivilege = (void *)GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
1092 if (!pRtlAdjustPrivilege)
1094 win_skip("missing RtlAdjustPrivilege, skipping test\n");
1095 return;
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);
1104 return;
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",
1209 GetLastError());
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");
1222 if(pNtAccessCheck)
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");
1263 else
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",
1275 GetLastError());
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());
1294 /* sd with dacl */
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",
1301 GetLastError());
1303 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1304 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1305 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1306 ok(AccessStatus,
1307 "AccessCheck failed to grant any access with error %d\n",
1308 GetLastError());
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);
1322 SetLastError(0);
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",
1328 GetLastError());
1330 ret = ImpersonateLoggedOnUser(Token);
1331 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1332 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
1333 if (!ret)
1335 SetLastError(0);
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",
1341 GetLastError());
1342 ok(Access == ACCESS_SYSTEM_SECURITY,
1343 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1344 Access);
1346 else
1347 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1348 ret);
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
1357 * the next ones.
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());
1364 else
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);
1375 CloseHandle(Token);
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);
1387 CloseHandle(Token);
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);
1398 if (EveryoneSid)
1399 FreeSid(EveryoneSid);
1400 if (AdminSid)
1401 FreeSid(AdminSid);
1402 if (UsersSid)
1403 FreeSid(UsersSid);
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;
1413 DWORD Size, Size2;
1414 TOKEN_PRIVILEGES *Privileges;
1415 TOKEN_GROUPS *Groups;
1416 TOKEN_USER *User;
1417 TOKEN_DEFAULT_DACL *Dacl;
1418 BOOL ret;
1419 DWORD i, GLE;
1420 LPSTR SidString;
1421 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1422 ACL *acl;
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");
1430 return;
1432 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1433 if (ret)
1435 DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1436 Size = sizeof(buf);
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);
1443 CloseHandle(Token);
1446 if(!pConvertSidToStringSidA)
1448 win_skip("ConvertSidToStringSidA is not available\n");
1449 return;
1452 SetLastError(0xdeadbeef);
1453 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1454 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1456 /* groups */
1457 /* insufficient buffer length */
1458 SetLastError(0xdeadbeef);
1459 Size2 = 0;
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());
1464 Size2 -= 1;
1465 Groups = HeapAlloc(GetProcessHeap(), 0, Size2);
1466 memset(Groups, 0xcc, Size2);
1467 Size = 0;
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());
1472 if(!ret)
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",
1488 GetLastError());
1489 trace("TokenGroups:\n");
1490 for (i = 0; i < Groups->GroupCount; i++)
1492 DWORD NameLength = 255;
1493 CHAR Name[255];
1494 DWORD DomainLength = 255;
1495 CHAR Domain[255];
1496 SID_NAME_USE SidNameUse;
1497 Name[0] = '\0';
1498 Domain[0] = '\0';
1499 ret = LookupAccountSidA(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1500 if (ret)
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);
1510 /* user */
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);
1516 ok(ret,
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);
1524 /* privileges */
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);
1530 ok(ret,
1531 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1532 trace("TokenPrivileges:\n");
1533 for (i = 0; i < Privileges->PrivilegeCount; i++)
1535 CHAR Name[256];
1536 DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
1537 LookupPrivilegeNameA(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);
1552 /* default dacl */
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");
1579 Size2 = 0;
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());
1594 } else
1595 win_skip("TOKEN_DEFAULT_DACL size too small on WoW64\n");
1597 HeapFree(GetProcessHeap(), 0, Dacl);
1598 CloseHandle(Token);
1601 typedef union _MAX_SID
1603 SID sid;
1604 char max[SECURITY_MAX_SID_SIZE];
1605 } MAX_SID;
1607 static void test_sid_str(PSID * sid)
1609 char *str_sid;
1610 BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
1611 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
1612 if (ret)
1614 char account[MAX_PATH], domain[MAX_PATH];
1615 SID_NAME_USE use;
1616 DWORD acc_size = MAX_PATH;
1617 DWORD dom_size = MAX_PATH;
1618 ret = LookupAccountSidA (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());
1621 if (ret)
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);
1625 LocalFree(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;
1671 DWORD size, error;
1672 BOOL ret;
1673 unsigned int i;
1675 if (!pCreateWellKnownSid)
1677 win_skip("CreateWellKnownSid not available\n");
1678 return;
1681 size = 0;
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];
1707 LPSTR str;
1708 DWORD cb;
1710 if (value->sid_string == NULL)
1711 continue;
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);
1720 break;
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);
1731 LocalFree(str);
1733 if (value->without_domain)
1735 char buf2[SECURITY_MAX_SID_SIZE];
1736 cb = sizeof(buf2);
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);
1743 FreeSid(domainsid);
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;
1756 SID_NAME_USE use;
1757 BOOL ret;
1758 DWORD error, size, cbti = 0;
1759 MAX_SID max_sid;
1760 CHAR *str_sidA;
1761 int i;
1762 HANDLE hToken;
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))
1774 return;
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 */
1794 acc_sizeA = 1;
1795 dom_sizeA = MAX_PATH;
1796 accountA[0] = 0;
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 */
1803 acc_sizeA = 0;
1804 dom_sizeA = MAX_PATH;
1805 accountA[0] = 0;
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 */
1813 acc_sizeA = 0;
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 */
1822 dom_sizeA = 1;
1823 acc_sizeA = MAX_PATH;
1824 accountA[0] = 0;
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 */
1831 dom_sizeA = 0;
1832 acc_sizeA = MAX_PATH;
1833 accountA[0] = 0;
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 */
1841 dom_sizeA = 0;
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 */
1865 acc_sizeW = 1;
1866 dom_sizeW = MAX_PATH;
1867 accountW[0] = 0;
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 */
1874 acc_sizeW = 0;
1875 dom_sizeW = MAX_PATH;
1876 accountW[0] = 0;
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 */
1884 acc_sizeW = 0;
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 */
1893 dom_sizeW = 1;
1894 acc_sizeW = MAX_PATH;
1895 accountW[0] = 0;
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 */
1902 dom_sizeW = 0;
1903 acc_sizeW = MAX_PATH;
1904 accountW[0] = 0;
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 */
1912 dom_sizeW = 0;
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);
1930 FreeSid(pUsersSid);
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);
1968 else
1970 if (GetLastError() != ERROR_INVALID_PARAMETER)
1971 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1972 else
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)
1984 NTSTATUS status;
1985 LSA_HANDLE handle;
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;
2059 SID_NAME_USE use;
2061 *user = account;
2062 *dom = domain;
2064 size = dom_size = UNLEN + 1;
2065 account[0] = '\0';
2066 domain[0] = '\0';
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];
2076 DWORD cb;
2078 DWORD sid_size, domain_size;
2079 SID_NAME_USE sid_use;
2080 LPSTR domain, account, sid_domain, wk_domain, wk_account;
2081 PSID psid;
2082 BOOL ret ,ret2;
2084 sid_size = 0;
2085 domain_size = 0;
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);
2092 if (!result)
2094 ok(!ret, " %s Should have failed to lookup account name\n",name);
2095 goto cleanup;
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);
2103 goto cleanup;
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);
2110 goto cleanup;
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(!lstrcmpA(account, wk_account), "Expected %s , got %s\n", account, wk_account);
2121 ok(!lstrcmpA(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
2122 ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
2124 cleanup:
2125 FreeSid(domainsid);
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;
2138 PSID psid;
2139 BOOL ret;
2141 /* native crashes if (assuming all other parameters correct):
2142 * - peUse is NULL
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());
2153 /* get sizes */
2154 sid_size = 0;
2155 domain_size = 0;
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");
2162 return;
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(!lstrcmpA(account, user_name), "Expected %s, got %s\n", user_name, account);
2183 ok(!lstrcmpA(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", lstrlenA(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");
2194 else
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(!lstrcmpA(account, "Everyone"), "Expected Everyone, got %s\n", account);
2201 ok(!lstrcmpA(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", lstrlenA(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);
2210 sid_size = 0;
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);
2220 domain_size--;
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);
2230 domain_size = 0;
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 */
2242 sid_size = 0;
2243 domain_size = 0;
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");
2249 else
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(!lstrcmpA(account, domain),
2267 "Got %s for account and %s for domain, these should be the same\n",
2268 account, domain);
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);
2277 sid_size = 0;
2278 domain_size = 0;
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);
2289 sid_size = 0;
2290 domain_size = 0;
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);
2301 sid_size = 0;
2302 domain_size = 0;
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");
2325 return;
2328 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2330 skip("Non-English locale (skipping well known name creation tests)\n");
2331 return;
2334 check_wellknown_name("LocalService", WinLocalServiceSid);
2335 check_wellknown_name("Local Service", WinLocalServiceSid);
2336 /* 2 spaces */
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;
2366 char buf[8192];
2367 DWORD size;
2368 BOOL isDefault, isPresent, ret;
2369 PACL pacl;
2370 PSID psid;
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");
2377 return;
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);
2386 size = 5;
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");
2390 if (size <= 8192)
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;
2416 NTSTATUS status;
2418 if (!pNtQueryObject)
2420 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
2421 return;
2424 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
2425 sizeof(obj_info), NULL );
2426 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2427 if (alt)
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);
2431 else
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) \
2437 do{ \
2438 BOOL res_; \
2439 DWORD err; \
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); \
2445 else \
2446 ok(!res_ && err == e, "SetKernelObjectSecurity should have failed " \
2447 "with %s, instead of %d\n", #e, err); \
2448 }while(0)
2450 static void test_process_security(void)
2452 BOOL res;
2453 PTOKEN_OWNER owner;
2454 PTOKEN_PRIMARY_GROUP group;
2455 PSID AdminSid = NULL, UsersSid = NULL;
2456 PACL Acl = 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;
2463 DWORD size;
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);
2471 return;
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());
2478 if (!res)
2480 HeapFree(GetProcessHeap(), 0, Acl);
2481 return;
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 );
2505 if (!res)
2507 HeapFree(GetProcessHeap(), 0, group);
2508 HeapFree(GetProcessHeap(), 0, owner);
2509 HeapFree(GetProcessHeap(), 0, Acl);
2510 return;
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 = CreateEventA( 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;
2577 BOOL ret;
2578 DWORD err;
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();
2595 todo_wine
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() );
2603 todo_wine
2604 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
2605 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
2606 todo_wine
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;
2635 HANDLE Token2;
2636 DWORD Size;
2637 TOKEN_PRIVILEGES *Privileges;
2638 TOKEN_USER *User;
2639 PRIVILEGE_SET *PrivilegeSet;
2640 BOOL AccessGranted;
2641 BOOL ret;
2642 HKEY hkey;
2643 DWORD error;
2645 pDuplicateTokenEx = (void *)GetProcAddress(hmod, "DuplicateTokenEx");
2646 if( !pDuplicateTokenEx ) {
2647 win_skip("DuplicateTokenEx is not available\n");
2648 return;
2650 SetLastError(0xdeadbeef);
2651 ret = ImpersonateSelf(SecurityAnonymous);
2652 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2654 win_skip("ImpersonateSelf is not implemented\n");
2655 return;
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 */
2663 todo_wine {
2664 error = RegOpenKeyExA(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);
2668 RevertToSelf();
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);
2709 CloseHandle(Token);
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 = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2718 todo_wine {
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());
2724 CloseHandle(Token);
2725 RevertToSelf();
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 = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2732 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
2733 RegCloseKey(hkey);
2734 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2735 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
2736 RevertToSelf();
2738 CloseHandle(Token);
2739 CloseHandle(ProcessToken);
2741 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
2744 static void test_SetEntriesInAclW(void)
2746 DWORD res;
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");
2758 return;
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");
2766 return;
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);
2772 LocalFree(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);
2780 return;
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");
2805 LocalFree(NewAcl);
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");
2813 LocalFree(NewAcl);
2815 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2817 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2819 else
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");
2826 LocalFree(NewAcl);
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");
2852 LocalFree(NewAcl);
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");
2860 LocalFree(NewAcl);
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");
2868 LocalFree(NewAcl);
2870 FreeSid(UsersSid);
2871 FreeSid(EveryoneSid);
2872 HeapFree(GetProcessHeap(), 0, OldAcl);
2875 static void test_SetEntriesInAclA(void)
2877 DWORD res;
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_ACCESSA 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");
2889 return;
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");
2897 return;
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);
2903 LocalFree(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);
2911 return;
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");
2936 LocalFree(NewAcl);
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");
2944 LocalFree(NewAcl);
2946 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2948 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2950 else
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");
2957 LocalFree(NewAcl);
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");
2983 LocalFree(NewAcl);
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");
2991 LocalFree(NewAcl);
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");
2999 LocalFree(NewAcl);
3001 FreeSid(UsersSid);
3002 FreeSid(EveryoneSid);
3003 HeapFree(GetProcessHeap(), 0, OldAcl);
3006 static void test_CreateDirectoryA(void)
3008 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
3009 DWORD sid_size = sizeof(admin_ptr), user_size;
3010 PSID admin_sid = (PSID) admin_ptr, user_sid;
3011 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3012 PSECURITY_DESCRIPTOR pSD = &sd;
3013 ACL_SIZE_INFORMATION acl_size;
3014 ACCESS_ALLOWED_ACE *ace;
3015 SECURITY_ATTRIBUTES sa;
3016 char tmpdir[MAX_PATH];
3017 struct _SID *owner;
3018 BOOL bret = TRUE;
3019 HANDLE token;
3020 DWORD error;
3021 PACL pDacl;
3023 if (!pGetNamedSecurityInfoA || !pCreateWellKnownSid)
3025 win_skip("Required functions are not available\n");
3026 return;
3029 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3031 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3032 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3034 if (!bret)
3036 win_skip("Failed to get current user token\n");
3037 return;
3039 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3040 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3041 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3042 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3043 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3044 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3045 CloseHandle( token );
3046 user_sid = ((TOKEN_USER *)user)->User.Sid;
3048 sa.nLength = sizeof(sa);
3049 sa.lpSecurityDescriptor = pSD;
3050 sa.bInheritHandle = TRUE;
3051 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3052 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3053 pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
3054 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
3055 ok(bret, "Failed to initialize ACL.\n");
3056 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3057 GENERIC_ALL, user_sid);
3058 ok(bret, "Failed to add Current User to ACL.\n");
3059 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3060 GENERIC_ALL, admin_sid);
3061 ok(bret, "Failed to add Administrator Group to ACL.\n");
3062 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3063 ok(bret, "Failed to add ACL to security desciptor.\n");
3065 GetTempPathA(MAX_PATH, tmpdir);
3066 lstrcatA(tmpdir, "Please Remove Me");
3067 bret = CreateDirectoryA(tmpdir, &sa);
3068 ok(bret == TRUE, "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
3069 HeapFree(GetProcessHeap(), 0, pDacl);
3071 SetLastError(0xdeadbeef);
3072 error = pGetNamedSecurityInfoA(tmpdir, SE_FILE_OBJECT,
3073 OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, (PSID*)&owner,
3074 NULL, &pDacl, NULL, &pSD);
3075 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3077 win_skip("GetNamedSecurityInfoA is not implemented\n");
3078 goto done;
3080 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3082 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3083 ok(bret, "GetAclInformation failed\n");
3084 todo_wine ok(acl_size.AceCount == 2,
3085 "GetAclInformation returned unexpected entry count (%d != 2).\n",
3086 acl_size.AceCount);
3087 if (acl_size.AceCount > 0)
3089 bret = pGetAce(pDacl, 0, (VOID **)&ace);
3090 ok(bret, "Failed to get Current User ACE.\n");
3091 bret = EqualSid(&ace->SidStart, user_sid);
3092 todo_wine ok(bret, "Current User ACE != Current User SID.\n");
3093 todo_wine ok(((ACE_HEADER *)ace)->AceFlags == (OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE),
3094 "Current User ACE has unexpected flags (0x%x != 0x03)\n",
3095 ((ACE_HEADER *)ace)->AceFlags);
3096 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3097 ace->Mask);
3099 if (acl_size.AceCount > 1)
3101 bret = pGetAce(pDacl, 1, (VOID **)&ace);
3102 ok(bret, "Failed to get Administators Group ACE.\n");
3103 bret = EqualSid(&ace->SidStart, admin_sid);
3104 todo_wine ok(bret, "Administators Group ACE != Administators Group SID.\n");
3105 todo_wine ok(((ACE_HEADER *)ace)->AceFlags == (OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE),
3106 "Administators Group ACE has unexpected flags (0x%x != 0x03)\n",
3107 ((ACE_HEADER *)ace)->AceFlags);
3108 ok(ace->Mask == 0x1f01ff, "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3109 ace->Mask);
3112 done:
3113 HeapFree(GetProcessHeap(), 0, user);
3114 bret = RemoveDirectoryA(tmpdir);
3115 ok(bret == TRUE, "RemoveDirectoryA should always succeed\n");
3118 static void test_GetNamedSecurityInfoA(void)
3120 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
3121 char system_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
3122 char users_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
3123 PSID admin_sid = (PSID) admin_ptr, users_sid = (PSID) users_ptr;
3124 PSID system_sid = (PSID) system_ptr, user_sid;
3125 DWORD sid_size = sizeof(admin_ptr), user_size;
3126 char invalid_path[] = "/an invalid file path";
3127 int users_ace_id = -1, admins_ace_id = -1, i;
3128 char software_key[] = "MACHINE\\Software";
3129 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3130 SECURITY_DESCRIPTOR_CONTROL control;
3131 ACL_SIZE_INFORMATION acl_size;
3132 CHAR windows_dir[MAX_PATH];
3133 PSECURITY_DESCRIPTOR pSD;
3134 ACCESS_ALLOWED_ACE *ace;
3135 BOOL bret = TRUE, isNT4;
3136 char tmpfile[MAX_PATH];
3137 DWORD error, revision;
3138 BOOL owner_defaulted;
3139 BOOL group_defaulted;
3140 BOOL dacl_defaulted;
3141 HANDLE token, hTemp;
3142 PSID owner, group;
3143 BOOL dacl_present;
3144 PACL pDacl;
3145 BYTE flags;
3147 if (!pSetNamedSecurityInfoA || !pGetNamedSecurityInfoA || !pCreateWellKnownSid)
3149 win_skip("Required functions are not available\n");
3150 return;
3153 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3155 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3156 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3158 if (!bret)
3160 win_skip("Failed to get current user token\n");
3161 return;
3163 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3164 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3165 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3166 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3167 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3168 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3169 CloseHandle( token );
3170 user_sid = ((TOKEN_USER *)user)->User.Sid;
3172 bret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
3173 ok(bret, "GetWindowsDirectory failed with error %d\n", GetLastError());
3175 SetLastError(0xdeadbeef);
3176 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
3177 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
3178 NULL, NULL, NULL, NULL, &pSD);
3179 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3181 win_skip("GetNamedSecurityInfoA is not implemented\n");
3182 HeapFree(GetProcessHeap(), 0, user);
3183 return;
3185 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3187 bret = GetSecurityDescriptorControl(pSD, &control, &revision);
3188 ok(bret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
3189 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
3190 broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
3191 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
3192 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
3194 isNT4 = (control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT;
3196 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
3197 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3198 ok(owner != NULL, "owner should not be NULL\n");
3200 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
3201 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3202 ok(group != NULL, "group should not be NULL\n");
3203 LocalFree(pSD);
3206 /* NULL descriptor tests */
3207 if(isNT4)
3209 win_skip("NT4 does not support GetNamedSecutityInfo with a NULL descriptor\n");
3210 HeapFree(GetProcessHeap(), 0, user);
3211 return;
3214 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3215 NULL, NULL, NULL, NULL, NULL);
3216 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3218 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3219 NULL, NULL, &pDacl, NULL, NULL);
3220 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3221 ok(pDacl != NULL, "DACL should not be NULL\n");
3223 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,
3224 NULL, NULL, &pDacl, NULL, NULL);
3225 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3227 /* Test behavior of SetNamedSecurityInfo with an invalid path */
3228 SetLastError(0xdeadbeef);
3229 error = pSetNamedSecurityInfoA(invalid_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3230 NULL, NULL, NULL);
3231 ok(error == ERROR_FILE_NOT_FOUND, "Unexpected error returned: 0x%x\n", error);
3232 ok(GetLastError() == 0xdeadbeef, "Expected last error to remain unchanged.\n");
3234 /* Create security descriptor information and test that it comes back the same */
3235 pSD = &sd;
3236 pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
3237 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3238 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3239 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
3240 ok(bret, "Failed to initialize ACL.\n");
3241 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
3242 ok(bret, "Failed to add Current User to ACL.\n");
3243 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
3244 ok(bret, "Failed to add Administrator Group to ACL.\n");
3245 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3246 ok(bret, "Failed to add ACL to security desciptor.\n");
3247 GetTempFileNameA(".", "foo", 0, tmpfile);
3248 hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING,
3249 FILE_FLAG_DELETE_ON_CLOSE, NULL);
3250 SetLastError(0xdeadbeef);
3251 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3252 NULL, pDacl, NULL);
3253 HeapFree(GetProcessHeap(), 0, pDacl);
3254 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3256 win_skip("SetNamedSecurityInfoA is not implemented\n");
3257 HeapFree(GetProcessHeap(), 0, user);
3258 CloseHandle(hTemp);
3259 return;
3261 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
3262 SetLastError(0xdeadbeef);
3263 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3264 NULL, NULL, &pDacl, NULL, &pSD);
3265 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3267 win_skip("GetNamedSecurityInfoA is not implemented\n");
3268 HeapFree(GetProcessHeap(), 0, user);
3269 CloseHandle(hTemp);
3270 return;
3272 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3274 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3275 ok(bret, "GetAclInformation failed\n");
3276 if (acl_size.AceCount > 0)
3278 bret = pGetAce(pDacl, 0, (VOID **)&ace);
3279 ok(bret, "Failed to get Current User ACE.\n");
3280 bret = EqualSid(&ace->SidStart, user_sid);
3281 todo_wine ok(bret, "Current User ACE != Current User SID.\n");
3282 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3283 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3284 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3285 ace->Mask);
3287 if (acl_size.AceCount > 1)
3289 bret = pGetAce(pDacl, 1, (VOID **)&ace);
3290 ok(bret, "Failed to get Administators Group ACE.\n");
3291 bret = EqualSid(&ace->SidStart, admin_sid);
3292 todo_wine ok(bret || broken(!bret) /* win2k */,
3293 "Administators Group ACE != Administators Group SID.\n");
3294 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3295 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3296 ok(ace->Mask == 0x1f01ff || broken(ace->Mask == GENERIC_ALL) /* win2k */,
3297 "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n", ace->Mask);
3299 LocalFree(pSD);
3300 HeapFree(GetProcessHeap(), 0, user);
3301 CloseHandle(hTemp);
3303 /* Test querying the ownership of a built-in registry key */
3304 sid_size = sizeof(system_ptr);
3305 pCreateWellKnownSid(WinLocalSystemSid, NULL, system_sid, &sid_size);
3306 error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY,
3307 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
3308 NULL, NULL, NULL, NULL, &pSD);
3309 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3311 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
3312 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3313 ok(owner != NULL, "owner should not be NULL\n");
3314 ok(EqualSid(owner, admin_sid), "MACHINE\\Software owner SID != Administrators SID.\n");
3316 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
3317 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3318 ok(group != NULL, "group should not be NULL\n");
3319 ok(EqualSid(group, admin_sid) || broken(EqualSid(group, system_sid)) /* before Win7 */
3320 || broken(((SID*)group)->SubAuthority[0] == SECURITY_NT_NON_UNIQUE) /* Vista */,
3321 "MACHINE\\Software group SID != Local System SID.\n");
3322 LocalFree(pSD);
3324 /* Test querying the DACL of a built-in registry key */
3325 sid_size = sizeof(users_ptr);
3326 pCreateWellKnownSid(WinBuiltinUsersSid, NULL, users_sid, &sid_size);
3327 error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
3328 NULL, NULL, NULL, NULL, &pSD);
3329 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3331 bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
3332 ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
3333 ok(dacl_present, "DACL should be present\n");
3334 ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
3335 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3336 ok(bret, "GetAclInformation failed\n");
3337 ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
3338 for (i=0; i<acl_size.AceCount; i++)
3340 bret = pGetAce(pDacl, i, (VOID **)&ace);
3341 ok(bret, "Failed to get ACE %d.\n", i);
3342 bret = EqualSid(&ace->SidStart, users_sid);
3343 if (bret) users_ace_id = i;
3344 bret = EqualSid(&ace->SidStart, admin_sid);
3345 if (bret) admins_ace_id = i;
3347 ok(users_ace_id != -1 || broken(users_ace_id == -1) /* win2k */,
3348 "Bultin Users ACE not found.\n");
3349 if (users_ace_id != -1)
3351 bret = pGetAce(pDacl, users_ace_id, (VOID **)&ace);
3352 ok(bret, "Failed to get Builtin Users ACE.\n");
3353 flags = ((ACE_HEADER *)ace)->AceFlags;
3354 ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)
3355 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */,
3356 "Builtin Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
3357 INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
3358 ok(ace->Mask == GENERIC_READ, "Builtin Users ACE has unexpected mask (0x%x != 0x%x)\n",
3359 ace->Mask, GENERIC_READ);
3361 ok(admins_ace_id != -1, "Bultin Admins ACE not found.\n");
3362 if (admins_ace_id != -1)
3364 bret = pGetAce(pDacl, admins_ace_id, (VOID **)&ace);
3365 ok(bret, "Failed to get Builtin Admins ACE.\n");
3366 flags = ((ACE_HEADER *)ace)->AceFlags;
3367 ok(flags == 0x0
3368 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */,
3369 "Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
3370 ok(ace->Mask == KEY_ALL_ACCESS || broken(ace->Mask == GENERIC_ALL) /* w2k8 */,
3371 "Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, KEY_ALL_ACCESS);
3373 LocalFree(pSD);
3376 static void test_ConvertStringSecurityDescriptor(void)
3378 BOOL ret;
3379 PSECURITY_DESCRIPTOR pSD;
3380 static const WCHAR Blank[] = { 0 };
3381 unsigned int i;
3382 static const struct
3384 const char *sidstring;
3385 DWORD revision;
3386 BOOL ret;
3387 DWORD GLE;
3388 DWORD altGLE;
3389 } cssd[] =
3391 { "D:(A;;GA;;;WD)", 0xdeadbeef, FALSE, ERROR_UNKNOWN_REVISION },
3392 /* test ACE string type */
3393 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3394 { "D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3395 { "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
3396 /* test ACE string with spaces */
3397 { " D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3398 { "D: (D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3399 { "D:( D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3400 { "D:(D ;;GA;;;WD)", SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
3401 { "D:(D; ;GA;;;WD)", SDDL_REVISION_1, TRUE },
3402 { "D:(D;; GA;;;WD)", SDDL_REVISION_1, TRUE },
3403 { "D:(D;;GA ;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
3404 { "D:(D;;GA; ;;WD)", SDDL_REVISION_1, TRUE },
3405 { "D:(D;;GA;; ;WD)", SDDL_REVISION_1, TRUE },
3406 { "D:(D;;GA;;; WD)", SDDL_REVISION_1, TRUE },
3407 { "D:(D;;GA;;;WD )", SDDL_REVISION_1, TRUE },
3408 /* test ACE string access rights */
3409 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
3410 { "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, TRUE },
3411 { "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, TRUE },
3412 { "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, TRUE },
3413 { "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, TRUE },
3414 { "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, TRUE },
3415 { "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
3416 { "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
3417 /* test ACE string access right error case */
3418 { "D:(A;;ROB;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
3419 /* test behaviour with empty strings */
3420 { "", SDDL_REVISION_1, TRUE },
3421 /* test ACE string SID */
3422 { "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, TRUE },
3423 { "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
3426 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
3428 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3429 return;
3432 for (i = 0; i < sizeof(cssd)/sizeof(cssd[0]); i++)
3434 DWORD GLE;
3436 SetLastError(0xdeadbeef);
3437 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3438 cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
3439 GLE = GetLastError();
3440 ok(ret == cssd[i].ret, "(%02u) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
3441 if (!cssd[i].ret)
3442 ok(GLE == cssd[i].GLE ||
3443 (cssd[i].altGLE && GLE == cssd[i].altGLE),
3444 "(%02u) Unexpected last error %d\n", i, GLE);
3445 if (ret)
3446 LocalFree(pSD);
3449 /* test behaviour with NULL parameters */
3450 SetLastError(0xdeadbeef);
3451 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3452 NULL, 0xdeadbeef, &pSD, NULL);
3453 todo_wine
3454 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3455 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3456 GetLastError());
3458 SetLastError(0xdeadbeef);
3459 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
3460 NULL, 0xdeadbeef, &pSD, NULL);
3461 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3462 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3463 GetLastError());
3465 SetLastError(0xdeadbeef);
3466 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3467 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
3468 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3469 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3470 GetLastError());
3472 SetLastError(0xdeadbeef);
3473 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
3474 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
3475 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
3476 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
3477 GetLastError());
3479 /* test behaviour with empty strings */
3480 SetLastError(0xdeadbeef);
3481 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
3482 Blank, SDDL_REVISION_1, &pSD, NULL);
3483 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
3484 LocalFree(pSD);
3487 static void test_ConvertSecurityDescriptorToString(void)
3489 SECURITY_DESCRIPTOR desc;
3490 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
3491 LPSTR string;
3492 DWORD size;
3493 PSID psid, psid2;
3494 PACL pacl;
3495 char sid_buf[256];
3496 char acl_buf[8192];
3497 ULONG len;
3499 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
3501 win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
3502 return;
3504 if (!pCreateWellKnownSid)
3506 win_skip("CreateWellKnownSid is not available\n");
3507 return;
3510 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
3511 * don't replicate this feature so we only test len >= strlen+1. */
3512 #define CHECK_RESULT_AND_FREE(exp_str) \
3513 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
3514 ok(len >= (strlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlenA(exp_str) + 1, len); \
3515 LocalFree(string);
3517 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
3518 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); \
3519 ok(len >= (strlen(exp_str1) + 1) || len >= (strlen(exp_str2) + 1), "Length mismatch (expected %d or %d, got %d)\n", lstrlenA(exp_str1) + 1, lstrlenA(exp_str2) + 1, len); \
3520 LocalFree(string);
3522 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
3523 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3524 CHECK_RESULT_AND_FREE("");
3526 size = 4096;
3527 pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
3528 SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
3529 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3530 CHECK_RESULT_AND_FREE("O:S-1-2-0");
3532 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
3533 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3534 CHECK_RESULT_AND_FREE("O:S-1-2-0");
3536 size = sizeof(sid_buf);
3537 pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
3538 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
3539 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3540 CHECK_RESULT_AND_FREE("O:SY");
3542 pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
3543 SetSecurityDescriptorGroup(&desc, psid, TRUE);
3544 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3545 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
3547 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
3548 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
3550 pacl = (PACL)acl_buf;
3551 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
3552 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
3553 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3554 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
3556 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
3557 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3558 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
3560 pConvertStringSidToSidA("S-1-5-6", &psid2);
3561 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
3562 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3563 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
3565 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
3566 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3567 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
3569 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
3570 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3571 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)");
3574 pacl = (PACL)acl_buf;
3575 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
3576 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
3577 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3578 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
3580 /* fails in win2k */
3581 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
3582 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
3583 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
3585 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
3586 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
3589 /* fails in win2k */
3590 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
3591 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
3593 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
3594 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
3597 LocalFree(psid2);
3598 LocalFree(psid);
3601 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
3603 SECURITY_DESCRIPTOR_CONTROL ref;
3604 SECURITY_DESCRIPTOR_CONTROL test;
3606 SECURITY_DESCRIPTOR_CONTROL const mutable
3607 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
3608 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
3609 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
3610 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
3612 SECURITY_DESCRIPTOR_CONTROL const immutable
3613 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
3614 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
3615 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
3616 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
3619 int bit;
3620 DWORD dwRevision;
3621 LPCSTR fmt = "Expected error %s, got %u\n";
3623 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
3625 /* The mutable bits are mutable regardless of the truth of
3626 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
3628 /* Check call barfs if any bit-of-interest is immutable */
3629 for (bit = 0; bit < 16; ++bit)
3631 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
3632 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
3634 SECURITY_DESCRIPTOR_CONTROL ctrl;
3636 DWORD dwExpect = (bitOfInterest & immutable)
3637 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
3638 LPCSTR strExpect = (bitOfInterest & immutable)
3639 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
3641 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
3642 setOrClear ^= bitOfInterest;
3643 SetLastError (0xbebecaca);
3644 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
3645 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3646 GetSecurityDescriptorControl(sec, &test, &dwRevision);
3647 expect_eq(test, ctrl, int, "%x");
3649 setOrClear ^= bitOfInterest;
3650 SetLastError (0xbebecaca);
3651 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
3652 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3653 GetSecurityDescriptorControl (sec, &test, &dwRevision);
3654 expect_eq(test, ref, int, "%x");
3657 /* Check call barfs if any bit-to-set is immutable
3658 even when not a bit-of-interest */
3659 for (bit = 0; bit < 16; ++bit)
3661 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
3662 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
3664 SECURITY_DESCRIPTOR_CONTROL ctrl;
3666 DWORD dwExpect = ((1 << bit) & immutable)
3667 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
3668 LPCSTR strExpect = ((1 << bit) & immutable)
3669 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
3671 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
3672 setOrClear ^= bitsOfInterest;
3673 SetLastError (0xbebecaca);
3674 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
3675 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3676 GetSecurityDescriptorControl(sec, &test, &dwRevision);
3677 expect_eq(test, ctrl, int, "%x");
3679 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
3680 setOrClear ^= bitsOfInterest;
3681 SetLastError (0xbebecaca);
3682 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
3683 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
3684 GetSecurityDescriptorControl(sec, &test, &dwRevision);
3685 expect_eq(test, ctrl, int, "%x");
3689 static void test_PrivateObjectSecurity(void)
3691 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
3692 SECURITY_DESCRIPTOR_CONTROL ctrl;
3693 PSECURITY_DESCRIPTOR sec;
3694 DWORD dwDescSize;
3695 DWORD dwRevision;
3696 DWORD retSize;
3697 LPSTR string;
3698 ULONG len;
3699 PSECURITY_DESCRIPTOR buf;
3700 BOOL ret;
3702 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
3704 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3705 return;
3708 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3709 "O:SY"
3710 "G:S-1-5-21-93476-23408-4576"
3711 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
3712 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3713 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
3714 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3716 test_SetSecurityDescriptorControl(sec);
3718 LocalFree(sec);
3720 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3721 "O:SY"
3722 "G:S-1-5-21-93476-23408-4576",
3723 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3725 test_SetSecurityDescriptorControl(sec);
3727 LocalFree(sec);
3729 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3730 "O:SY"
3731 "G:S-1-5-21-93476-23408-4576"
3732 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3733 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3734 buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
3735 pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
3736 GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
3737 expect_eq(ctrl, 0x9014, int, "%x");
3739 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
3740 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3741 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3742 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3743 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
3744 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3745 expect_eq(ctrl, 0x8000, int, "%x");
3747 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
3748 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3749 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3750 ret = pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len);
3751 ok(ret, "Conversion failed err=%u\n", GetLastError());
3752 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)",
3753 "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 */
3754 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3755 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8004, int, "%x");
3757 ret = GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize);
3758 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3759 ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3760 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3761 CHECK_ONE_OF_AND_FREE("O:SY"
3762 "G:S-1-5-21-93476-23408-4576"
3763 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3764 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
3765 "O:SY"
3766 "G:S-1-5-21-93476-23408-4576"
3767 "D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3768 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)"); /* Win7 */
3769 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3770 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8014, int, "%x");
3772 SetLastError(0xdeadbeef);
3773 ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
3774 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
3776 LocalFree(sec);
3777 HeapFree(GetProcessHeap(), 0, buf);
3779 #undef CHECK_RESULT_AND_FREE
3780 #undef CHECK_ONE_OF_AND_FREE
3782 static void test_acls(void)
3784 char buffer[256];
3785 PACL pAcl = (PACL)buffer;
3786 BOOL ret;
3788 SetLastError(0xdeadbeef);
3789 ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
3790 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3792 win_skip("InitializeAcl is not implemented\n");
3793 return;
3796 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
3798 SetLastError(0xdeadbeef);
3799 ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
3800 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
3802 SetLastError(0xdeadbeef);
3803 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
3804 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
3806 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
3807 ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
3809 ret = IsValidAcl(pAcl);
3810 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3812 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
3813 ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
3815 ret = IsValidAcl(pAcl);
3816 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3818 SetLastError(0xdeadbeef);
3819 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
3820 if (GetLastError() != ERROR_INVALID_PARAMETER)
3822 ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
3824 ret = IsValidAcl(pAcl);
3825 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3827 else
3828 win_skip("ACL_REVISION4 is not implemented on NT4\n");
3830 SetLastError(0xdeadbeef);
3831 ret = InitializeAcl(pAcl, sizeof(buffer), -1);
3832 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
3835 static void test_GetSecurityInfo(void)
3837 char b[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
3838 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], dacl[100];
3839 DWORD sid_size = sizeof(admin_ptr), l = sizeof(b);
3840 PSID admin_sid = (PSID) admin_ptr, user_sid;
3841 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3842 ACL_SIZE_INFORMATION acl_size;
3843 PSECURITY_DESCRIPTOR pSD;
3844 ACCESS_ALLOWED_ACE *ace;
3845 HANDLE token, obj;
3846 PSID owner, group;
3847 BOOL bret = TRUE;
3848 PACL pDacl;
3849 DWORD ret;
3851 if (!pGetSecurityInfo || !pSetSecurityInfo)
3853 win_skip("[Get|Set]SecurityInfo is not available\n");
3854 return;
3857 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3859 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3860 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3862 if (!bret)
3864 win_skip("Failed to get current user token\n");
3865 return;
3867 GetTokenInformation(token, TokenUser, b, l, &l);
3868 CloseHandle( token );
3869 user_sid = ((TOKEN_USER *)b)->User.Sid;
3871 /* Create something. Files have lots of associated security info. */
3872 obj = CreateFileA(myARGV[0], GENERIC_READ|WRITE_DAC, FILE_SHARE_READ, NULL,
3873 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3874 if (obj == INVALID_HANDLE_VALUE)
3876 skip("Couldn't create an object for GetSecurityInfo test\n");
3877 return;
3880 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3881 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3882 &owner, &group, &pDacl, NULL, &pSD);
3883 if (ret == ERROR_CALL_NOT_IMPLEMENTED)
3885 win_skip("GetSecurityInfo is not implemented\n");
3886 CloseHandle(obj);
3887 return;
3889 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3890 ok(pSD != NULL, "GetSecurityInfo\n");
3891 ok(owner != NULL, "GetSecurityInfo\n");
3892 ok(group != NULL, "GetSecurityInfo\n");
3893 if (pDacl != NULL)
3894 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
3895 else
3896 win_skip("No ACL information returned\n");
3898 LocalFree(pSD);
3900 if (!pCreateWellKnownSid)
3902 win_skip("NULL parameter test would crash on NT4\n");
3903 CloseHandle(obj);
3904 return;
3907 /* If we don't ask for the security descriptor, Windows will still give us
3908 the other stuff, leaving us no way to free it. */
3909 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3910 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3911 &owner, &group, &pDacl, NULL, NULL);
3912 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3913 ok(owner != NULL, "GetSecurityInfo\n");
3914 ok(group != NULL, "GetSecurityInfo\n");
3915 if (pDacl != NULL)
3916 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
3917 else
3918 win_skip("No ACL information returned\n");
3920 /* Create security descriptor information and test that it comes back the same */
3921 pSD = &sd;
3922 pDacl = (PACL)&dacl;
3923 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3924 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3925 bret = InitializeAcl(pDacl, sizeof(dacl), ACL_REVISION);
3926 ok(bret, "Failed to initialize ACL.\n");
3927 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
3928 ok(bret, "Failed to add Current User to ACL.\n");
3929 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
3930 ok(bret, "Failed to add Administrator Group to ACL.\n");
3931 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3932 ok(bret, "Failed to add ACL to security desciptor.\n");
3933 ret = pSetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3934 NULL, NULL, pDacl, NULL);
3935 ok(ret == ERROR_SUCCESS, "SetSecurityInfo returned %d\n", ret);
3936 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3937 NULL, NULL, &pDacl, NULL, NULL);
3938 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3939 ok(pDacl && IsValidAcl(pDacl), "GetSecurityInfo returned invalid DACL.\n");
3940 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3941 ok(bret, "GetAclInformation failed\n");
3942 if (acl_size.AceCount > 0)
3944 bret = pGetAce(pDacl, 0, (VOID **)&ace);
3945 ok(bret, "Failed to get Current User ACE.\n");
3946 bret = EqualSid(&ace->SidStart, user_sid);
3947 todo_wine ok(bret, "Current User ACE != Current User SID.\n");
3948 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3949 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3950 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3951 ace->Mask);
3953 if (acl_size.AceCount > 1)
3955 bret = pGetAce(pDacl, 1, (VOID **)&ace);
3956 ok(bret, "Failed to get Administators Group ACE.\n");
3957 bret = EqualSid(&ace->SidStart, admin_sid);
3958 todo_wine ok(bret, "Administators Group ACE != Administators Group SID.\n");
3959 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3960 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3961 ok(ace->Mask == 0x1f01ff, "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3962 ace->Mask);
3964 CloseHandle(obj);
3967 static void test_GetSidSubAuthority(void)
3969 PSID psid = NULL;
3971 if (!pGetSidSubAuthority || !pConvertStringSidToSidA || !pIsValidSid || !pGetSidSubAuthorityCount)
3973 win_skip("Some functions not available\n");
3974 return;
3976 /* Note: on windows passing in an invalid index like -1, lets GetSidSubAuthority return 0x05000000 but
3977 still GetLastError returns ERROR_SUCCESS then. We don't test these unlikely cornercases here for now */
3978 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576",&psid),"ConvertStringSidToSidA failed\n");
3979 ok(pIsValidSid(psid),"Sid is not valid\n");
3980 SetLastError(0xbebecaca);
3981 ok(*pGetSidSubAuthorityCount(psid) == 4,"GetSidSubAuthorityCount gave %d expected 4\n",*pGetSidSubAuthorityCount(psid));
3982 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3983 SetLastError(0xbebecaca);
3984 ok(*pGetSidSubAuthority(psid,0) == 21,"GetSidSubAuthority gave %d expected 21\n",*pGetSidSubAuthority(psid,0));
3985 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3986 SetLastError(0xbebecaca);
3987 ok(*pGetSidSubAuthority(psid,1) == 93476,"GetSidSubAuthority gave %d expected 93476\n",*pGetSidSubAuthority(psid,1));
3988 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3989 SetLastError(0xbebecaca);
3990 ok(pGetSidSubAuthority(psid,4) != NULL,"Expected out of bounds GetSidSubAuthority to return a non-NULL pointer\n");
3991 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
3992 LocalFree(psid);
3995 static void test_CheckTokenMembership(void)
3997 PTOKEN_GROUPS token_groups;
3998 DWORD size;
3999 HANDLE process_token, token;
4000 BOOL is_member;
4001 BOOL ret;
4002 DWORD i;
4004 if (!pCheckTokenMembership)
4006 win_skip("CheckTokenMembership is not available\n");
4007 return;
4009 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
4010 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
4012 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
4013 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
4015 /* groups */
4016 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
4017 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
4018 "GetTokenInformation(TokenGroups) %s with error %d\n",
4019 ret ? "succeeded" : "failed", GetLastError());
4020 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
4021 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
4022 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
4024 for (i = 0; i < token_groups->GroupCount; i++)
4026 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
4027 break;
4030 if (i == token_groups->GroupCount)
4032 HeapFree(GetProcessHeap(), 0, token_groups);
4033 CloseHandle(token);
4034 skip("user not a member of any group\n");
4035 return;
4038 is_member = FALSE;
4039 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
4040 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
4041 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
4043 is_member = FALSE;
4044 ret = pCheckTokenMembership(NULL, token_groups->Groups[i].Sid, &is_member);
4045 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
4046 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
4048 is_member = TRUE;
4049 SetLastError(0xdeadbeef);
4050 ret = pCheckTokenMembership(process_token, token_groups->Groups[i].Sid, &is_member);
4051 ok(!ret && GetLastError() == ERROR_NO_IMPERSONATION_TOKEN,
4052 "CheckTokenMembership with process token %s with error %d\n",
4053 ret ? "succeeded" : "failed", GetLastError());
4054 ok(!is_member, "CheckTokenMembership should have cleared is_member\n");
4056 HeapFree(GetProcessHeap(), 0, token_groups);
4057 CloseHandle(token);
4058 CloseHandle(process_token);
4061 static void test_EqualSid(void)
4063 PSID sid1, sid2;
4064 BOOL ret;
4065 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
4066 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
4068 SetLastError(0xdeadbeef);
4069 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
4070 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid1);
4071 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4073 win_skip("AllocateAndInitializeSid is not implemented\n");
4074 return;
4076 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
4077 ok(GetLastError() == 0xdeadbeef,
4078 "AllocateAndInitializeSid shouldn't have set last error to %d\n",
4079 GetLastError());
4081 ret = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
4082 0, 0, 0, 0, 0, 0, 0, &sid2);
4083 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
4085 SetLastError(0xdeadbeef);
4086 ret = EqualSid(sid1, sid2);
4087 ok(!ret, "World and domain admins sids shouldn't have been equal\n");
4088 ok(GetLastError() == ERROR_SUCCESS ||
4089 broken(GetLastError() == 0xdeadbeef), /* NT4 */
4090 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
4091 GetLastError());
4093 SetLastError(0xdeadbeef);
4094 sid2 = FreeSid(sid2);
4095 ok(!sid2, "FreeSid should have returned NULL instead of %p\n", sid2);
4096 ok(GetLastError() == 0xdeadbeef,
4097 "FreeSid shouldn't have set last error to %d\n",
4098 GetLastError());
4100 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
4101 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid2);
4102 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
4104 SetLastError(0xdeadbeef);
4105 ret = EqualSid(sid1, sid2);
4106 ok(ret, "Same sids should have been equal\n");
4107 ok(GetLastError() == ERROR_SUCCESS ||
4108 broken(GetLastError() == 0xdeadbeef), /* NT4 */
4109 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
4110 GetLastError());
4112 ((SID *)sid2)->Revision = 2;
4113 SetLastError(0xdeadbeef);
4114 ret = EqualSid(sid1, sid2);
4115 ok(!ret, "EqualSid with invalid sid should have returned FALSE\n");
4116 ok(GetLastError() == ERROR_SUCCESS ||
4117 broken(GetLastError() == 0xdeadbeef), /* NT4 */
4118 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
4119 GetLastError());
4120 ((SID *)sid2)->Revision = SID_REVISION;
4122 FreeSid(sid1);
4123 FreeSid(sid2);
4126 static void test_GetUserNameA(void)
4128 char buffer[UNLEN + 1], filler[UNLEN + 1];
4129 DWORD required_len, buffer_len;
4130 BOOL ret;
4132 /* Test crashes on Windows. */
4133 if (0)
4135 SetLastError(0xdeadbeef);
4136 GetUserNameA(NULL, NULL);
4139 SetLastError(0xdeadbeef);
4140 required_len = 0;
4141 ret = GetUserNameA(NULL, &required_len);
4142 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
4143 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
4144 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4146 SetLastError(0xdeadbeef);
4147 required_len = 1;
4148 ret = GetUserNameA(NULL, &required_len);
4149 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
4150 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
4151 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4153 /* Tests crashes on Windows. */
4154 if (0)
4156 SetLastError(0xdeadbeef);
4157 required_len = UNLEN + 1;
4158 GetUserNameA(NULL, &required_len);
4160 SetLastError(0xdeadbeef);
4161 GetUserNameA(buffer, NULL);
4164 memset(filler, 'x', sizeof(filler));
4166 /* Note that GetUserNameA on XP and newer outputs the number of bytes
4167 * required for a Unicode string, which affects a test in the next block. */
4168 SetLastError(0xdeadbeef);
4169 memcpy(buffer, filler, sizeof(filler));
4170 required_len = 0;
4171 ret = GetUserNameA(buffer, &required_len);
4172 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
4173 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
4174 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
4175 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4177 SetLastError(0xdeadbeef);
4178 memcpy(buffer, filler, sizeof(filler));
4179 buffer_len = required_len;
4180 ret = GetUserNameA(buffer, &buffer_len);
4181 ok(ret == TRUE, "GetUserNameA returned %d, last error %u\n", ret, GetLastError());
4182 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
4183 ok(buffer_len == required_len ||
4184 broken(buffer_len == required_len / sizeof(WCHAR)), /* XP+ */
4185 "Outputted buffer length was %u\n", buffer_len);
4187 /* Use the reported buffer size from the last GetUserNameA call and pass
4188 * a length that is one less than the required value. */
4189 SetLastError(0xdeadbeef);
4190 memcpy(buffer, filler, sizeof(filler));
4191 buffer_len--;
4192 ret = GetUserNameA(buffer, &buffer_len);
4193 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
4194 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was untouched\n");
4195 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
4196 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4199 static void test_GetUserNameW(void)
4201 WCHAR buffer[UNLEN + 1], filler[UNLEN + 1];
4202 DWORD required_len, buffer_len;
4203 BOOL ret;
4205 /* Test crashes on Windows. */
4206 if (0)
4208 SetLastError(0xdeadbeef);
4209 GetUserNameW(NULL, NULL);
4212 SetLastError(0xdeadbeef);
4213 required_len = 0;
4214 ret = GetUserNameW(NULL, &required_len);
4215 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4216 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
4217 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4219 SetLastError(0xdeadbeef);
4220 required_len = 1;
4221 ret = GetUserNameW(NULL, &required_len);
4222 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4223 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
4224 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4226 /* Tests crash on Windows. */
4227 if (0)
4229 SetLastError(0xdeadbeef);
4230 required_len = UNLEN + 1;
4231 GetUserNameW(NULL, &required_len);
4233 SetLastError(0xdeadbeef);
4234 GetUserNameW(buffer, NULL);
4237 memset(filler, 'x', sizeof(filler));
4239 SetLastError(0xdeadbeef);
4240 memcpy(buffer, filler, sizeof(filler));
4241 required_len = 0;
4242 ret = GetUserNameW(buffer, &required_len);
4243 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4244 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
4245 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
4246 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4248 SetLastError(0xdeadbeef);
4249 memcpy(buffer, filler, sizeof(filler));
4250 buffer_len = required_len;
4251 ret = GetUserNameW(buffer, &buffer_len);
4252 ok(ret == TRUE, "GetUserNameW returned %d, last error %u\n", ret, GetLastError());
4253 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
4254 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
4256 /* GetUserNameW on XP and newer writes a truncated portion of the username string to the buffer. */
4257 SetLastError(0xdeadbeef);
4258 memcpy(buffer, filler, sizeof(filler));
4259 buffer_len--;
4260 ret = GetUserNameW(buffer, &buffer_len);
4261 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
4262 ok(!memcmp(buffer, filler, sizeof(filler)) ||
4263 broken(memcmp(buffer, filler, sizeof(filler)) != 0), /* XP+ */
4264 "Output buffer was altered\n");
4265 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
4266 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
4269 static void test_CreateRestrictedToken(void)
4271 HANDLE process_token, token, r_token;
4272 PTOKEN_GROUPS token_groups, groups2;
4273 SID_AND_ATTRIBUTES sattr;
4274 SECURITY_IMPERSONATION_LEVEL level;
4275 TOKEN_TYPE type;
4276 BOOL is_member;
4277 DWORD size;
4278 BOOL ret;
4279 DWORD i, j;
4281 if (!pCreateRestrictedToken)
4283 win_skip("CreateRestrictedToken is not available\n");
4284 return;
4287 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
4288 ok(ret, "got error %d\n", GetLastError());
4290 ret = DuplicateTokenEx(process_token, TOKEN_DUPLICATE|TOKEN_ADJUST_GROUPS|TOKEN_QUERY,
4291 NULL, SecurityImpersonation, TokenImpersonation, &token);
4292 ok(ret, "got error %d\n", GetLastError());
4294 /* groups */
4295 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
4296 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
4297 "got %d with error %d\n", ret, GetLastError());
4298 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
4299 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
4300 ok(ret, "got error %d\n", GetLastError());
4302 for (i = 0; i < token_groups->GroupCount; i++)
4304 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
4305 break;
4308 if (i == token_groups->GroupCount)
4310 HeapFree(GetProcessHeap(), 0, token_groups);
4311 CloseHandle(token);
4312 skip("User not a member of any group\n");
4313 return;
4316 is_member = FALSE;
4317 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
4318 ok(ret, "got error %d\n", GetLastError());
4319 ok(is_member, "not a member\n");
4321 /* disable a SID in new token */
4322 sattr.Sid = token_groups->Groups[i].Sid;
4323 sattr.Attributes = 0;
4324 r_token = NULL;
4325 ret = pCreateRestrictedToken(token, 0, 1, &sattr, 0, NULL, 0, NULL, &r_token);
4326 ok(ret, "got error %d\n", GetLastError());
4328 if (ret)
4330 /* check if a SID is enabled */
4331 is_member = TRUE;
4332 ret = pCheckTokenMembership(r_token, token_groups->Groups[i].Sid, &is_member);
4333 ok(ret, "got error %d\n", GetLastError());
4334 todo_wine ok(!is_member, "not a member\n");
4336 ret = GetTokenInformation(r_token, TokenGroups, NULL, 0, &size);
4337 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d with error %d\n",
4338 ret, GetLastError());
4339 groups2 = HeapAlloc(GetProcessHeap(), 0, size);
4340 ret = GetTokenInformation(r_token, TokenGroups, groups2, size, &size);
4341 ok(ret, "got error %d\n", GetLastError());
4343 for (j = 0; j < groups2->GroupCount; j++)
4345 if (EqualSid(groups2->Groups[j].Sid, token_groups->Groups[i].Sid))
4346 break;
4349 todo_wine ok(groups2->Groups[j].Attributes & SE_GROUP_USE_FOR_DENY_ONLY,
4350 "got wrong attributes\n");
4351 todo_wine ok((groups2->Groups[j].Attributes & SE_GROUP_ENABLED) == 0,
4352 "got wrong attributes\n");
4354 HeapFree(GetProcessHeap(), 0, groups2);
4356 size = sizeof(type);
4357 ret = GetTokenInformation(r_token, TokenType, &type, size, &size);
4358 ok(ret, "got error %d\n", GetLastError());
4359 ok(type == TokenImpersonation, "got type %u\n", type);
4361 size = sizeof(level);
4362 ret = GetTokenInformation(r_token, TokenImpersonationLevel, &level, size, &size);
4363 ok(ret, "got error %d\n", GetLastError());
4364 ok(level == SecurityImpersonation, "got level %u\n", type);
4367 HeapFree(GetProcessHeap(), 0, token_groups);
4368 CloseHandle(r_token);
4369 CloseHandle(token);
4370 CloseHandle(process_token);
4373 static void validate_default_security_descriptor(SECURITY_DESCRIPTOR *sd)
4375 BOOL ret, present, defaulted;
4376 ACL *acl;
4377 void *sid;
4379 ret = IsValidSecurityDescriptor(sd);
4380 ok(ret, "security descriptor is not valid\n");
4382 present = -1;
4383 defaulted = -1;
4384 acl = (void *)0xdeadbeef;
4385 SetLastError(0xdeadbeef);
4386 ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
4387 ok(ret, "GetSecurityDescriptorDacl error %d\n", GetLastError());
4388 todo_wine
4389 ok(present == 1, "acl is not present\n");
4390 todo_wine
4391 ok(acl != (void *)0xdeadbeef && acl != NULL, "acl pointer is not set\n");
4392 ok(defaulted == 0, "defaulted is set to TRUE\n");
4394 defaulted = -1;
4395 sid = (void *)0xdeadbeef;
4396 SetLastError(0xdeadbeef);
4397 ret = GetSecurityDescriptorOwner(sd, &sid, &defaulted);
4398 ok(ret, "GetSecurityDescriptorOwner error %d\n", GetLastError());
4399 todo_wine
4400 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
4401 ok(defaulted == 0, "defaulted is set to TRUE\n");
4403 defaulted = -1;
4404 sid = (void *)0xdeadbeef;
4405 SetLastError(0xdeadbeef);
4406 ret = GetSecurityDescriptorGroup(sd, &sid, &defaulted);
4407 ok(ret, "GetSecurityDescriptorGroup error %d\n", GetLastError());
4408 todo_wine
4409 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
4410 ok(defaulted == 0, "defaulted is set to TRUE\n");
4413 static void test_default_handle_security(HANDLE token, HANDLE handle, GENERIC_MAPPING *mapping)
4415 DWORD ret, length, needed, granted, priv_set_len;
4416 BOOL status;
4417 PRIVILEGE_SET priv_set;
4418 SECURITY_DESCRIPTOR *sd;
4420 needed = 0xdeadbeef;
4421 SetLastError(0xdeadbeef);
4422 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4423 NULL, 0, &needed);
4424 ok(!ret, "GetKernelObjectSecurity should fail\n");
4425 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4426 ok(needed != 0xdeadbeef, "GetKernelObjectSecurity should return required buffer length\n");
4428 length = needed;
4429 sd = HeapAlloc(GetProcessHeap(), 0, length);
4431 needed = 0xdeadbeef;
4432 SetLastError(0xdeadbeef);
4433 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4434 sd, length, &needed);
4435 ok(ret, "GetKernelObjectSecurity error %d\n", GetLastError());
4436 ok(needed == length || needed == 0 /* file, pipe */, "GetKernelObjectSecurity should return %u instead of %u\n", length, needed);
4438 validate_default_security_descriptor(sd);
4440 priv_set_len = sizeof(priv_set);
4441 granted = 0xdeadbeef;
4442 status = 0xdeadbeef;
4443 SetLastError(0xdeadbeef);
4444 ret = AccessCheck(sd, token, MAXIMUM_ALLOWED, mapping, &priv_set, &priv_set_len, &granted, &status);
4445 todo_wine {
4446 ok(ret, "AccessCheck error %d\n", GetLastError());
4447 ok(status == 1, "expected 1, got %d\n", status);
4448 ok(granted == mapping->GenericAll, "expected all access %#x, got %#x\n", mapping->GenericAll, granted);
4450 priv_set_len = sizeof(priv_set);
4451 granted = 0xdeadbeef;
4452 status = 0xdeadbeef;
4453 SetLastError(0xdeadbeef);
4454 ret = AccessCheck(sd, token, 0, mapping, &priv_set, &priv_set_len, &granted, &status);
4455 todo_wine {
4456 ok(ret, "AccessCheck error %d\n", GetLastError());
4457 ok(status == 0 || broken(status == 1) /* NT4 */, "expected 0, got %d\n", status);
4458 ok(granted == 0 || broken(granted == mapping->GenericRead) /* NT4 */, "expected 0, got %#x\n", granted);
4460 priv_set_len = sizeof(priv_set);
4461 granted = 0xdeadbeef;
4462 status = 0xdeadbeef;
4463 SetLastError(0xdeadbeef);
4464 ret = AccessCheck(sd, token, ACCESS_SYSTEM_SECURITY, mapping, &priv_set, &priv_set_len, &granted, &status);
4465 todo_wine {
4466 ok(ret, "AccessCheck error %d\n", GetLastError());
4467 ok(status == 0, "expected 0, got %d\n", status);
4468 ok(granted == 0, "expected 0, got %#x\n", granted);
4470 priv_set_len = sizeof(priv_set);
4471 granted = 0xdeadbeef;
4472 status = 0xdeadbeef;
4473 SetLastError(0xdeadbeef);
4474 ret = AccessCheck(sd, token, mapping->GenericRead, mapping, &priv_set, &priv_set_len, &granted, &status);
4475 todo_wine {
4476 ok(ret, "AccessCheck error %d\n", GetLastError());
4477 ok(status == 1, "expected 1, got %d\n", status);
4478 ok(granted == mapping->GenericRead, "expected read access %#x, got %#x\n", mapping->GenericRead, granted);
4480 priv_set_len = sizeof(priv_set);
4481 granted = 0xdeadbeef;
4482 status = 0xdeadbeef;
4483 SetLastError(0xdeadbeef);
4484 ret = AccessCheck(sd, token, mapping->GenericWrite, mapping, &priv_set, &priv_set_len, &granted, &status);
4485 todo_wine {
4486 ok(ret, "AccessCheck error %d\n", GetLastError());
4487 ok(status == 1, "expected 1, got %d\n", status);
4488 ok(granted == mapping->GenericWrite, "expected write access %#x, got %#x\n", mapping->GenericWrite, granted);
4490 priv_set_len = sizeof(priv_set);
4491 granted = 0xdeadbeef;
4492 status = 0xdeadbeef;
4493 SetLastError(0xdeadbeef);
4494 ret = AccessCheck(sd, token, mapping->GenericExecute, mapping, &priv_set, &priv_set_len, &granted, &status);
4495 todo_wine {
4496 ok(ret, "AccessCheck error %d\n", GetLastError());
4497 ok(status == 1, "expected 1, got %d\n", status);
4498 ok(granted == mapping->GenericExecute, "expected execute access %#x, got %#x\n", mapping->GenericExecute, granted);
4500 HeapFree(GetProcessHeap(), 0, sd);
4503 static void test_mutex_security(HANDLE token)
4505 HANDLE mutex;
4506 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE | SYNCHRONIZE,
4507 STANDARD_RIGHTS_WRITE | MUTEX_MODIFY_STATE | SYNCHRONIZE,
4508 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
4509 STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS };
4511 SetLastError(0xdeadbeef);
4512 mutex = OpenMutexA(0, FALSE, "WineTestMutex");
4513 ok(!mutex, "mutex should not exist\n");
4514 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
4516 SetLastError(0xdeadbeef);
4517 mutex = CreateMutexA(NULL, FALSE, "WineTestMutex");
4518 ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
4520 test_default_handle_security(token, mutex, &mapping);
4522 CloseHandle (mutex);
4525 static void test_event_security(HANDLE token)
4527 HANDLE event;
4528 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | EVENT_QUERY_STATE | SYNCHRONIZE,
4529 STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE | SYNCHRONIZE,
4530 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
4531 STANDARD_RIGHTS_ALL | EVENT_ALL_ACCESS };
4533 SetLastError(0xdeadbeef);
4534 event = OpenEventA(0, FALSE, "WineTestEvent");
4535 ok(!event, "event should not exist\n");
4536 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
4538 SetLastError(0xdeadbeef);
4539 event = CreateEventA(NULL, FALSE, FALSE, "WineTestEvent");
4540 ok(event != 0, "CreateEvent error %d\n", GetLastError());
4542 test_default_handle_security(token, event, &mapping);
4544 CloseHandle(event);
4547 #define WINE_TEST_PIPE "\\\\.\\pipe\\WineTestPipe"
4548 static void test_named_pipe_security(HANDLE token)
4550 HANDLE pipe, file;
4551 GENERIC_MAPPING mapping = { FILE_GENERIC_READ,
4552 FILE_GENERIC_WRITE,
4553 FILE_GENERIC_EXECUTE,
4554 STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS };
4556 SetLastError(0xdeadbeef);
4557 pipe = CreateNamedPipeA(WINE_TEST_PIPE, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
4558 PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES,
4559 0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL);
4560 ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe error %d\n", GetLastError());
4562 test_default_handle_security(token, pipe, &mapping);
4564 SetLastError(0xdeadbeef);
4565 file = CreateFileA(WINE_TEST_PIPE, FILE_ALL_ACCESS, 0, NULL, OPEN_EXISTING, 0, 0);
4566 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4567 CloseHandle(file);
4569 CloseHandle(pipe);
4571 SetLastError(0xdeadbeef);
4572 file = CreateFileA("\\\\.\\pipe\\", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
4573 ok(file != INVALID_HANDLE_VALUE || broken(file == INVALID_HANDLE_VALUE) /* before Vista */, "CreateFile error %d\n", GetLastError());
4574 CloseHandle(file);
4577 static BOOL validate_impersonation_token(HANDLE token, DWORD *token_type)
4579 DWORD ret, needed;
4580 TOKEN_TYPE type;
4581 SECURITY_IMPERSONATION_LEVEL sil;
4583 type = 0xdeadbeef;
4584 needed = 0;
4585 SetLastError(0xdeadbeef);
4586 ret = GetTokenInformation(token, TokenType, &type, sizeof(type), &needed);
4587 ok(ret, "GetTokenInformation error %d\n", GetLastError());
4588 ok(needed == sizeof(type), "GetTokenInformation should return required buffer length\n");
4589 ok(type == TokenPrimary || type == TokenImpersonation, "expected TokenPrimary or TokenImpersonation, got %d\n", type);
4591 *token_type = type;
4592 if (type != TokenImpersonation) return FALSE;
4594 needed = 0;
4595 SetLastError(0xdeadbeef);
4596 ret = GetTokenInformation(token, TokenImpersonationLevel, &sil, sizeof(sil), &needed);
4597 ok(ret, "GetTokenInformation error %d\n", GetLastError());
4598 ok(needed == sizeof(sil), "GetTokenInformation should return required buffer length\n");
4599 ok(sil == SecurityImpersonation, "expected SecurityImpersonation, got %d\n", sil);
4601 needed = 0xdeadbeef;
4602 SetLastError(0xdeadbeef);
4603 ret = GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &needed);
4604 ok(!ret, "GetTokenInformation should fail\n");
4605 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4606 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
4607 ok(needed > sizeof(TOKEN_DEFAULT_DACL), "GetTokenInformation returned empty default DACL\n");
4609 needed = 0xdeadbeef;
4610 SetLastError(0xdeadbeef);
4611 ret = GetTokenInformation(token, TokenOwner, NULL, 0, &needed);
4612 ok(!ret, "GetTokenInformation should fail\n");
4613 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4614 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
4615 ok(needed > sizeof(TOKEN_OWNER), "GetTokenInformation returned empty token owner\n");
4617 needed = 0xdeadbeef;
4618 SetLastError(0xdeadbeef);
4619 ret = GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &needed);
4620 ok(!ret, "GetTokenInformation should fail\n");
4621 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
4622 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
4623 ok(needed > sizeof(TOKEN_PRIMARY_GROUP), "GetTokenInformation returned empty token primary group\n");
4625 return TRUE;
4628 static void test_kernel_objects_security(void)
4630 HANDLE token, process_token;
4631 DWORD ret, token_type;
4633 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process_token);
4634 ok(ret, "OpenProcessToken error %d\n", GetLastError());
4636 ret = validate_impersonation_token(process_token, &token_type);
4637 ok(token_type == TokenPrimary, "expected TokenPrimary, got %d\n", token_type);
4638 ok(!ret, "access token should not be an impersonation token\n");
4640 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
4641 ok(ret, "DuplicateToken error %d\n", GetLastError());
4643 ret = validate_impersonation_token(token, &token_type);
4644 ok(ret, "access token should be a valid impersonation token\n");
4645 ok(token_type == TokenImpersonation, "expected TokenImpersonation, got %d\n", token_type);
4647 test_mutex_security(token);
4648 test_event_security(token);
4649 test_named_pipe_security(token);
4650 /* FIXME: test other kernel object types */
4652 CloseHandle(process_token);
4653 CloseHandle(token);
4656 static void test_TokenIntegrityLevel(void)
4658 TOKEN_MANDATORY_LABEL *tml;
4659 BYTE buffer[64]; /* using max. 28 byte in win7 x64 */
4660 HANDLE token;
4661 DWORD size;
4662 DWORD res;
4663 char *sidname = NULL;
4664 static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
4665 {SECURITY_MANDATORY_HIGH_RID}};
4666 static SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
4667 {SECURITY_MANDATORY_MEDIUM_RID}};
4669 SetLastError(0xdeadbeef);
4670 res = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
4671 ok(res, "got %d with %d (expected TRUE)\n", res, GetLastError());
4673 SetLastError(0xdeadbeef);
4674 res = GetTokenInformation(token, TokenIntegrityLevel, buffer, sizeof(buffer), &size);
4676 /* not supported before Vista */
4677 if (!res && ((GetLastError() == ERROR_INVALID_PARAMETER) || GetLastError() == ERROR_INVALID_FUNCTION))
4679 win_skip("TokenIntegrityLevel not supported\n");
4680 CloseHandle(token);
4681 return;
4684 ok(res, "got %u with %u (expected TRUE)\n", res, GetLastError());
4685 if (!res)
4687 CloseHandle(token);
4688 return;
4691 tml = (TOKEN_MANDATORY_LABEL*) buffer;
4692 ok(tml->Label.Attributes == (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED),
4693 "got 0x%x (expected 0x%x)\n", tml->Label.Attributes, (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED));
4695 SetLastError(0xdeadbeef);
4696 res = pConvertSidToStringSidA(tml->Label.Sid, &sidname);
4697 ok(res, "got %u and %u\n", res, GetLastError());
4699 ok(EqualSid(tml->Label.Sid, &medium_level) || EqualSid(tml->Label.Sid, &high_level),
4700 "got %s (expected 'S-1-16-8192' or 'S-1-16-12288')\n", sidname);
4702 LocalFree(sidname);
4703 CloseHandle(token);
4706 static void test_default_dacl_owner_sid(void)
4708 HANDLE handle;
4709 BOOL ret, defaulted, present, found;
4710 DWORD size, index;
4711 SECURITY_DESCRIPTOR *sd;
4712 SECURITY_ATTRIBUTES sa;
4713 PSID owner;
4714 ACL *dacl;
4715 ACCESS_ALLOWED_ACE *ace;
4717 sd = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
4718 ret = InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION );
4719 ok( ret, "error %u\n", GetLastError() );
4721 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4722 sa.lpSecurityDescriptor = sd;
4723 sa.bInheritHandle = FALSE;
4724 handle = CreateEventA( &sa, TRUE, TRUE, "test_event" );
4725 ok( handle != NULL, "error %u\n", GetLastError() );
4727 size = 0;
4728 ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, NULL, 0, &size );
4729 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "error %u\n", GetLastError() );
4731 sd = HeapAlloc( GetProcessHeap(), 0, size );
4732 ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, sd, size, &size );
4733 ok( ret, "error %u\n", GetLastError() );
4735 owner = (void *)0xdeadbeef;
4736 defaulted = TRUE;
4737 ret = GetSecurityDescriptorOwner( sd, &owner, &defaulted );
4738 ok( ret, "error %u\n", GetLastError() );
4739 ok( owner != (void *)0xdeadbeef, "owner not set\n" );
4740 todo_wine ok( !defaulted, "owner defaulted\n" );
4742 dacl = (void *)0xdeadbeef;
4743 present = FALSE;
4744 defaulted = TRUE;
4745 ret = GetSecurityDescriptorDacl( sd, &present, &dacl, &defaulted );
4746 ok( ret, "error %u\n", GetLastError() );
4747 ok( present, "dacl not present\n" );
4748 ok( dacl != (void *)0xdeadbeef, "dacl not set\n" );
4749 todo_wine ok( !defaulted, "dacl defaulted\n" );
4751 index = 0;
4752 found = FALSE;
4753 while (pGetAce( dacl, index++, (void **)&ace ))
4755 if (EqualSid( &ace->SidStart, owner )) found = TRUE;
4757 ok( found, "owner sid not found in dacl\n" );
4759 HeapFree( GetProcessHeap(), 0, sa.lpSecurityDescriptor );
4760 HeapFree( GetProcessHeap(), 0, sd );
4761 CloseHandle( handle );
4764 START_TEST(security)
4766 init();
4767 if (!hmod) return;
4769 if (myARGC >= 3)
4771 test_process_security_child();
4772 return;
4774 test_kernel_objects_security();
4775 test_sid();
4776 test_trustee();
4777 test_luid();
4778 test_CreateWellKnownSid();
4779 test_FileSecurity();
4780 test_AccessCheck();
4781 test_token_attr();
4782 test_LookupAccountSid();
4783 test_LookupAccountName();
4784 test_security_descriptor();
4785 test_process_security();
4786 test_impersonation_level();
4787 test_SetEntriesInAclW();
4788 test_SetEntriesInAclA();
4789 test_CreateDirectoryA();
4790 test_GetNamedSecurityInfoA();
4791 test_ConvertStringSecurityDescriptor();
4792 test_ConvertSecurityDescriptorToString();
4793 test_PrivateObjectSecurity();
4794 test_acls();
4795 test_GetSecurityInfo();
4796 test_GetSidSubAuthority();
4797 test_CheckTokenMembership();
4798 test_EqualSid();
4799 test_GetUserNameA();
4800 test_GetUserNameW();
4801 test_CreateRestrictedToken();
4802 test_TokenIntegrityLevel();
4803 test_default_dacl_owner_sid();