advapi32/tests: Simple tests of GetFileSecurity()/SetFileSecurity().
[wine/multimedia.git] / dlls / advapi32 / tests / security.c
blobd3efa0b9643412cbb8070f9199f1b3a8a5cba227
1 /*
2 * Unit tests for security functions
4 * Copyright (c) 2004 Mike McCormack
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
22 #include <stdio.h>
24 #include "ntstatus.h"
25 #define WIN32_NO_STATUS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winerror.h"
29 #include "aclapi.h"
30 #include "winnt.h"
31 #include "sddl.h"
32 #include "ntsecapi.h"
33 #include "lmcons.h"
35 #include "wine/test.h"
37 /* copied from Wine winternl.h - not included in the Windows SDK */
38 typedef enum _OBJECT_INFORMATION_CLASS {
39 ObjectBasicInformation,
40 ObjectNameInformation,
41 ObjectTypeInformation,
42 ObjectAllInformation,
43 ObjectDataInformation
44 } OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;
46 typedef struct _OBJECT_BASIC_INFORMATION {
47 ULONG Attributes;
48 ACCESS_MASK GrantedAccess;
49 ULONG HandleCount;
50 ULONG PointerCount;
51 ULONG PagedPoolUsage;
52 ULONG NonPagedPoolUsage;
53 ULONG Reserved[3];
54 ULONG NameInformationLength;
55 ULONG TypeInformationLength;
56 ULONG SecurityDescriptorLength;
57 LARGE_INTEGER CreateTime;
58 } OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;
60 #define expect_eq(expr, value, type, format) { type ret = expr; ok((value) == ret, #expr " expected " format " got " format "\n", (value), (ret)); }
62 static BOOL (WINAPI *pAddAccessAllowedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
63 static BOOL (WINAPI *pAddAccessDeniedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
64 static BOOL (WINAPI *pAddAuditAccessAceEx)(PACL, DWORD, DWORD, DWORD, PSID, BOOL, BOOL);
65 typedef VOID (WINAPI *fnBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
66 typedef VOID (WINAPI *fnBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
67 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
68 POBJECTS_AND_NAME_A pObjName,
69 SE_OBJECT_TYPE ObjectType,
70 LPSTR ObjectTypeName,
71 LPSTR InheritedObjectTypeName,
72 LPSTR Name );
73 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
74 POBJECTS_AND_SID pObjSid,
75 GUID* pObjectGuid,
76 GUID* pInheritedObjectGuid,
77 PSID pSid );
78 typedef LPSTR (WINAPI *fnGetTrusteeNameA)( PTRUSTEEA pTrustee );
79 typedef BOOL (WINAPI *fnMakeSelfRelativeSD)( PSECURITY_DESCRIPTOR, PSECURITY_DESCRIPTOR, LPDWORD );
80 typedef BOOL (WINAPI *fnConvertSidToStringSidA)( PSID pSid, LPSTR *str );
81 typedef BOOL (WINAPI *fnConvertStringSidToSidA)( LPCSTR str, PSID pSid );
82 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
83 PSECURITY_DESCRIPTOR*, PULONG );
84 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorW)(LPCWSTR, DWORD,
85 PSECURITY_DESCRIPTOR*, PULONG );
86 static BOOL (WINAPI *pConvertSecurityDescriptorToStringSecurityDescriptorA)(PSECURITY_DESCRIPTOR, DWORD,
87 SECURITY_INFORMATION, LPSTR *, PULONG );
88 typedef BOOL (WINAPI *fnGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
89 PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
90 typedef BOOL (WINAPI *fnSetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
91 PSECURITY_DESCRIPTOR);
92 static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
93 PSID*, PSID*, PACL*, PACL*,
94 PSECURITY_DESCRIPTOR*);
95 typedef DWORD (WINAPI *fnRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
96 typedef BOOL (WINAPI *fnCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
97 typedef BOOL (WINAPI *fnDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
98 SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
100 typedef NTSTATUS (WINAPI *fnLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
101 typedef NTSTATUS (WINAPI *fnLsaClose)(LSA_HANDLE);
102 typedef NTSTATUS (WINAPI *fnLsaFreeMemory)(PVOID);
103 typedef NTSTATUS (WINAPI *fnLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
104 static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
105 static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
106 static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
107 SECURITY_DESCRIPTOR_CONTROL);
108 static DWORD (WINAPI *pGetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
109 PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
111 static HMODULE hmod;
112 static int myARGC;
113 static char** myARGV;
115 fnBuildTrusteeWithSidA pBuildTrusteeWithSidA;
116 fnBuildTrusteeWithNameA pBuildTrusteeWithNameA;
117 fnBuildTrusteeWithObjectsAndNameA pBuildTrusteeWithObjectsAndNameA;
118 fnBuildTrusteeWithObjectsAndSidA pBuildTrusteeWithObjectsAndSidA;
119 fnGetTrusteeNameA pGetTrusteeNameA;
120 fnMakeSelfRelativeSD pMakeSelfRelativeSD;
121 fnConvertSidToStringSidA pConvertSidToStringSidA;
122 fnConvertStringSidToSidA pConvertStringSidToSidA;
123 fnGetFileSecurityA pGetFileSecurityA;
124 fnSetFileSecurityA pSetFileSecurityA;
125 fnRtlAdjustPrivilege pRtlAdjustPrivilege;
126 fnCreateWellKnownSid pCreateWellKnownSid;
127 fnDuplicateTokenEx pDuplicateTokenEx;
128 fnLsaQueryInformationPolicy pLsaQueryInformationPolicy;
129 fnLsaClose pLsaClose;
130 fnLsaFreeMemory pLsaFreeMemory;
131 fnLsaOpenPolicy pLsaOpenPolicy;
133 struct sidRef
135 SID_IDENTIFIER_AUTHORITY auth;
136 const char *refStr;
139 static void init(void)
141 HMODULE hntdll;
143 hntdll = GetModuleHandleA("ntdll.dll");
144 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
146 hmod = GetModuleHandle("advapi32.dll");
147 pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
148 pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
149 pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
150 pConvertStringSecurityDescriptorToSecurityDescriptorA =
151 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
152 pConvertStringSecurityDescriptorToSecurityDescriptorW =
153 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
154 pConvertSecurityDescriptorToStringSecurityDescriptorA =
155 (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
156 pGetFileSecurityA = (fnGetFileSecurityA)GetProcAddress(hmod, "GetFileSecurityA" );
157 pSetFileSecurityA = (fnSetFileSecurityA)GetProcAddress(hmod, "SetFileSecurityA" );
158 pCreateWellKnownSid = (fnCreateWellKnownSid)GetProcAddress( hmod, "CreateWellKnownSid" );
159 pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
160 pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
161 pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
162 pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
163 pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
165 myARGC = winetest_get_mainargs( &myARGV );
168 static void test_str_sid(const char *str_sid)
170 PSID psid;
171 char *temp;
173 if (pConvertStringSidToSidA(str_sid, &psid))
175 if (pConvertSidToStringSidA(psid, &temp))
177 trace(" %s: %s\n", str_sid, temp);
178 LocalFree(temp);
180 LocalFree(psid);
182 else
184 if (GetLastError() != ERROR_INVALID_SID)
185 trace(" %s: couldn't be converted, returned %d\n", str_sid, GetLastError());
186 else
187 trace(" %s: couldn't be converted\n", str_sid);
191 static void test_sid(void)
193 struct sidRef refs[] = {
194 { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
195 { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
196 { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
197 { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
198 { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
199 { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
201 const char noSubAuthStr[] = "S-1-5";
202 unsigned int i;
203 PSID psid = NULL;
204 SID *pisid;
205 BOOL r;
206 LPSTR str = NULL;
208 pConvertSidToStringSidA = (fnConvertSidToStringSidA)
209 GetProcAddress( hmod, "ConvertSidToStringSidA" );
210 if( !pConvertSidToStringSidA )
211 return;
212 pConvertStringSidToSidA = (fnConvertStringSidToSidA)
213 GetProcAddress( hmod, "ConvertStringSidToSidA" );
214 if( !pConvertStringSidToSidA )
215 return;
217 r = pConvertStringSidToSidA( NULL, NULL );
218 ok( !r, "expected failure with NULL parameters\n" );
219 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
220 return;
221 ok( GetLastError() == ERROR_INVALID_PARAMETER,
222 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
223 GetLastError() );
225 r = pConvertStringSidToSidA( refs[0].refStr, NULL );
226 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
227 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
228 GetLastError() );
230 r = pConvertStringSidToSidA( NULL, &str );
231 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
232 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
233 GetLastError() );
235 r = pConvertStringSidToSidA( noSubAuthStr, &psid );
236 ok( !r,
237 "expected failure with no sub authorities\n" );
238 ok( GetLastError() == ERROR_INVALID_SID,
239 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
240 GetLastError() );
242 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
243 pisid = (SID *)psid;
244 ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
245 ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expceted 21, got %d\n", pisid->SubAuthority[0]);
246 ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expceted 4576, got %d\n", pisid->SubAuthority[3]);
247 LocalFree(str);
249 for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
251 PISID pisid;
253 r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
254 &psid );
255 ok( r, "failed to allocate sid\n" );
256 r = pConvertSidToStringSidA( psid, &str );
257 ok( r, "failed to convert sid\n" );
258 if (r)
260 ok( !strcmp( str, refs[i].refStr ),
261 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
262 LocalFree( str );
264 if( psid )
265 FreeSid( psid );
267 r = pConvertStringSidToSidA( refs[i].refStr, &psid );
268 ok( r, "failed to parse sid string\n" );
269 pisid = (PISID)psid;
270 ok( pisid &&
271 !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
272 sizeof(refs[i].auth) ),
273 "string sid %s didn't parse to expected value\n"
274 "(got 0x%04x%08x, expected 0x%04x%08x)\n",
275 refs[i].refStr,
276 MAKEWORD( pisid->IdentifierAuthority.Value[1],
277 pisid->IdentifierAuthority.Value[0] ),
278 MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
279 pisid->IdentifierAuthority.Value[4] ),
280 MAKEWORD( pisid->IdentifierAuthority.Value[3],
281 pisid->IdentifierAuthority.Value[2] ) ),
282 MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
283 MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
284 MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
285 if( psid )
286 LocalFree( psid );
289 trace("String SIDs:\n");
290 test_str_sid("AO");
291 test_str_sid("RU");
292 test_str_sid("AN");
293 test_str_sid("AU");
294 test_str_sid("BA");
295 test_str_sid("BG");
296 test_str_sid("BO");
297 test_str_sid("BU");
298 test_str_sid("CA");
299 test_str_sid("CG");
300 test_str_sid("CO");
301 test_str_sid("DA");
302 test_str_sid("DC");
303 test_str_sid("DD");
304 test_str_sid("DG");
305 test_str_sid("DU");
306 test_str_sid("EA");
307 test_str_sid("ED");
308 test_str_sid("WD");
309 test_str_sid("PA");
310 test_str_sid("IU");
311 test_str_sid("LA");
312 test_str_sid("LG");
313 test_str_sid("LS");
314 test_str_sid("SY");
315 test_str_sid("NU");
316 test_str_sid("NO");
317 test_str_sid("NS");
318 test_str_sid("PO");
319 test_str_sid("PS");
320 test_str_sid("PU");
321 test_str_sid("RS");
322 test_str_sid("RD");
323 test_str_sid("RE");
324 test_str_sid("RC");
325 test_str_sid("SA");
326 test_str_sid("SO");
327 test_str_sid("SU");
330 static void test_trustee(void)
332 GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
333 GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
334 GUID ZeroGuid;
335 OBJECTS_AND_NAME_ oan;
336 OBJECTS_AND_SID oas;
337 TRUSTEE trustee;
338 PSID psid;
339 char szObjectTypeName[] = "ObjectTypeName";
340 char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
341 char szTrusteeName[] = "szTrusteeName";
342 SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
344 memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
346 pBuildTrusteeWithSidA = (fnBuildTrusteeWithSidA)
347 GetProcAddress( hmod, "BuildTrusteeWithSidA" );
348 pBuildTrusteeWithNameA = (fnBuildTrusteeWithNameA)
349 GetProcAddress( hmod, "BuildTrusteeWithNameA" );
350 pBuildTrusteeWithObjectsAndNameA = (fnBuildTrusteeWithObjectsAndNameA)
351 GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
352 pBuildTrusteeWithObjectsAndSidA = (fnBuildTrusteeWithObjectsAndSidA)
353 GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
354 pGetTrusteeNameA = (fnGetTrusteeNameA)
355 GetProcAddress (hmod, "GetTrusteeNameA" );
356 if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
357 !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
358 !pGetTrusteeNameA )
359 return;
361 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
363 trace( "failed to init SID\n" );
364 return;
367 /* test BuildTrusteeWithSidA */
368 memset( &trustee, 0xff, sizeof trustee );
369 pBuildTrusteeWithSidA( &trustee, psid );
371 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
372 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
373 "MultipleTrusteeOperation wrong\n");
374 ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
375 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
376 ok( trustee.ptstrName == (LPSTR) psid, "ptstrName wrong\n" );
378 /* test BuildTrusteeWithObjectsAndSidA (test 1) */
379 memset( &trustee, 0xff, sizeof trustee );
380 memset( &oas, 0xff, sizeof(oas) );
381 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
382 &InheritedObjectType, psid);
384 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
385 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
386 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
387 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
388 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
390 ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
391 ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
392 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
393 ok(oas.pSid == psid, "pSid wrong\n");
395 /* test GetTrusteeNameA */
396 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
398 /* test BuildTrusteeWithObjectsAndSidA (test 2) */
399 memset( &trustee, 0xff, sizeof trustee );
400 memset( &oas, 0xff, sizeof(oas) );
401 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
402 &InheritedObjectType, psid);
404 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
405 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
406 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
407 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
408 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
410 ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
411 ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
412 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
413 ok(oas.pSid == psid, "pSid wrong\n");
415 FreeSid( psid );
417 /* test BuildTrusteeWithNameA */
418 memset( &trustee, 0xff, sizeof trustee );
419 pBuildTrusteeWithNameA( &trustee, szTrusteeName );
421 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
422 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
423 "MultipleTrusteeOperation wrong\n");
424 ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
425 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
426 ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
428 /* test BuildTrusteeWithObjectsAndNameA (test 1) */
429 memset( &trustee, 0xff, sizeof trustee );
430 memset( &oan, 0xff, sizeof(oan) );
431 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
432 szInheritedObjectTypeName, szTrusteeName);
434 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
435 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
436 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
437 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
438 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
440 ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
441 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
442 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
443 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
445 /* test GetTrusteeNameA */
446 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
448 /* test BuildTrusteeWithObjectsAndNameA (test 2) */
449 memset( &trustee, 0xff, sizeof trustee );
450 memset( &oan, 0xff, sizeof(oan) );
451 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
452 szInheritedObjectTypeName, szTrusteeName);
454 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
455 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
456 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
457 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
458 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
460 ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
461 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
462 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
463 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
465 /* test BuildTrusteeWithObjectsAndNameA (test 3) */
466 memset( &trustee, 0xff, sizeof trustee );
467 memset( &oan, 0xff, sizeof(oan) );
468 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
469 NULL, szTrusteeName);
471 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
472 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
473 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
474 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
475 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
477 ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
478 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
479 ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
480 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
483 /* If the first isn't defined, assume none is */
484 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
485 #define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
486 #define SE_CREATE_TOKEN_PRIVILEGE 2L
487 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
488 #define SE_LOCK_MEMORY_PRIVILEGE 4L
489 #define SE_INCREASE_QUOTA_PRIVILEGE 5L
490 #define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
491 #define SE_TCB_PRIVILEGE 7L
492 #define SE_SECURITY_PRIVILEGE 8L
493 #define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
494 #define SE_LOAD_DRIVER_PRIVILEGE 10L
495 #define SE_SYSTEM_PROFILE_PRIVILEGE 11L
496 #define SE_SYSTEMTIME_PRIVILEGE 12L
497 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
498 #define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
499 #define SE_CREATE_PAGEFILE_PRIVILEGE 15L
500 #define SE_CREATE_PERMANENT_PRIVILEGE 16L
501 #define SE_BACKUP_PRIVILEGE 17L
502 #define SE_RESTORE_PRIVILEGE 18L
503 #define SE_SHUTDOWN_PRIVILEGE 19L
504 #define SE_DEBUG_PRIVILEGE 20L
505 #define SE_AUDIT_PRIVILEGE 21L
506 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
507 #define SE_CHANGE_NOTIFY_PRIVILLEGE 23L
508 #define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
509 #define SE_UNDOCK_PRIVILEGE 25L
510 #define SE_SYNC_AGENT_PRIVILEGE 26L
511 #define SE_ENABLE_DELEGATION_PRIVILEGE 27L
512 #define SE_MANAGE_VOLUME_PRIVILEGE 28L
513 #define SE_IMPERSONATE_PRIVILEGE 29L
514 #define SE_CREATE_GLOBAL_PRIVILEGE 30L
515 #define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
516 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
518 static void test_allocateLuid(void)
520 BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
521 LUID luid1, luid2;
522 BOOL ret;
524 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
525 if (!pAllocateLocallyUniqueId) return;
527 ret = pAllocateLocallyUniqueId(&luid1);
528 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
529 return;
531 ok(ret,
532 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
533 ret = pAllocateLocallyUniqueId(&luid2);
534 ok( ret,
535 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
536 ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
537 "AllocateLocallyUniqueId returned a well-known LUID\n");
538 ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
539 "AllocateLocallyUniqueId returned non-unique LUIDs\n");
540 ret = pAllocateLocallyUniqueId(NULL);
541 ok( !ret && GetLastError() == ERROR_NOACCESS,
542 "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
543 GetLastError());
546 static void test_lookupPrivilegeName(void)
548 BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
549 char buf[MAX_PATH]; /* arbitrary, seems long enough */
550 DWORD cchName = sizeof(buf);
551 LUID luid = { 0, 0 };
552 LONG i;
553 BOOL ret;
555 /* check whether it's available first */
556 pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
557 if (!pLookupPrivilegeNameA) return;
558 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
559 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
560 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
561 return;
563 /* check with a short buffer */
564 cchName = 0;
565 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
566 ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
567 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
568 "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
569 GetLastError());
570 ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
571 "LookupPrivilegeNameA returned an incorrect required length for\n"
572 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
573 lstrlenA("SeCreateTokenPrivilege") + 1);
574 /* check a known value and its returned length on success */
575 cchName = sizeof(buf);
576 ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
577 cchName == strlen("SeCreateTokenPrivilege"),
578 "LookupPrivilegeNameA returned an incorrect output length for\n"
579 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
580 (int)strlen("SeCreateTokenPrivilege"));
581 /* check known values */
582 for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i < SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
584 luid.LowPart = i;
585 cchName = sizeof(buf);
586 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
587 ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
588 "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
590 /* check a bogus LUID */
591 luid.LowPart = 0xdeadbeef;
592 cchName = sizeof(buf);
593 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
594 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
595 "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
596 GetLastError());
597 /* check on a bogus system */
598 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
599 cchName = sizeof(buf);
600 ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
601 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
602 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
603 "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
604 GetLastError());
607 struct NameToLUID
609 const char *name;
610 DWORD lowPart;
613 static void test_lookupPrivilegeValue(void)
615 static const struct NameToLUID privs[] = {
616 { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
617 { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
618 { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
619 { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
620 { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
621 { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
622 { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
623 { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
624 { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
625 { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
626 { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
627 { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
628 { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
629 { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
630 { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
631 { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
632 { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
633 { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
634 { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
635 { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
636 { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
637 { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILLEGE },
638 { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
639 { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
640 { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
641 { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
642 { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
643 { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
644 { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
646 BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
647 int i;
648 LUID luid;
649 BOOL ret;
651 /* check whether it's available first */
652 pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
653 if (!pLookupPrivilegeValueA) return;
654 ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
655 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
656 return;
658 /* check a bogus system name */
659 ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
660 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
661 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
662 "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
663 GetLastError());
664 /* check a NULL string */
665 ret = pLookupPrivilegeValueA(NULL, 0, &luid);
666 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
667 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
668 GetLastError());
669 /* check a bogus privilege name */
670 ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &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 case insensitive */
675 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
676 ok( ret,
677 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
678 GetLastError());
679 for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
681 /* Not all privileges are implemented on all Windows versions, so
682 * don't worry if the call fails
684 if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
686 ok(luid.LowPart == privs[i].lowPart,
687 "LookupPrivilegeValueA returned an invalid LUID for %s\n",
688 privs[i].name);
693 static void test_luid(void)
695 test_allocateLuid();
696 test_lookupPrivilegeName();
697 test_lookupPrivilegeValue();
700 static void test_FileSecurity(void)
702 char wintmpdir [MAX_PATH];
703 char path [MAX_PATH];
704 char file [MAX_PATH];
705 BOOL rc;
706 HANDLE fh;
707 DWORD sdSize;
708 DWORD retSize;
709 BYTE *sd;
710 SECURITY_INFORMATION const request = OWNER_SECURITY_INFORMATION
711 | GROUP_SECURITY_INFORMATION
712 | DACL_SECURITY_INFORMATION;
714 if (!pGetFileSecurityA) {
715 win_skip ("GetFileSecurity is not available\n");
716 return;
719 if (!pSetFileSecurityA) {
720 win_skip ("SetFileSecurity is not available\n");
721 return;
724 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
725 win_skip ("GetTempPathA failed\n");
726 return;
729 /* Create a temporary directory and in it a temporary file */
730 strcat (strcpy (path, wintmpdir), "rary");
731 SetLastError (NO_ERROR);
732 rc = CreateDirectoryA (path, NULL);
733 ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
734 "failed for '%s' with %d\n", path, GetLastError());
736 strcat (strcpy (file, path), "\\ess");
737 SetLastError (NO_ERROR);
738 fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
739 ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
740 "failed for '%s' with %d\n", file, GetLastError());
741 CloseHandle (fh);
743 /* For the temporary file ... */
745 /* Get size needed */
746 retSize = 0;
747 SetLastError (NO_ERROR);
748 rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
749 ok (!rc, "GetFileSecurityA "
750 "was expected to fail for '%s'\n", file);
751 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
752 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
753 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA "
754 "returned size %d; expected > %d\n", retSize, sizeof (SECURITY_DESCRIPTOR));
756 sdSize = retSize;
757 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
759 /* Get security descriptor for real */
760 retSize = 0;
761 SetLastError (NO_ERROR);
762 rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
763 ok (rc, "GetFileSecurityA "
764 "was not expected to fail '%s'\n", file);
765 ok (GetLastError () == NO_ERROR, "GetFileSecurityA "
766 "returned %d; expected NO_ERROR\n", GetLastError ());
767 ok (retSize == sdSize, "GetFileSecurityA "
768 "returned size %d; expected %d\n", retSize, sdSize);
770 /* Use it to set security descriptor */
771 SetLastError (NO_ERROR);
772 rc = pSetFileSecurityA (file, request, sd);
773 ok (rc, "SetFileSecurityA "
774 "was not expected to fail '%s'\n", file);
775 ok (GetLastError () == NO_ERROR, "SetFileSecurityA "
776 "returned %d; expected NO_ERROR\n", GetLastError ());
778 HeapFree (GetProcessHeap (), 0, sd);
780 /* Remove temporary file and directory */
781 DeleteFileA (file);
782 RemoveDirectoryA (path);
784 /* Old test */
785 strcpy (wintmpdir, "\\Should not exist");
786 SetLastError (NO_ERROR);
787 rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
788 ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
789 ok ((GetLastError() == ERROR_FILE_NOT_FOUND ) ||
790 (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
791 "last error ERROR_FILE_NOT_FOUND / ERROR_CALL_NOT_IMPLEMENTED (98) "
792 "expected, got %d\n", GetLastError());
795 static void test_AccessCheck(void)
797 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
798 PACL Acl = NULL;
799 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
800 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
801 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
802 GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
803 ACCESS_MASK Access;
804 BOOL AccessStatus;
805 HANDLE Token;
806 HANDLE ProcessToken;
807 BOOL ret;
808 DWORD PrivSetLen;
809 PRIVILEGE_SET *PrivSet;
810 BOOL res;
811 HMODULE NtDllModule;
812 BOOLEAN Enabled;
813 DWORD err;
815 NtDllModule = GetModuleHandle("ntdll.dll");
816 if (!NtDllModule)
818 skip("not running on NT, skipping test\n");
819 return;
821 pRtlAdjustPrivilege = (fnRtlAdjustPrivilege)
822 GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
823 if (!pRtlAdjustPrivilege)
825 skip("missing RtlAdjustPrivilege, skipping test\n");
826 return;
829 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
830 res = InitializeAcl(Acl, 256, ACL_REVISION);
831 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
833 skip("ACLs not implemented - skipping tests\n");
834 HeapFree(GetProcessHeap(), 0, Acl);
835 return;
837 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
839 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
840 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
842 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
843 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
844 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
846 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
847 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
848 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
850 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
852 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
853 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
855 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
856 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
858 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
859 PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
860 PrivSet->PrivilegeCount = 16;
862 res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
863 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
865 pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
867 res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
868 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
870 /* SD without owner/group */
871 SetLastError(0xdeadbeef);
872 Access = AccessStatus = 0xdeadbeef;
873 ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
874 PrivSet, &PrivSetLen, &Access, &AccessStatus);
875 err = GetLastError();
876 ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
877 "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
878 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
879 "Access and/or AccessStatus were changed!\n");
881 /* Set owner and group */
882 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
883 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
884 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
885 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
887 /* Generic access mask */
888 SetLastError(0xdeadbeef);
889 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
890 PrivSet, &PrivSetLen, &Access, &AccessStatus);
891 err = GetLastError();
892 ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
893 "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
894 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
895 "Access and/or AccessStatus were changed!\n");
897 /* sd with no dacl present */
898 ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
899 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
900 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
901 PrivSet, &PrivSetLen, &Access, &AccessStatus);
902 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
903 ok(AccessStatus && (Access == KEY_READ),
904 "AccessCheck failed to grant access with error %d\n",
905 GetLastError());
907 /* sd with NULL dacl */
908 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
909 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
910 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
911 PrivSet, &PrivSetLen, &Access, &AccessStatus);
912 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
913 ok(AccessStatus && (Access == KEY_READ),
914 "AccessCheck failed to grant access with error %d\n",
915 GetLastError());
917 /* sd with blank dacl */
918 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
919 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
920 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
921 PrivSet, &PrivSetLen, &Access, &AccessStatus);
922 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
923 err = GetLastError();
924 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
925 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
926 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
928 res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
929 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
931 res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
932 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
934 /* sd with dacl */
935 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
936 PrivSet, &PrivSetLen, &Access, &AccessStatus);
937 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
938 ok(AccessStatus && (Access == KEY_READ),
939 "AccessCheck failed to grant access with error %d\n",
940 GetLastError());
942 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
943 PrivSet, &PrivSetLen, &Access, &AccessStatus);
944 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
945 ok(AccessStatus,
946 "AccessCheck failed to grant any access with error %d\n",
947 GetLastError());
948 trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
950 /* Access denied by SD */
951 SetLastError(0xdeadbeef);
952 ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
953 PrivSet, &PrivSetLen, &Access, &AccessStatus);
954 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
955 err = GetLastError();
956 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
957 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
958 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
960 SetLastError(0);
961 PrivSet->PrivilegeCount = 16;
962 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
963 PrivSet, &PrivSetLen, &Access, &AccessStatus);
964 ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
965 "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
966 GetLastError());
968 ret = ImpersonateLoggedOnUser(Token);
969 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
970 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
971 if (!ret)
973 SetLastError(0);
974 PrivSet->PrivilegeCount = 16;
975 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
976 PrivSet, &PrivSetLen, &Access, &AccessStatus);
977 ok(ret && AccessStatus && GetLastError() == 0,
978 "AccessCheck should have succeeded, error %d\n",
979 GetLastError());
980 ok(Access == ACCESS_SYSTEM_SECURITY,
981 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
982 Access);
984 else
985 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
986 ret);
987 ret = RevertToSelf();
988 ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
990 /* test INHERIT_ONLY_ACE */
991 ret = InitializeAcl(Acl, 256, ACL_REVISION);
992 ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
994 /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
995 * the next ones.
997 if (pAddAccessAllowedAceEx)
999 ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
1000 ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1002 else
1003 skip("AddAccessAllowedAceEx is not available\n");
1005 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1006 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1007 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1008 err = GetLastError();
1009 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1010 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1011 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1013 CloseHandle(Token);
1015 res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
1016 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1018 SetLastError(0xdeadbeef);
1019 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1020 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1021 err = GetLastError();
1022 ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
1023 "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
1025 CloseHandle(Token);
1027 SetLastError(0xdeadbeef);
1028 ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
1029 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1030 err = GetLastError();
1031 ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
1032 "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
1034 CloseHandle(ProcessToken);
1036 if (EveryoneSid)
1037 FreeSid(EveryoneSid);
1038 if (AdminSid)
1039 FreeSid(AdminSid);
1040 if (UsersSid)
1041 FreeSid(UsersSid);
1042 HeapFree(GetProcessHeap(), 0, Acl);
1043 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1044 HeapFree(GetProcessHeap(), 0, PrivSet);
1047 /* test GetTokenInformation for the various attributes */
1048 static void test_token_attr(void)
1050 HANDLE Token, ImpersonationToken;
1051 DWORD Size;
1052 TOKEN_PRIVILEGES *Privileges;
1053 TOKEN_GROUPS *Groups;
1054 TOKEN_USER *User;
1055 BOOL ret;
1056 DWORD i, GLE;
1057 LPSTR SidString;
1058 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1060 /* cygwin-like use case */
1061 SetLastError(0xdeadbeef);
1062 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1063 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1065 skip("OpenProcessToken is not implemented\n");
1066 return;
1068 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1069 if (ret)
1071 BYTE buf[1024];
1072 Size = sizeof(buf);
1073 ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1074 ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1075 Size = sizeof(ImpersonationLevel);
1076 ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1077 GLE = GetLastError();
1078 ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1079 CloseHandle(Token);
1082 if(!pConvertSidToStringSidA)
1084 skip("ConvertSidToStringSidA is not available\n");
1085 return;
1088 SetLastError(0xdeadbeef);
1089 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &Token);
1090 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1092 /* groups */
1093 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1094 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1095 ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1096 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1097 trace("TokenGroups:\n");
1098 for (i = 0; i < Groups->GroupCount; i++)
1100 DWORD NameLength = 255;
1101 TCHAR Name[255];
1102 DWORD DomainLength = 255;
1103 TCHAR Domain[255];
1104 SID_NAME_USE SidNameUse;
1105 pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1106 Name[0] = '\0';
1107 Domain[0] = '\0';
1108 ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1109 if (ret)
1110 trace("\t%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
1111 else
1112 trace("\t%s, attr: 0x%08x LookupAccountSid failed with error %d\n", SidString, Groups->Groups[i].Attributes, GetLastError());
1113 LocalFree(SidString);
1115 HeapFree(GetProcessHeap(), 0, Groups);
1117 /* user */
1118 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1119 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1120 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1121 User = HeapAlloc(GetProcessHeap(), 0, Size);
1122 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1123 ok(ret,
1124 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1126 pConvertSidToStringSidA(User->User.Sid, &SidString);
1127 trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1128 LocalFree(SidString);
1129 HeapFree(GetProcessHeap(), 0, User);
1131 /* privileges */
1132 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1133 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1134 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1135 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1136 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1137 ok(ret,
1138 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1139 trace("TokenPrivileges:\n");
1140 for (i = 0; i < Privileges->PrivilegeCount; i++)
1142 TCHAR Name[256];
1143 DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
1144 LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1145 trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1147 HeapFree(GetProcessHeap(), 0, Privileges);
1149 ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
1150 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1152 Size = sizeof(ImpersonationLevel);
1153 ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1154 ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1155 ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
1157 CloseHandle(ImpersonationToken);
1158 CloseHandle(Token);
1161 typedef union _MAX_SID
1163 SID sid;
1164 char max[SECURITY_MAX_SID_SIZE];
1165 } MAX_SID;
1167 static void test_sid_str(PSID * sid)
1169 char *str_sid;
1170 BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
1171 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
1172 if (ret)
1174 char account[MAX_PATH], domain[MAX_PATH];
1175 SID_NAME_USE use;
1176 DWORD acc_size = MAX_PATH;
1177 DWORD dom_size = MAX_PATH;
1178 ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
1179 ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
1180 "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
1181 if (ret)
1182 trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
1183 else if (GetLastError() == ERROR_NONE_MAPPED)
1184 trace(" %s couldn't be mapped\n", str_sid);
1185 LocalFree(str_sid);
1189 struct well_known_sid_value
1191 BOOL without_domain;
1192 const char *sid_string;
1193 } well_known_sid_values[] = {
1194 /* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
1195 /* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
1196 /* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
1197 /* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
1198 /* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
1199 /* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
1200 /* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
1201 /* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
1202 /* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
1203 /* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
1204 /* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
1205 /* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
1206 /* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
1207 /* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
1208 /* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
1209 /* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
1210 /* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
1211 /* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
1212 /* Added in Windows Server 2003 */
1213 /* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
1214 /* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
1215 /* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
1216 /* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
1217 /* Added in Windows Vista: */
1218 /* 62 */ {TRUE, "S-1-5-32-568"},
1219 /* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
1220 /* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
1221 /* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
1222 /* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
1223 /* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"}
1226 static void test_CreateWellKnownSid()
1228 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1229 PSID domainsid;
1230 int i;
1232 if (!pCreateWellKnownSid)
1234 skip("CreateWellKnownSid not available\n");
1235 return;
1238 /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
1239 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
1241 for (i = 0; i < sizeof(well_known_sid_values)/sizeof(well_known_sid_values[0]); i++)
1243 struct well_known_sid_value *value = &well_known_sid_values[i];
1244 char sid_buffer[SECURITY_MAX_SID_SIZE];
1245 LPSTR str;
1246 DWORD cb;
1248 if (value->sid_string == NULL)
1249 continue;
1251 if (i > WinAccountRasAndIasServersSid)
1253 /* These SIDs aren't implemented by all Windows versions - detect it and break the loop */
1254 cb = sizeof(sid_buffer);
1255 if (!pCreateWellKnownSid(i, domainsid, sid_buffer, &cb))
1257 skip("Well known SIDs starting from %d are not implemented\n", i);
1258 break;
1262 cb = sizeof(sid_buffer);
1263 ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %d\n", i);
1264 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1265 ok(IsValidSid(sid_buffer), "The sid is not valid\n");
1266 ok(pConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
1267 ok(strcmp(str, value->sid_string) == 0, "SID mismatch - expected %s, got %s\n",
1268 value->sid_string, str);
1269 LocalFree(str);
1271 if (value->without_domain)
1273 char buf2[SECURITY_MAX_SID_SIZE];
1274 cb = sizeof(buf2);
1275 ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %d with optional domain\n", i);
1276 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1277 ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%d)\n", i);
1282 static void test_LookupAccountSid(void)
1284 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1285 CHAR accountA[MAX_PATH], domainA[MAX_PATH];
1286 DWORD acc_sizeA, dom_sizeA;
1287 DWORD real_acc_sizeA, real_dom_sizeA;
1288 WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
1289 DWORD acc_sizeW, dom_sizeW;
1290 DWORD real_acc_sizeW, real_dom_sizeW;
1291 PSID pUsersSid = NULL;
1292 SID_NAME_USE use;
1293 BOOL ret;
1294 DWORD size;
1295 MAX_SID max_sid;
1296 CHAR *str_sidA;
1297 int i;
1299 /* native windows crashes if account size, domain size, or name use is NULL */
1301 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1302 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
1303 ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
1304 "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1306 /* not running on NT so give up */
1307 if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1308 return;
1310 real_acc_sizeA = MAX_PATH;
1311 real_dom_sizeA = MAX_PATH;
1312 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1313 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1315 /* try NULL account */
1316 acc_sizeA = MAX_PATH;
1317 dom_sizeA = MAX_PATH;
1318 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1319 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1321 /* try NULL domain */
1322 acc_sizeA = MAX_PATH;
1323 dom_sizeA = MAX_PATH;
1324 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1325 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1327 /* try a small account buffer */
1328 acc_sizeA = 1;
1329 dom_sizeA = MAX_PATH;
1330 accountA[0] = 0;
1331 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1332 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1333 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1334 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1336 /* try a 0 sized account buffer */
1337 acc_sizeA = 0;
1338 dom_sizeA = MAX_PATH;
1339 accountA[0] = 0;
1340 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1341 /* this can fail or succeed depending on OS version but the size will always be returned */
1342 ok(acc_sizeA == real_acc_sizeA + 1,
1343 "LookupAccountSidA() Expected acc_size = %u, got %u\n",
1344 real_acc_sizeA + 1, acc_sizeA);
1346 /* try a 0 sized account buffer */
1347 acc_sizeA = 0;
1348 dom_sizeA = MAX_PATH;
1349 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1350 /* this can fail or succeed depending on OS version but the size will always be returned */
1351 ok(acc_sizeA == real_acc_sizeA + 1,
1352 "LookupAccountSid() Expected acc_size = %u, got %u\n",
1353 real_acc_sizeA + 1, acc_sizeA);
1355 /* try a small domain buffer */
1356 dom_sizeA = 1;
1357 acc_sizeA = MAX_PATH;
1358 accountA[0] = 0;
1359 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1360 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1361 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1362 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1364 /* try a 0 sized domain buffer */
1365 dom_sizeA = 0;
1366 acc_sizeA = MAX_PATH;
1367 accountA[0] = 0;
1368 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1369 /* this can fail or succeed depending on OS version but the size will always be returned */
1370 ok(dom_sizeA == real_dom_sizeA + 1,
1371 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1372 real_dom_sizeA + 1, dom_sizeA);
1374 /* try a 0 sized domain buffer */
1375 dom_sizeA = 0;
1376 acc_sizeA = MAX_PATH;
1377 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1378 /* this can fail or succeed depending on OS version but the size will always be returned */
1379 ok(dom_sizeA == real_dom_sizeA + 1,
1380 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1381 real_dom_sizeA + 1, dom_sizeA);
1383 real_acc_sizeW = MAX_PATH;
1384 real_dom_sizeW = MAX_PATH;
1385 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
1386 ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
1388 /* try an invalid system name */
1389 real_acc_sizeA = MAX_PATH;
1390 real_dom_sizeA = MAX_PATH;
1391 ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1392 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1393 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
1394 "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
1396 /* native windows crashes if domainW or accountW is NULL */
1398 /* try a small account buffer */
1399 acc_sizeW = 1;
1400 dom_sizeW = MAX_PATH;
1401 accountW[0] = 0;
1402 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1403 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1404 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1405 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1407 /* try a 0 sized account buffer */
1408 acc_sizeW = 0;
1409 dom_sizeW = MAX_PATH;
1410 accountW[0] = 0;
1411 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1412 /* this can fail or succeed depending on OS version but the size will always be returned */
1413 ok(acc_sizeW == real_acc_sizeW + 1,
1414 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1415 real_acc_sizeW + 1, acc_sizeW);
1417 /* try a 0 sized account buffer */
1418 acc_sizeW = 0;
1419 dom_sizeW = MAX_PATH;
1420 ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1421 /* this can fail or succeed depending on OS version but the size will always be returned */
1422 ok(acc_sizeW == real_acc_sizeW + 1,
1423 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1424 real_acc_sizeW + 1, acc_sizeW);
1426 /* try a small domain buffer */
1427 dom_sizeW = 1;
1428 acc_sizeW = MAX_PATH;
1429 accountW[0] = 0;
1430 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1431 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1432 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1433 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1435 /* try a 0 sized domain buffer */
1436 dom_sizeW = 0;
1437 acc_sizeW = MAX_PATH;
1438 accountW[0] = 0;
1439 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1440 /* this can fail or succeed depending on OS version but the size will always be returned */
1441 ok(dom_sizeW == real_dom_sizeW + 1,
1442 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1443 real_dom_sizeW + 1, dom_sizeW);
1445 /* try a 0 sized domain buffer */
1446 dom_sizeW = 0;
1447 acc_sizeW = MAX_PATH;
1448 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1449 /* this can fail or succeed depending on OS version but the size will always be returned */
1450 ok(dom_sizeW == real_dom_sizeW + 1,
1451 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1452 real_dom_sizeW + 1, dom_sizeW);
1454 FreeSid(pUsersSid);
1456 if (pCreateWellKnownSid && pConvertSidToStringSidA)
1458 trace("Well Known SIDs:\n");
1459 for (i = 0; i <= 60; i++)
1461 size = SECURITY_MAX_SID_SIZE;
1462 if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
1464 if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1466 acc_sizeA = MAX_PATH;
1467 dom_sizeA = MAX_PATH;
1468 if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
1469 trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
1470 LocalFree(str_sidA);
1473 else
1475 if (GetLastError() != ERROR_INVALID_PARAMETER)
1476 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1477 else
1478 trace(" %d: not supported\n", i);
1482 pLsaQueryInformationPolicy = (fnLsaQueryInformationPolicy)GetProcAddress( hmod, "LsaQueryInformationPolicy");
1483 pLsaOpenPolicy = (fnLsaOpenPolicy)GetProcAddress( hmod, "LsaOpenPolicy");
1484 pLsaFreeMemory = (fnLsaFreeMemory)GetProcAddress( hmod, "LsaFreeMemory");
1485 pLsaClose = (fnLsaClose)GetProcAddress( hmod, "LsaClose");
1487 if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
1489 NTSTATUS status;
1490 LSA_HANDLE handle;
1491 LSA_OBJECT_ATTRIBUTES object_attributes;
1493 ZeroMemory(&object_attributes, sizeof(object_attributes));
1494 object_attributes.Length = sizeof(object_attributes);
1496 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1497 ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1498 "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1500 /* try a more restricted access mask if necessary */
1501 if (status == STATUS_ACCESS_DENIED) {
1502 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
1503 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1504 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
1507 if (status == STATUS_SUCCESS)
1509 PPOLICY_ACCOUNT_DOMAIN_INFO info;
1510 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
1511 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
1512 if (status == STATUS_SUCCESS)
1514 ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
1515 if (info->DomainSid)
1517 int count = *GetSidSubAuthorityCount(info->DomainSid);
1518 CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
1519 test_sid_str((PSID)&max_sid.sid);
1520 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
1521 max_sid.sid.SubAuthorityCount = count + 1;
1522 test_sid_str((PSID)&max_sid.sid);
1523 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
1524 test_sid_str((PSID)&max_sid.sid);
1525 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
1526 test_sid_str((PSID)&max_sid.sid);
1527 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
1528 test_sid_str((PSID)&max_sid.sid);
1529 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
1530 test_sid_str((PSID)&max_sid.sid);
1531 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
1532 test_sid_str((PSID)&max_sid.sid);
1533 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
1534 test_sid_str((PSID)&max_sid.sid);
1535 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
1536 test_sid_str((PSID)&max_sid.sid);
1537 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
1538 test_sid_str((PSID)&max_sid.sid);
1539 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
1540 test_sid_str((PSID)&max_sid.sid);
1541 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
1542 test_sid_str((PSID)&max_sid.sid);
1543 max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
1544 test_sid_str((PSID)&max_sid.sid);
1545 max_sid.sid.SubAuthority[count] = 1000; /* first user account */
1546 test_sid_str((PSID)&max_sid.sid);
1549 pLsaFreeMemory((LPVOID)info);
1552 status = pLsaClose(handle);
1553 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
1559 static void get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
1561 static CHAR account[UNLEN + 1];
1562 static CHAR domain[UNLEN + 1];
1563 DWORD size, dom_size;
1564 SID_NAME_USE use;
1566 *user = account;
1567 *dom = domain;
1569 size = dom_size = UNLEN + 1;
1570 account[0] = '\0';
1571 domain[0] = '\0';
1572 LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
1575 static void test_LookupAccountName(void)
1577 DWORD sid_size, domain_size, user_size;
1578 DWORD sid_save, domain_save;
1579 CHAR user_name[UNLEN + 1];
1580 SID_NAME_USE sid_use;
1581 LPSTR domain, account, sid_dom;
1582 PSID psid;
1583 BOOL ret;
1585 /* native crashes if (assuming all other parameters correct):
1586 * - peUse is NULL
1587 * - Sid is NULL and cbSid is > 0
1588 * - cbSid or cchReferencedDomainName are NULL
1589 * - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
1592 user_size = UNLEN + 1;
1593 SetLastError(0xdeadbeef);
1594 ret = GetUserNameA(user_name, &user_size);
1595 if (!ret && (GetLastError() == ERROR_NOT_LOGGED_ON))
1597 /* Probably on win9x where the user used 'Cancel' instead of properly logging in */
1598 skip("Cannot get the user name (win9x and not logged in properly)\n");
1599 return;
1601 ok(ret, "Failed to get user name : %d\n", GetLastError());
1603 /* get sizes */
1604 sid_size = 0;
1605 domain_size = 0;
1606 sid_use = 0xcafebabe;
1607 SetLastError(0xdeadbeef);
1608 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
1609 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1611 skip("LookupAccountNameA is not implemented\n");
1612 return;
1614 ok(!ret, "Expected 0, got %d\n", ret);
1615 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1616 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1617 ok(sid_size != 0, "Expected non-zero sid size\n");
1618 ok(domain_size != 0, "Expected non-zero domain size\n");
1619 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1621 sid_save = sid_size;
1622 domain_save = domain_size;
1624 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1625 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1627 /* try valid account name */
1628 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
1629 get_sid_info(psid, &account, &sid_dom);
1630 ok(ret, "Failed to lookup account name\n");
1631 ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
1632 todo_wine
1634 ok(!lstrcmp(account, user_name), "Expected %s, got %s\n", user_name, account);
1635 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1637 ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
1638 ok(lstrlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
1639 ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
1640 domain_size = domain_save;
1641 sid_size = sid_save;
1643 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
1645 skip("Non-english locale (test with hardcoded 'Everyone')\n");
1647 else
1649 ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
1650 get_sid_info(psid, &account, &sid_dom);
1651 ok(ret, "Failed to lookup account name\n");
1652 ok(sid_size != 0, "sid_size was zero\n");
1653 ok(!lstrcmp(account, "Everyone"), "Expected Everyone, got %s\n", account);
1654 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1655 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
1656 ok(lstrlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
1657 ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
1658 domain_size = domain_save;
1661 /* NULL Sid with zero sid size */
1662 SetLastError(0xdeadbeef);
1663 sid_size = 0;
1664 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1665 ok(!ret, "Expected 0, got %d\n", ret);
1666 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1667 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1668 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1669 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1671 /* try cchReferencedDomainName - 1 */
1672 SetLastError(0xdeadbeef);
1673 domain_size--;
1674 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1675 ok(!ret, "Expected 0, got %d\n", ret);
1676 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1677 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1678 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1679 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1681 /* NULL ReferencedDomainName with zero domain name size */
1682 SetLastError(0xdeadbeef);
1683 domain_size = 0;
1684 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
1685 ok(!ret, "Expected 0, got %d\n", ret);
1686 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1687 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1688 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1689 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1691 HeapFree(GetProcessHeap(), 0, psid);
1692 HeapFree(GetProcessHeap(), 0, domain);
1694 /* get sizes for NULL account name */
1695 sid_size = 0;
1696 domain_size = 0;
1697 sid_use = 0xcafebabe;
1698 SetLastError(0xdeadbeef);
1699 ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
1700 ok(!ret, "Expected 0, got %d\n", ret);
1701 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1702 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1703 ok(sid_size != 0, "Expected non-zero sid size\n");
1704 ok(domain_size != 0, "Expected non-zero domain size\n");
1705 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1707 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1708 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1710 /* try NULL account name */
1711 ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
1712 get_sid_info(psid, &account, &sid_dom);
1713 ok(ret, "Failed to lookup account name\n");
1714 /* Using a fixed string will not work on different locales */
1715 ok(!lstrcmp(account, domain),
1716 "Got %s for account and %s for domain, these should be the same\n",
1717 account, domain);
1718 ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
1720 /* try an invalid account name */
1721 SetLastError(0xdeadbeef);
1722 sid_size = 0;
1723 domain_size = 0;
1724 ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
1725 ok(!ret, "Expected 0, got %d\n", ret);
1726 ok(GetLastError() == ERROR_NONE_MAPPED ||
1727 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
1728 "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
1729 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
1730 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
1732 /* try an invalid system name */
1733 SetLastError(0xdeadbeef);
1734 sid_size = 0;
1735 domain_size = 0;
1736 ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
1737 ok(!ret, "Expected 0, got %d\n", ret);
1738 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
1739 "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
1740 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
1741 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
1743 HeapFree(GetProcessHeap(), 0, psid);
1744 HeapFree(GetProcessHeap(), 0, domain);
1747 static void test_security_descriptor(void)
1749 SECURITY_DESCRIPTOR sd;
1750 char buf[8192];
1751 DWORD size;
1752 BOOL isDefault, isPresent, ret;
1753 PACL pacl;
1754 PSID psid;
1756 SetLastError(0xdeadbeef);
1757 ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
1758 if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1760 skip("InitializeSecurityDescriptor is not implemented\n");
1761 return;
1764 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
1765 expect_eq(psid, NULL, PSID, "%p");
1766 expect_eq(isDefault, FALSE, BOOL, "%d");
1767 sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
1769 SetLastError(0xdeadbeef);
1770 size = 5;
1771 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
1772 expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
1773 ok(size > 5, "Size not increased\n");
1774 if (size <= 8192)
1776 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
1777 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
1778 expect_eq(psid, NULL, PSID, "%p");
1779 expect_eq(isDefault, FALSE, BOOL, "%d");
1780 ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
1781 expect_eq(psid, NULL, PSID, "%p");
1782 expect_eq(isDefault, FALSE, BOOL, "%d");
1783 ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
1784 expect_eq(isPresent, TRUE, BOOL, "%d");
1785 expect_eq(psid, NULL, PSID, "%p");
1786 expect_eq(isDefault, FALSE, BOOL, "%d");
1787 ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
1788 expect_eq(isPresent, TRUE, BOOL, "%d");
1789 expect_eq(psid, NULL, PSID, "%p");
1790 expect_eq(isDefault, FALSE, BOOL, "%d");
1794 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
1795 #define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
1796 static void test_granted_access(HANDLE handle, ACCESS_MASK access,
1797 ACCESS_MASK alt, int line)
1799 OBJECT_BASIC_INFORMATION obj_info;
1800 NTSTATUS status;
1802 if (!pNtQueryObject)
1804 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
1805 return;
1808 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
1809 sizeof(obj_info), NULL );
1810 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
1811 if (alt)
1812 ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
1813 obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
1814 "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
1815 else
1816 ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
1817 "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
1820 #define CHECK_SET_SECURITY(o,i,e) \
1821 do{ \
1822 BOOL res; \
1823 DWORD err; \
1824 SetLastError( 0xdeadbeef ); \
1825 res = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
1826 err = GetLastError(); \
1827 if (e == ERROR_SUCCESS) \
1828 ok(res, "SetKernelObjectSecurity failed with %d\n", err); \
1829 else \
1830 ok(!res && err == e, "SetKernelObjectSecurity should have failed " \
1831 "with %s, instead of %d\n", #e, err); \
1832 }while(0)
1834 static void test_process_security(void)
1836 BOOL res;
1837 char owner[32], group[32];
1838 PSID AdminSid = NULL, UsersSid = NULL;
1839 PACL Acl = NULL;
1840 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
1841 char buffer[MAX_PATH];
1842 PROCESS_INFORMATION info;
1843 STARTUPINFOA startup;
1844 SECURITY_ATTRIBUTES psa;
1845 HANDLE token, event;
1846 DWORD tmp;
1848 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
1849 res = InitializeAcl(Acl, 256, ACL_REVISION);
1850 if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1852 skip("ACLs not implemented - skipping tests\n");
1853 HeapFree(GetProcessHeap(), 0, Acl);
1854 return;
1856 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
1858 /* get owner from the token we might be running as a user not admin */
1859 res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
1860 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
1861 if (!res)
1863 HeapFree(GetProcessHeap(), 0, Acl);
1864 return;
1867 res = GetTokenInformation( token, TokenOwner, owner, sizeof(owner), &tmp );
1868 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
1869 AdminSid = ((TOKEN_OWNER*)owner)->Owner;
1870 res = GetTokenInformation( token, TokenPrimaryGroup, group, sizeof(group), &tmp );
1871 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
1872 UsersSid = ((TOKEN_PRIMARY_GROUP*)group)->PrimaryGroup;
1874 CloseHandle( token );
1875 if (!res)
1877 HeapFree(GetProcessHeap(), 0, Acl);
1878 return;
1881 res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
1882 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1883 res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
1884 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1886 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
1887 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1888 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
1890 event = CreateEvent( NULL, TRUE, TRUE, "test_event" );
1891 ok(event != NULL, "CreateEvent %d\n", GetLastError());
1893 SecurityDescriptor->Revision = 0;
1894 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
1895 SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
1897 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
1898 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
1899 CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
1900 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
1901 /* NULL DACL is valid and means default DACL from token */
1902 SecurityDescriptor->Control |= SE_DACL_PRESENT;
1903 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
1905 /* Set owner and group and dacl */
1906 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
1907 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
1908 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
1909 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
1910 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
1911 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
1912 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1913 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1914 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
1916 sprintf(buffer, "%s tests/security.c test", myARGV[0]);
1917 memset(&startup, 0, sizeof(startup));
1918 startup.cb = sizeof(startup);
1919 startup.dwFlags = STARTF_USESHOWWINDOW;
1920 startup.wShowWindow = SW_SHOWNORMAL;
1922 psa.nLength = sizeof(psa);
1923 psa.lpSecurityDescriptor = SecurityDescriptor;
1924 psa.bInheritHandle = TRUE;
1926 /* Doesn't matter what ACL say we should get full access for ourselves */
1927 ok(CreateProcessA( NULL, buffer, &psa, NULL, FALSE, 0, NULL, NULL, &startup, &info ),
1928 "CreateProcess with err:%d\n", GetLastError());
1929 TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS,
1930 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
1931 winetest_wait_child_process( info.hProcess );
1933 CloseHandle( info.hProcess );
1934 CloseHandle( info.hThread );
1935 CloseHandle( event );
1936 HeapFree(GetProcessHeap(), 0, Acl);
1937 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1940 static void test_process_security_child(void)
1942 HANDLE handle, handle1;
1943 BOOL ret;
1944 DWORD err;
1946 handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
1947 ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
1948 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
1950 ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
1951 &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS ),
1952 "duplicating handle err:%d\n", GetLastError());
1953 TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
1955 CloseHandle( handle1 );
1957 SetLastError( 0xdeadbeef );
1958 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
1959 &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
1960 err = GetLastError();
1961 todo_wine
1962 ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
1963 "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
1965 CloseHandle( handle );
1967 /* These two should fail - they are denied by ACL */
1968 handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
1969 todo_wine
1970 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
1971 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
1972 todo_wine
1973 ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
1975 /* Documented privilege elevation */
1976 ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
1977 &handle, 0, TRUE, DUPLICATE_SAME_ACCESS ),
1978 "duplicating handle err:%d\n", GetLastError());
1979 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS,
1980 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
1982 CloseHandle( handle );
1984 /* Same only explicitly asking for all access rights */
1985 ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
1986 &handle, PROCESS_ALL_ACCESS, TRUE, 0 ),
1987 "duplicating handle err:%d\n", GetLastError());
1988 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS,
1989 PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
1990 ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
1991 &handle1, PROCESS_VM_READ, TRUE, 0 ),
1992 "duplicating handle err:%d\n", GetLastError());
1993 TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
1994 CloseHandle( handle1 );
1995 CloseHandle( handle );
1998 static void test_impersonation_level(void)
2000 HANDLE Token, ProcessToken;
2001 HANDLE Token2;
2002 DWORD Size;
2003 TOKEN_PRIVILEGES *Privileges;
2004 TOKEN_USER *User;
2005 PRIVILEGE_SET *PrivilegeSet;
2006 BOOL AccessGranted;
2007 BOOL ret;
2008 HKEY hkey;
2009 DWORD error;
2011 pDuplicateTokenEx = (fnDuplicateTokenEx) GetProcAddress(hmod, "DuplicateTokenEx");
2012 if( !pDuplicateTokenEx ) {
2013 skip("DuplicateTokenEx is not available\n");
2014 return;
2016 SetLastError(0xdeadbeef);
2017 ret = ImpersonateSelf(SecurityAnonymous);
2018 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2020 skip("ImpersonateSelf is not implemented\n");
2021 return;
2023 ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
2024 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2025 ok(!ret, "OpenThreadToken should have failed\n");
2026 error = GetLastError();
2027 ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2028 /* can't perform access check when opening object against an anonymous impersonation token */
2029 todo_wine {
2030 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2031 ok(error == ERROR_INVALID_HANDLE, "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE instead of %d\n", error);
2033 RevertToSelf();
2035 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
2036 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
2038 ret = pDuplicateTokenEx(ProcessToken,
2039 TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
2040 SecurityAnonymous, TokenImpersonation, &Token);
2041 ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
2042 /* can't increase the impersonation level */
2043 ret = DuplicateToken(Token, SecurityIdentification, &Token2);
2044 error = GetLastError();
2045 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
2046 "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2047 /* we can query anything from an anonymous token, including the user */
2048 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
2049 error = GetLastError();
2050 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2051 User = HeapAlloc(GetProcessHeap(), 0, Size);
2052 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
2053 ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
2054 HeapFree(GetProcessHeap(), 0, User);
2056 /* PrivilegeCheck fails with SecurityAnonymous level */
2057 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
2058 error = GetLastError();
2059 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2060 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
2061 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
2062 ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
2064 PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
2065 PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
2066 memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
2067 PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
2068 HeapFree(GetProcessHeap(), 0, Privileges);
2070 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2071 error = GetLastError();
2072 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2074 CloseHandle(Token);
2076 ret = ImpersonateSelf(SecurityIdentification);
2077 ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
2078 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2079 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2081 /* can't perform access check when opening object against an identification impersonation token */
2082 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2083 todo_wine {
2084 ok(error == ERROR_INVALID_HANDLE, "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE instead of %d\n", error);
2086 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2087 ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
2088 CloseHandle(Token);
2089 RevertToSelf();
2091 ret = ImpersonateSelf(SecurityImpersonation);
2092 ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
2093 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2094 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2095 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2096 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
2097 RegCloseKey(hkey);
2098 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2099 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
2100 RevertToSelf();
2102 CloseHandle(Token);
2103 CloseHandle(ProcessToken);
2105 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
2108 static void test_SetEntriesInAcl(void)
2110 DWORD res;
2111 PSID EveryoneSid = NULL, UsersSid = NULL;
2112 PACL OldAcl = NULL, NewAcl;
2113 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2114 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2115 EXPLICIT_ACCESSW ExplicitAccess;
2116 static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
2118 if (!pSetEntriesInAclW)
2120 skip("SetEntriesInAclW is not available\n");
2121 return;
2124 NewAcl = (PACL)0xdeadbeef;
2125 res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
2126 if(res == ERROR_CALL_NOT_IMPLEMENTED)
2128 skip("SetEntriesInAclW is not implemented\n");
2129 return;
2131 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2132 ok(NewAcl == NULL, "NewAcl=%p, expected NULL\n", NewAcl);
2134 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
2135 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
2136 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2138 skip("ACLs not implemented - skipping tests\n");
2139 HeapFree(GetProcessHeap(), 0, OldAcl);
2140 return;
2142 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2144 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2145 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2147 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2148 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
2149 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2151 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
2152 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2154 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
2155 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
2156 ExplicitAccess.grfInheritance = NO_INHERITANCE;
2157 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2158 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2159 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2160 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
2161 ExplicitAccess.Trustee.ptstrName = (LPWSTR)EveryoneSid;
2162 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2163 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2164 ok(NewAcl != NULL, "returned acl was NULL\n");
2165 LocalFree(NewAcl);
2167 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
2169 skip("Non-english locale (test with hardcoded 'Everyone')\n");
2171 else
2173 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2174 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
2175 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2176 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2177 ok(NewAcl != NULL, "returned acl was NULL\n");
2178 LocalFree(NewAcl);
2180 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
2181 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2182 ok(res == ERROR_INVALID_PARAMETER, "SetEntriesInAclW failed: %u\n", res);
2183 ok(NewAcl == NULL, "returned acl wasn't NULL: %p\n", NewAcl);
2184 LocalFree(NewAcl);
2186 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2187 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
2188 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2189 ok(res == ERROR_INVALID_PARAMETER, "SetEntriesInAclW failed: %u\n", res);
2190 ok(NewAcl == NULL, "returned acl wasn't NULL: %p\n", NewAcl);
2191 LocalFree(NewAcl);
2193 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2194 ExplicitAccess.grfAccessMode = SET_ACCESS;
2195 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2196 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2197 ok(NewAcl != NULL, "returned acl was NULL\n");
2198 LocalFree(NewAcl);
2201 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
2202 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2203 ExplicitAccess.Trustee.ptstrName = (LPWSTR)UsersSid;
2204 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2205 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2206 ok(NewAcl != NULL, "returned acl was NULL\n");
2207 LocalFree(NewAcl);
2209 LocalFree(UsersSid);
2210 LocalFree(EveryoneSid);
2211 HeapFree(GetProcessHeap(), 0, OldAcl);
2214 static void test_GetNamedSecurityInfoA(void)
2216 PSECURITY_DESCRIPTOR pSecDesc;
2217 DWORD revision;
2218 SECURITY_DESCRIPTOR_CONTROL control;
2219 PSID owner;
2220 PSID group;
2221 BOOL owner_defaulted;
2222 BOOL group_defaulted;
2223 DWORD error;
2224 BOOL ret;
2225 CHAR windows_dir[MAX_PATH];
2227 if (!pGetNamedSecurityInfoA)
2229 skip("GetNamedSecurityInfoA is not available\n");
2230 return;
2233 ret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
2234 ok(ret, "GetWindowsDirectory failed with error %d\n", GetLastError());
2236 SetLastError(0xdeadbeef);
2237 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
2238 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
2239 NULL, NULL, NULL, NULL, &pSecDesc);
2240 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2242 skip("GetNamedSecurityInfoA is not implemented\n");
2243 return;
2245 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
2247 ret = GetSecurityDescriptorControl(pSecDesc, &control, &revision);
2248 ok(ret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
2249 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT),
2250 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
2251 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
2252 ret = GetSecurityDescriptorOwner(pSecDesc, &owner, &owner_defaulted);
2253 ok(ret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2254 ok(owner != NULL, "owner should not be NULL\n");
2255 ret = GetSecurityDescriptorGroup(pSecDesc, &group, &group_defaulted);
2256 ok(ret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2257 ok(group != NULL, "group should not be NULL\n");
2260 static void test_ConvertStringSecurityDescriptor(void)
2262 BOOL ret;
2263 PSECURITY_DESCRIPTOR pSD;
2264 static const WCHAR Blank[] = { 0 };
2266 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
2268 skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
2269 return;
2272 SetLastError(0xdeadbeef);
2273 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2274 "D:(A;;GA;;;WD)", 0xdeadbeef, &pSD, NULL);
2275 ok(!ret && GetLastError() == ERROR_UNKNOWN_REVISION,
2276 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_UNKNOWN_REVISION instead of %d\n",
2277 GetLastError());
2279 /* test ACE string type */
2280 SetLastError(0xdeadbeef);
2281 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2282 "D:(A;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2283 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2284 LocalFree(pSD);
2286 SetLastError(0xdeadbeef);
2287 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2288 "D:(D;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2289 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2290 LocalFree(pSD);
2292 SetLastError(0xdeadbeef);
2293 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2294 "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2295 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2296 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2297 GetLastError());
2299 /* test ACE string access rights */
2300 SetLastError(0xdeadbeef);
2301 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2302 "D:(A;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2303 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2304 LocalFree(pSD);
2305 SetLastError(0xdeadbeef);
2306 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2307 "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2308 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2309 LocalFree(pSD);
2310 SetLastError(0xdeadbeef);
2311 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2312 "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2313 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2314 LocalFree(pSD);
2315 SetLastError(0xdeadbeef);
2316 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2317 "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2318 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2319 LocalFree(pSD);
2320 SetLastError(0xdeadbeef);
2321 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2322 "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2323 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2324 LocalFree(pSD);
2325 SetLastError(0xdeadbeef);
2326 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2327 "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2328 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2329 LocalFree(pSD);
2330 SetLastError(0xdeadbeef);
2331 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2332 "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2333 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2334 LocalFree(pSD);
2335 SetLastError(0xdeadbeef);
2336 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2337 "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2338 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2339 LocalFree(pSD);
2341 /* test ACE string access right error case */
2342 SetLastError(0xdeadbeef);
2343 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2344 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2345 ok(!ret && GetLastError() == ERROR_INVALID_ACL,
2346 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_ACL instead of %d\n",
2347 GetLastError());
2349 /* test behaviour with NULL parameters */
2350 SetLastError(0xdeadbeef);
2351 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2352 NULL, 0xdeadbeef, &pSD, NULL);
2353 todo_wine
2354 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2355 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2356 GetLastError());
2358 SetLastError(0xdeadbeef);
2359 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
2360 NULL, 0xdeadbeef, &pSD, NULL);
2361 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2362 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2363 GetLastError());
2365 SetLastError(0xdeadbeef);
2366 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2367 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
2368 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2369 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2370 GetLastError());
2372 SetLastError(0xdeadbeef);
2373 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2374 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
2375 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2376 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2377 GetLastError());
2379 /* test behaviour with empty strings */
2380 SetLastError(0xdeadbeef);
2381 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2382 "", SDDL_REVISION_1, &pSD, NULL);
2383 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2385 SetLastError(0xdeadbeef);
2386 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
2387 Blank, SDDL_REVISION_1, &pSD, NULL);
2388 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2390 /* test ACE string SID */
2391 SetLastError(0xdeadbeef);
2392 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2393 "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, &pSD, NULL);
2394 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2395 LocalFree(pSD);
2397 SetLastError(0xdeadbeef);
2398 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2399 "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, &pSD, NULL);
2400 ok(!ret, "Expected failure, got %d\n", ret);
2401 ok(GetLastError() == ERROR_INVALID_ACL || GetLastError() == ERROR_INVALID_SID,
2402 "Expected ERROR_INVALID_ACL or ERROR_INVALID_SID, got %d\n", GetLastError());
2405 static void test_ConvertSecurityDescriptorToString()
2407 SECURITY_DESCRIPTOR desc;
2408 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
2409 LPSTR string;
2410 DWORD size;
2411 PSID psid, psid2;
2412 PACL pacl;
2413 char sid_buf[256];
2414 char acl_buf[8192];
2415 ULONG len;
2417 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
2419 skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
2420 return;
2422 if (!pCreateWellKnownSid)
2424 skip("CreateWellKnownSid is not available\n");
2425 return;
2428 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
2429 * don't replicate this feature so we only test len >= strlen+1. */
2430 #define CHECK_RESULT_AND_FREE(exp_str) \
2431 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
2432 ok(len >= (lstrlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(exp_str) + 1, len); \
2433 LocalFree(string);
2435 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
2436 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); \
2437 ok(len >= (strlen(string) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(string) + 1, len); \
2438 LocalFree(string);
2440 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
2441 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2442 CHECK_RESULT_AND_FREE("");
2444 size = 4096;
2445 pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
2446 SetSecurityDescriptorOwner(&desc, (PSID)sid_buf, FALSE);
2447 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2448 CHECK_RESULT_AND_FREE("O:S-1-2-0");
2450 SetSecurityDescriptorOwner(&desc, (PSID)sid_buf, TRUE);
2451 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2452 CHECK_RESULT_AND_FREE("O:S-1-2-0");
2454 size = sizeof(sid_buf);
2455 pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
2456 SetSecurityDescriptorOwner(&desc, (PSID)sid_buf, TRUE);
2457 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2458 CHECK_RESULT_AND_FREE("O:SY");
2460 pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
2461 SetSecurityDescriptorGroup(&desc, psid, TRUE);
2462 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2463 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
2465 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
2466 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
2468 pacl = (PACL)acl_buf;
2469 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
2470 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
2471 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2472 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
2474 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
2475 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2476 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
2478 pConvertStringSidToSidA("S-1-5-6", &psid2);
2479 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
2480 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2481 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
2483 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
2484 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2485 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
2487 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
2488 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2489 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)");
2492 pacl = (PACL)acl_buf;
2493 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
2494 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
2495 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2496 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
2498 /* fails in win2k */
2499 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
2500 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
2501 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
2503 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
2504 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
2507 /* fails in win2k */
2508 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
2509 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
2511 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
2512 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
2516 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
2518 SECURITY_DESCRIPTOR_CONTROL ref;
2519 SECURITY_DESCRIPTOR_CONTROL test;
2521 SECURITY_DESCRIPTOR_CONTROL const mutable
2522 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
2523 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
2524 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
2525 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
2527 SECURITY_DESCRIPTOR_CONTROL const immutable
2528 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
2529 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
2530 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
2531 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
2534 int bit;
2535 DWORD dwRevision;
2536 LPCSTR fmt = "Expected error %s, got %u\n";
2538 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
2540 /* The mutable bits are mutable regardless of the truth of
2541 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
2543 /* Check call barfs if any bit-of-interest is immutable */
2544 for (bit = 0; bit < 16; ++bit)
2546 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
2547 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
2549 SECURITY_DESCRIPTOR_CONTROL ctrl;
2551 DWORD dwExpect = (bitOfInterest & immutable)
2552 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
2553 LPCSTR strExpect = (bitOfInterest & immutable)
2554 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
2556 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
2557 setOrClear ^= bitOfInterest;
2558 SetLastError (0xbebecaca);
2559 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
2560 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2561 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2562 expect_eq(test, ctrl, int, "%x");
2564 ctrl = ref;
2565 setOrClear ^= bitOfInterest;
2566 SetLastError (0xbebecaca);
2567 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
2568 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2569 GetSecurityDescriptorControl (sec, &test, &dwRevision);
2570 expect_eq(test, ref, int, "%x");
2573 /* Check call barfs if any bit-to-set is immutable
2574 even when not a bit-of-interest */
2575 for (bit = 0; bit < 16; ++bit)
2577 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
2578 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
2580 SECURITY_DESCRIPTOR_CONTROL ctrl;
2582 DWORD dwExpect = ((1 << bit) & immutable)
2583 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
2584 LPCSTR strExpect = ((1 << bit) & immutable)
2585 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
2587 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
2588 setOrClear ^= bitsOfInterest;
2589 SetLastError (0xbebecaca);
2590 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
2591 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2592 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2593 expect_eq(test, ctrl, int, "%x");
2595 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
2596 setOrClear ^= bitsOfInterest;
2597 SetLastError (0xbebecaca);
2598 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
2599 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2600 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2601 expect_eq(test, ctrl, int, "%x");
2605 static void test_PrivateObjectSecurity(void)
2607 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
2608 SECURITY_DESCRIPTOR_CONTROL ctrl;
2609 PSECURITY_DESCRIPTOR sec;
2610 DWORD dwDescSize;
2611 DWORD dwRevision;
2612 DWORD retSize;
2613 LPSTR string;
2614 ULONG len;
2615 PSECURITY_DESCRIPTOR buf;
2617 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
2619 skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
2620 return;
2623 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
2624 "O:SY"
2625 "G:S-1-5-21-93476-23408-4576"
2626 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
2627 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
2628 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
2629 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
2631 test_SetSecurityDescriptorControl(sec);
2633 LocalFree(sec);
2635 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
2636 "O:SY"
2637 "G:S-1-5-21-93476-23408-4576",
2638 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
2640 test_SetSecurityDescriptorControl(sec);
2642 LocalFree(sec);
2644 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
2645 "O:SY"
2646 "G:S-1-5-21-93476-23408-4576"
2647 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
2648 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
2649 buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
2650 pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
2651 GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
2652 expect_eq(ctrl, 0x9014, int, "%x");
2654 ok(GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize),
2655 "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
2656 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
2657 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2658 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
2659 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
2660 expect_eq(ctrl, 0x8000, int, "%x");
2662 ok(GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize),
2663 "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
2664 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
2665 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed err=%u\n", GetLastError());
2666 CHECK_RESULT_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)");
2667 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
2668 expect_eq(ctrl, 0x8004, int, "%x");
2670 ok(GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize),
2671 "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
2672 ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
2673 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2674 CHECK_RESULT_AND_FREE("O:SY"
2675 "G:S-1-5-21-93476-23408-4576"
2676 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
2677 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)");
2678 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
2679 expect_eq(ctrl, 0x8014, int, "%x");
2681 SetLastError(0xdeadbeef);
2682 ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
2683 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
2685 LocalFree(sec);
2686 HeapFree(GetProcessHeap(), 0, buf);
2688 #undef CHECK_RESULT_AND_FREE
2689 #undef CHECK_ONE_OF_AND_FREE
2691 static void test_acls(void)
2693 char buffer[256];
2694 PACL pAcl = (PACL)buffer;
2695 BOOL ret;
2697 SetLastError(0xdeadbeef);
2698 ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
2699 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2701 skip("InitializeAcl is not implemented\n");
2702 return;
2705 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
2707 SetLastError(0xdeadbeef);
2708 ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
2709 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
2711 SetLastError(0xdeadbeef);
2712 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
2713 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
2715 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
2716 ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
2718 ret = IsValidAcl(pAcl);
2719 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
2721 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
2722 ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
2724 ret = IsValidAcl(pAcl);
2725 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
2727 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
2728 ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
2730 ret = IsValidAcl(pAcl);
2731 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
2733 SetLastError(0xdeadbeef);
2734 ret = InitializeAcl(pAcl, sizeof(buffer), -1);
2735 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
2738 static void test_GetSecurityInfo(void)
2740 HANDLE obj;
2741 PSECURITY_DESCRIPTOR sd;
2742 PSID owner, group;
2743 PACL dacl;
2744 DWORD ret;
2746 if (!pGetSecurityInfo)
2748 win_skip("GetSecurityInfo is not available\n");
2749 return;
2752 /* Create something. Files have lots of associated security info. */
2753 obj = CreateFile(myARGV[0], GENERIC_READ, FILE_SHARE_READ, NULL,
2754 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2755 if (obj == INVALID_HANDLE_VALUE)
2757 skip("Couldn't create an object for GetSecurityInfo test\n");
2758 return;
2761 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
2762 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
2763 &owner, &group, &dacl, NULL, &sd);
2764 if (ret == ERROR_CALL_NOT_IMPLEMENTED)
2766 win_skip("GetSecurityInfo is not implemented\n");
2767 CloseHandle(obj);
2768 return;
2770 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
2771 ok(sd != NULL, "GetSecurityInfo\n");
2772 ok(owner != NULL, "GetSecurityInfo\n");
2773 ok(group != NULL, "GetSecurityInfo\n");
2774 ok(dacl != NULL, "GetSecurityInfo\n");
2775 ok(IsValidAcl(dacl), "GetSecurityInfo\n");
2777 LocalFree(sd);
2779 /* If we don't ask for the security descriptor, Windows will still give us
2780 the other stuff, leaving us no way to free it. */
2781 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
2782 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
2783 &owner, &group, &dacl, NULL, NULL);
2784 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
2785 ok(owner != NULL, "GetSecurityInfo\n");
2786 ok(group != NULL, "GetSecurityInfo\n");
2787 ok(dacl != NULL, "GetSecurityInfo\n");
2788 ok(IsValidAcl(dacl), "GetSecurityInfo\n");
2790 CloseHandle(obj);
2793 START_TEST(security)
2795 init();
2796 if (!hmod) return;
2798 if (myARGC >= 3)
2800 test_process_security_child();
2801 return;
2803 test_sid();
2804 test_trustee();
2805 test_luid();
2806 test_CreateWellKnownSid();
2807 test_FileSecurity();
2808 test_AccessCheck();
2809 test_token_attr();
2810 test_LookupAccountSid();
2811 test_LookupAccountName();
2812 test_security_descriptor();
2813 test_process_security();
2814 test_impersonation_level();
2815 test_SetEntriesInAcl();
2816 test_GetNamedSecurityInfoA();
2817 test_ConvertStringSecurityDescriptor();
2818 test_ConvertSecurityDescriptorToString();
2819 test_PrivateObjectSecurity();
2820 test_acls();
2821 test_GetSecurityInfo();