push 5f793418e14616d83a4fb368b755a8821b49820b
[wine/hacks.git] / dlls / advapi32 / tests / security.c
blobb68629d3916d3953216ec0c9f240865632109795
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*);
110 static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
111 PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
113 static HMODULE hmod;
114 static int myARGC;
115 static char** myARGV;
117 fnBuildTrusteeWithSidA pBuildTrusteeWithSidA;
118 fnBuildTrusteeWithNameA pBuildTrusteeWithNameA;
119 fnBuildTrusteeWithObjectsAndNameA pBuildTrusteeWithObjectsAndNameA;
120 fnBuildTrusteeWithObjectsAndSidA pBuildTrusteeWithObjectsAndSidA;
121 fnGetTrusteeNameA pGetTrusteeNameA;
122 fnMakeSelfRelativeSD pMakeSelfRelativeSD;
123 fnConvertSidToStringSidA pConvertSidToStringSidA;
124 fnConvertStringSidToSidA pConvertStringSidToSidA;
125 fnGetFileSecurityA pGetFileSecurityA;
126 fnSetFileSecurityA pSetFileSecurityA;
127 fnRtlAdjustPrivilege pRtlAdjustPrivilege;
128 fnCreateWellKnownSid pCreateWellKnownSid;
129 fnDuplicateTokenEx pDuplicateTokenEx;
130 fnLsaQueryInformationPolicy pLsaQueryInformationPolicy;
131 fnLsaClose pLsaClose;
132 fnLsaFreeMemory pLsaFreeMemory;
133 fnLsaOpenPolicy pLsaOpenPolicy;
135 struct sidRef
137 SID_IDENTIFIER_AUTHORITY auth;
138 const char *refStr;
141 static void init(void)
143 HMODULE hntdll;
145 hntdll = GetModuleHandleA("ntdll.dll");
146 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
147 pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
149 hmod = GetModuleHandle("advapi32.dll");
150 pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
151 pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
152 pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
153 pConvertStringSecurityDescriptorToSecurityDescriptorA =
154 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
155 pConvertStringSecurityDescriptorToSecurityDescriptorW =
156 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
157 pConvertSecurityDescriptorToStringSecurityDescriptorA =
158 (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
159 pGetFileSecurityA = (fnGetFileSecurityA)GetProcAddress(hmod, "GetFileSecurityA" );
160 pSetFileSecurityA = (fnSetFileSecurityA)GetProcAddress(hmod, "SetFileSecurityA" );
161 pCreateWellKnownSid = (fnCreateWellKnownSid)GetProcAddress( hmod, "CreateWellKnownSid" );
162 pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
163 pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
164 pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
165 pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
166 pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
168 myARGC = winetest_get_mainargs( &myARGV );
171 static void test_str_sid(const char *str_sid)
173 PSID psid;
174 char *temp;
176 if (pConvertStringSidToSidA(str_sid, &psid))
178 if (pConvertSidToStringSidA(psid, &temp))
180 trace(" %s: %s\n", str_sid, temp);
181 LocalFree(temp);
183 LocalFree(psid);
185 else
187 if (GetLastError() != ERROR_INVALID_SID)
188 trace(" %s: couldn't be converted, returned %d\n", str_sid, GetLastError());
189 else
190 trace(" %s: couldn't be converted\n", str_sid);
194 static void test_sid(void)
196 struct sidRef refs[] = {
197 { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
198 { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
199 { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
200 { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
201 { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
202 { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
204 const char noSubAuthStr[] = "S-1-5";
205 unsigned int i;
206 PSID psid = NULL;
207 SID *pisid;
208 BOOL r;
209 LPSTR str = NULL;
211 pConvertSidToStringSidA = (fnConvertSidToStringSidA)
212 GetProcAddress( hmod, "ConvertSidToStringSidA" );
213 if( !pConvertSidToStringSidA )
214 return;
215 pConvertStringSidToSidA = (fnConvertStringSidToSidA)
216 GetProcAddress( hmod, "ConvertStringSidToSidA" );
217 if( !pConvertStringSidToSidA )
218 return;
220 r = pConvertStringSidToSidA( NULL, NULL );
221 ok( !r, "expected failure with NULL parameters\n" );
222 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
223 return;
224 ok( GetLastError() == ERROR_INVALID_PARAMETER,
225 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
226 GetLastError() );
228 r = pConvertStringSidToSidA( refs[0].refStr, NULL );
229 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
230 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
231 GetLastError() );
233 r = pConvertStringSidToSidA( NULL, &str );
234 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
235 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
236 GetLastError() );
238 r = pConvertStringSidToSidA( noSubAuthStr, &psid );
239 ok( !r,
240 "expected failure with no sub authorities\n" );
241 ok( GetLastError() == ERROR_INVALID_SID,
242 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
243 GetLastError() );
245 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
246 pisid = psid;
247 ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
248 ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expceted 21, got %d\n", pisid->SubAuthority[0]);
249 ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expceted 4576, got %d\n", pisid->SubAuthority[3]);
250 LocalFree(str);
252 for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
254 PISID pisid;
256 r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
257 &psid );
258 ok( r, "failed to allocate sid\n" );
259 r = pConvertSidToStringSidA( psid, &str );
260 ok( r, "failed to convert sid\n" );
261 if (r)
263 ok( !strcmp( str, refs[i].refStr ),
264 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
265 LocalFree( str );
267 if( psid )
268 FreeSid( psid );
270 r = pConvertStringSidToSidA( refs[i].refStr, &psid );
271 ok( r, "failed to parse sid string\n" );
272 pisid = psid;
273 ok( pisid &&
274 !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
275 sizeof(refs[i].auth) ),
276 "string sid %s didn't parse to expected value\n"
277 "(got 0x%04x%08x, expected 0x%04x%08x)\n",
278 refs[i].refStr,
279 MAKEWORD( pisid->IdentifierAuthority.Value[1],
280 pisid->IdentifierAuthority.Value[0] ),
281 MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
282 pisid->IdentifierAuthority.Value[4] ),
283 MAKEWORD( pisid->IdentifierAuthority.Value[3],
284 pisid->IdentifierAuthority.Value[2] ) ),
285 MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
286 MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
287 MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
288 if( psid )
289 LocalFree( psid );
292 trace("String SIDs:\n");
293 test_str_sid("AO");
294 test_str_sid("RU");
295 test_str_sid("AN");
296 test_str_sid("AU");
297 test_str_sid("BA");
298 test_str_sid("BG");
299 test_str_sid("BO");
300 test_str_sid("BU");
301 test_str_sid("CA");
302 test_str_sid("CG");
303 test_str_sid("CO");
304 test_str_sid("DA");
305 test_str_sid("DC");
306 test_str_sid("DD");
307 test_str_sid("DG");
308 test_str_sid("DU");
309 test_str_sid("EA");
310 test_str_sid("ED");
311 test_str_sid("WD");
312 test_str_sid("PA");
313 test_str_sid("IU");
314 test_str_sid("LA");
315 test_str_sid("LG");
316 test_str_sid("LS");
317 test_str_sid("SY");
318 test_str_sid("NU");
319 test_str_sid("NO");
320 test_str_sid("NS");
321 test_str_sid("PO");
322 test_str_sid("PS");
323 test_str_sid("PU");
324 test_str_sid("RS");
325 test_str_sid("RD");
326 test_str_sid("RE");
327 test_str_sid("RC");
328 test_str_sid("SA");
329 test_str_sid("SO");
330 test_str_sid("SU");
333 static void test_trustee(void)
335 GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
336 GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
337 GUID ZeroGuid;
338 OBJECTS_AND_NAME_ oan;
339 OBJECTS_AND_SID oas;
340 TRUSTEE trustee;
341 PSID psid;
342 char szObjectTypeName[] = "ObjectTypeName";
343 char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
344 char szTrusteeName[] = "szTrusteeName";
345 SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
347 memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
349 pBuildTrusteeWithSidA = (fnBuildTrusteeWithSidA)
350 GetProcAddress( hmod, "BuildTrusteeWithSidA" );
351 pBuildTrusteeWithNameA = (fnBuildTrusteeWithNameA)
352 GetProcAddress( hmod, "BuildTrusteeWithNameA" );
353 pBuildTrusteeWithObjectsAndNameA = (fnBuildTrusteeWithObjectsAndNameA)
354 GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
355 pBuildTrusteeWithObjectsAndSidA = (fnBuildTrusteeWithObjectsAndSidA)
356 GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
357 pGetTrusteeNameA = (fnGetTrusteeNameA)
358 GetProcAddress (hmod, "GetTrusteeNameA" );
359 if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
360 !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
361 !pGetTrusteeNameA )
362 return;
364 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
366 trace( "failed to init SID\n" );
367 return;
370 /* test BuildTrusteeWithSidA */
371 memset( &trustee, 0xff, sizeof trustee );
372 pBuildTrusteeWithSidA( &trustee, psid );
374 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
375 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
376 "MultipleTrusteeOperation wrong\n");
377 ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
378 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
379 ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
381 /* test BuildTrusteeWithObjectsAndSidA (test 1) */
382 memset( &trustee, 0xff, sizeof trustee );
383 memset( &oas, 0xff, sizeof(oas) );
384 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
385 &InheritedObjectType, psid);
387 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
388 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
389 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
390 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
391 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
393 ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
394 ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
395 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
396 ok(oas.pSid == psid, "pSid wrong\n");
398 /* test GetTrusteeNameA */
399 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
401 /* test BuildTrusteeWithObjectsAndSidA (test 2) */
402 memset( &trustee, 0xff, sizeof trustee );
403 memset( &oas, 0xff, sizeof(oas) );
404 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
405 &InheritedObjectType, psid);
407 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
408 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
409 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
410 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
411 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
413 ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
414 ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
415 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
416 ok(oas.pSid == psid, "pSid wrong\n");
418 FreeSid( psid );
420 /* test BuildTrusteeWithNameA */
421 memset( &trustee, 0xff, sizeof trustee );
422 pBuildTrusteeWithNameA( &trustee, szTrusteeName );
424 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
425 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
426 "MultipleTrusteeOperation wrong\n");
427 ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
428 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
429 ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
431 /* test BuildTrusteeWithObjectsAndNameA (test 1) */
432 memset( &trustee, 0xff, sizeof trustee );
433 memset( &oan, 0xff, sizeof(oan) );
434 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
435 szInheritedObjectTypeName, szTrusteeName);
437 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
438 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
439 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
440 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
441 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
443 ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
444 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
445 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
446 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
448 /* test GetTrusteeNameA */
449 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
451 /* test BuildTrusteeWithObjectsAndNameA (test 2) */
452 memset( &trustee, 0xff, sizeof trustee );
453 memset( &oan, 0xff, sizeof(oan) );
454 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
455 szInheritedObjectTypeName, szTrusteeName);
457 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
458 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
459 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
460 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
461 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
463 ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
464 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
465 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
466 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
468 /* test BuildTrusteeWithObjectsAndNameA (test 3) */
469 memset( &trustee, 0xff, sizeof trustee );
470 memset( &oan, 0xff, sizeof(oan) );
471 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
472 NULL, szTrusteeName);
474 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
475 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
476 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
477 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
478 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
480 ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
481 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
482 ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
483 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
486 /* If the first isn't defined, assume none is */
487 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
488 #define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
489 #define SE_CREATE_TOKEN_PRIVILEGE 2L
490 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
491 #define SE_LOCK_MEMORY_PRIVILEGE 4L
492 #define SE_INCREASE_QUOTA_PRIVILEGE 5L
493 #define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
494 #define SE_TCB_PRIVILEGE 7L
495 #define SE_SECURITY_PRIVILEGE 8L
496 #define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
497 #define SE_LOAD_DRIVER_PRIVILEGE 10L
498 #define SE_SYSTEM_PROFILE_PRIVILEGE 11L
499 #define SE_SYSTEMTIME_PRIVILEGE 12L
500 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
501 #define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
502 #define SE_CREATE_PAGEFILE_PRIVILEGE 15L
503 #define SE_CREATE_PERMANENT_PRIVILEGE 16L
504 #define SE_BACKUP_PRIVILEGE 17L
505 #define SE_RESTORE_PRIVILEGE 18L
506 #define SE_SHUTDOWN_PRIVILEGE 19L
507 #define SE_DEBUG_PRIVILEGE 20L
508 #define SE_AUDIT_PRIVILEGE 21L
509 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
510 #define SE_CHANGE_NOTIFY_PRIVILEGE 23L
511 #define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
512 #define SE_UNDOCK_PRIVILEGE 25L
513 #define SE_SYNC_AGENT_PRIVILEGE 26L
514 #define SE_ENABLE_DELEGATION_PRIVILEGE 27L
515 #define SE_MANAGE_VOLUME_PRIVILEGE 28L
516 #define SE_IMPERSONATE_PRIVILEGE 29L
517 #define SE_CREATE_GLOBAL_PRIVILEGE 30L
518 #define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
519 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
521 static void test_allocateLuid(void)
523 BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
524 LUID luid1, luid2;
525 BOOL ret;
527 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
528 if (!pAllocateLocallyUniqueId) return;
530 ret = pAllocateLocallyUniqueId(&luid1);
531 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
532 return;
534 ok(ret,
535 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
536 ret = pAllocateLocallyUniqueId(&luid2);
537 ok( ret,
538 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
539 ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
540 "AllocateLocallyUniqueId returned a well-known LUID\n");
541 ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
542 "AllocateLocallyUniqueId returned non-unique LUIDs\n");
543 ret = pAllocateLocallyUniqueId(NULL);
544 ok( !ret && GetLastError() == ERROR_NOACCESS,
545 "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
546 GetLastError());
549 static void test_lookupPrivilegeName(void)
551 BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
552 char buf[MAX_PATH]; /* arbitrary, seems long enough */
553 DWORD cchName = sizeof(buf);
554 LUID luid = { 0, 0 };
555 LONG i;
556 BOOL ret;
558 /* check whether it's available first */
559 pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
560 if (!pLookupPrivilegeNameA) return;
561 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
562 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
563 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
564 return;
566 /* check with a short buffer */
567 cchName = 0;
568 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
569 ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
570 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
571 "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
572 GetLastError());
573 ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
574 "LookupPrivilegeNameA returned an incorrect required length for\n"
575 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
576 lstrlenA("SeCreateTokenPrivilege") + 1);
577 /* check a known value and its returned length on success */
578 cchName = sizeof(buf);
579 ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
580 cchName == strlen("SeCreateTokenPrivilege"),
581 "LookupPrivilegeNameA returned an incorrect output length for\n"
582 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
583 (int)strlen("SeCreateTokenPrivilege"));
584 /* check known values */
585 for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
587 luid.LowPart = i;
588 cchName = sizeof(buf);
589 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
590 ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
591 "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
593 /* check a bogus LUID */
594 luid.LowPart = 0xdeadbeef;
595 cchName = sizeof(buf);
596 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
597 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
598 "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
599 GetLastError());
600 /* check on a bogus system */
601 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
602 cchName = sizeof(buf);
603 ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
604 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
605 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
606 "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
607 GetLastError());
610 struct NameToLUID
612 const char *name;
613 DWORD lowPart;
616 static void test_lookupPrivilegeValue(void)
618 static const struct NameToLUID privs[] = {
619 { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
620 { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
621 { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
622 { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
623 { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
624 { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
625 { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
626 { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
627 { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
628 { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
629 { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
630 { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
631 { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
632 { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
633 { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
634 { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
635 { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
636 { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
637 { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
638 { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
639 { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
640 { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
641 { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
642 { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
643 { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
644 { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
645 { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
646 { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
647 { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
649 BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
650 int i;
651 LUID luid;
652 BOOL ret;
654 /* check whether it's available first */
655 pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
656 if (!pLookupPrivilegeValueA) return;
657 ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
658 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
659 return;
661 /* check a bogus system name */
662 ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
663 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
664 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
665 "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
666 GetLastError());
667 /* check a NULL string */
668 ret = pLookupPrivilegeValueA(NULL, 0, &luid);
669 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
670 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
671 GetLastError());
672 /* check a bogus privilege name */
673 ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
674 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
675 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
676 GetLastError());
677 /* check case insensitive */
678 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
679 ok( ret,
680 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
681 GetLastError());
682 for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
684 /* Not all privileges are implemented on all Windows versions, so
685 * don't worry if the call fails
687 if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
689 ok(luid.LowPart == privs[i].lowPart,
690 "LookupPrivilegeValueA returned an invalid LUID for %s\n",
691 privs[i].name);
696 static void test_luid(void)
698 test_allocateLuid();
699 test_lookupPrivilegeName();
700 test_lookupPrivilegeValue();
703 static void test_FileSecurity(void)
705 char wintmpdir [MAX_PATH];
706 char path [MAX_PATH];
707 char file [MAX_PATH];
708 BOOL rc;
709 HANDLE fh;
710 DWORD sdSize;
711 DWORD retSize;
712 BYTE *sd;
713 SECURITY_INFORMATION const request = OWNER_SECURITY_INFORMATION
714 | GROUP_SECURITY_INFORMATION
715 | DACL_SECURITY_INFORMATION;
717 if (!pGetFileSecurityA) {
718 win_skip ("GetFileSecurity is not available\n");
719 return;
722 if (!pSetFileSecurityA) {
723 win_skip ("SetFileSecurity is not available\n");
724 return;
727 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
728 win_skip ("GetTempPathA failed\n");
729 return;
732 /* Create a temporary directory and in it a temporary file */
733 strcat (strcpy (path, wintmpdir), "rary");
734 SetLastError(0xdeadbeef);
735 rc = CreateDirectoryA (path, NULL);
736 ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
737 "failed for '%s' with %d\n", path, GetLastError());
739 strcat (strcpy (file, path), "\\ess");
740 SetLastError(0xdeadbeef);
741 fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
742 ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
743 "failed for '%s' with %d\n", file, GetLastError());
744 CloseHandle (fh);
746 /* For the temporary file ... */
748 /* Get size needed */
749 retSize = 0;
750 SetLastError(0xdeadbeef);
751 rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
752 if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
753 win_skip("GetFileSecurityA is not implemented\n");
754 goto cleanup;
756 ok (!rc, "GetFileSecurityA "
757 "was expected to fail for '%s'\n", file);
758 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
759 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
760 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
762 sdSize = retSize;
763 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
765 /* Get security descriptor for real */
766 retSize = -1;
767 SetLastError(0xdeadbeef);
768 rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
769 ok (rc, "GetFileSecurityA "
770 "was not expected to fail '%s': %d\n", file, GetLastError());
771 ok (retSize == sdSize ||
772 broken(retSize == 0), /* NT4 */
773 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
775 /* Use it to set security descriptor */
776 SetLastError(0xdeadbeef);
777 rc = pSetFileSecurityA (file, request, sd);
778 ok (rc, "SetFileSecurityA "
779 "was not expected to fail '%s': %d\n", file, GetLastError());
781 HeapFree (GetProcessHeap (), 0, sd);
783 /* Repeat for the temporary directory ... */
785 /* Get size needed */
786 retSize = 0;
787 SetLastError(0xdeadbeef);
788 rc = pGetFileSecurityA (path, request, NULL, 0, &retSize);
789 ok (!rc, "GetFileSecurityA "
790 "was expected to fail for '%s'\n", path);
791 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
792 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
793 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
795 sdSize = retSize;
796 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
798 /* Get security descriptor for real */
799 retSize = -1;
800 SetLastError(0xdeadbeef);
801 rc = pGetFileSecurityA (path, request, sd, sdSize, &retSize);
802 ok (rc, "GetFileSecurityA "
803 "was not expected to fail '%s': %d\n", path, GetLastError());
804 ok (retSize == sdSize ||
805 broken(retSize == 0), /* NT4 */
806 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
808 /* Use it to set security descriptor */
809 SetLastError(0xdeadbeef);
810 rc = pSetFileSecurityA (path, request, sd);
811 ok (rc, "SetFileSecurityA "
812 "was not expected to fail '%s': %d\n", path, GetLastError());
813 HeapFree (GetProcessHeap (), 0, sd);
815 /* Old test */
816 strcpy (wintmpdir, "\\Should not exist");
817 SetLastError(0xdeadbeef);
818 rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
819 ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
820 ok (GetLastError() == ERROR_FILE_NOT_FOUND,
821 "last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());
823 cleanup:
824 /* Remove temporary file and directory */
825 DeleteFileA(file);
826 RemoveDirectoryA(path);
829 static void test_AccessCheck(void)
831 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
832 PACL Acl = NULL;
833 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
834 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
835 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
836 GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
837 ACCESS_MASK Access;
838 BOOL AccessStatus;
839 HANDLE Token;
840 HANDLE ProcessToken;
841 BOOL ret;
842 DWORD PrivSetLen;
843 PRIVILEGE_SET *PrivSet;
844 BOOL res;
845 HMODULE NtDllModule;
846 BOOLEAN Enabled;
847 DWORD err;
848 NTSTATUS ntret, ntAccessStatus;
850 NtDllModule = GetModuleHandle("ntdll.dll");
851 if (!NtDllModule)
853 skip("not running on NT, skipping test\n");
854 return;
856 pRtlAdjustPrivilege = (fnRtlAdjustPrivilege)
857 GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
858 if (!pRtlAdjustPrivilege)
860 win_skip("missing RtlAdjustPrivilege, skipping test\n");
861 return;
864 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
865 res = InitializeAcl(Acl, 256, ACL_REVISION);
866 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
868 skip("ACLs not implemented - skipping tests\n");
869 HeapFree(GetProcessHeap(), 0, Acl);
870 return;
872 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
874 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
875 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
877 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
878 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
879 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
881 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
882 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
883 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
885 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
887 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
888 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
890 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
891 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
893 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
894 PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
895 PrivSet->PrivilegeCount = 16;
897 res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
898 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
900 pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
902 res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
903 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
905 /* SD without owner/group */
906 SetLastError(0xdeadbeef);
907 Access = AccessStatus = 0xdeadbeef;
908 ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
909 PrivSet, &PrivSetLen, &Access, &AccessStatus);
910 err = GetLastError();
911 ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
912 "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
913 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
914 "Access and/or AccessStatus were changed!\n");
916 /* Set owner and group */
917 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
918 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
919 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
920 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
922 /* Generic access mask */
923 SetLastError(0xdeadbeef);
924 Access = AccessStatus = 0xdeadbeef;
925 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
926 PrivSet, &PrivSetLen, &Access, &AccessStatus);
927 err = GetLastError();
928 ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
929 "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
930 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
931 "Access and/or AccessStatus were changed!\n");
933 /* Generic access mask - no privilegeset buffer */
934 SetLastError(0xdeadbeef);
935 Access = AccessStatus = 0xdeadbeef;
936 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
937 NULL, &PrivSetLen, &Access, &AccessStatus);
938 err = GetLastError();
939 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
940 "with ERROR_NOACCESS, instead of %d\n", err);
941 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
942 "Access and/or AccessStatus were changed!\n");
944 /* Generic access mask - no returnlength */
945 SetLastError(0xdeadbeef);
946 Access = AccessStatus = 0xdeadbeef;
947 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
948 PrivSet, NULL, &Access, &AccessStatus);
949 err = GetLastError();
950 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
951 "with ERROR_NOACCESS, instead of %d\n", err);
952 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
953 "Access and/or AccessStatus were changed!\n");
955 /* Generic access mask - no privilegeset buffer, no returnlength */
956 SetLastError(0xdeadbeef);
957 Access = AccessStatus = 0xdeadbeef;
958 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
959 NULL, NULL, &Access, &AccessStatus);
960 err = GetLastError();
961 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
962 "with ERROR_NOACCESS, instead of %d\n", err);
963 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
964 "Access and/or AccessStatus were changed!\n");
966 /* sd with no dacl present */
967 Access = AccessStatus = 0xdeadbeef;
968 ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
969 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
970 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
971 PrivSet, &PrivSetLen, &Access, &AccessStatus);
972 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
973 ok(AccessStatus && (Access == KEY_READ),
974 "AccessCheck failed to grant access with error %d\n",
975 GetLastError());
977 /* sd with no dacl present - no privilegeset buffer */
978 SetLastError(0xdeadbeef);
979 Access = AccessStatus = 0xdeadbeef;
980 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
981 NULL, &PrivSetLen, &Access, &AccessStatus);
982 err = GetLastError();
983 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
984 "with ERROR_NOACCESS, instead of %d\n", err);
985 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
986 "Access and/or AccessStatus were changed!\n");
988 if(pNtAccessCheck)
990 /* Generic access mask - no privilegeset buffer */
991 SetLastError(0xdeadbeef);
992 Access = ntAccessStatus = 0xdeadbeef;
993 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
994 NULL, &PrivSetLen, &Access, &ntAccessStatus);
995 err = GetLastError();
996 ok(ntret == STATUS_ACCESS_VIOLATION,
997 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
998 ok(err == 0xdeadbeef,
999 "NtAccessCheck shouldn't set last error, got %d\n", err);
1000 ok(Access == 0xdeadbeef && ntAccessStatus == 0xdeadbeef,
1001 "Access and/or AccessStatus were changed!\n");
1003 /* Generic access mask - no returnlength */
1004 SetLastError(0xdeadbeef);
1005 Access = ntAccessStatus = 0xdeadbeef;
1006 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1007 PrivSet, NULL, &Access, &ntAccessStatus);
1008 err = GetLastError();
1009 ok(ntret == STATUS_ACCESS_VIOLATION,
1010 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1011 ok(err == 0xdeadbeef,
1012 "NtAccessCheck shouldn't set last error, got %d\n", err);
1013 ok(Access == 0xdeadbeef && ntAccessStatus == 0xdeadbeef,
1014 "Access and/or AccessStatus were changed!\n");
1016 /* Generic access mask - no privilegeset buffer, no returnlength */
1017 SetLastError(0xdeadbeef);
1018 Access = ntAccessStatus = 0xdeadbeef;
1019 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1020 NULL, NULL, &Access, &ntAccessStatus);
1021 err = GetLastError();
1022 ok(ntret == STATUS_ACCESS_VIOLATION,
1023 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1024 ok(err == 0xdeadbeef,
1025 "NtAccessCheck shouldn't set last error, got %d\n", err);
1026 ok(Access == 0xdeadbeef && ntAccessStatus == 0xdeadbeef,
1027 "Access and/or AccessStatus were changed!\n");
1029 else
1030 win_skip("NtAccessCheck unavailable. Skipping.\n");
1032 /* sd with NULL dacl */
1033 Access = AccessStatus = 0xdeadbeef;
1034 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
1035 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1036 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1037 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1038 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1039 ok(AccessStatus && (Access == KEY_READ),
1040 "AccessCheck failed to grant access with error %d\n",
1041 GetLastError());
1043 /* sd with blank dacl */
1044 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1045 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1046 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1047 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1048 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1049 err = GetLastError();
1050 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1051 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1052 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1054 res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
1055 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1057 res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
1058 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1060 /* sd with dacl */
1061 Access = AccessStatus = 0xdeadbeef;
1062 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1063 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1064 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1065 ok(AccessStatus && (Access == KEY_READ),
1066 "AccessCheck failed to grant access with error %d\n",
1067 GetLastError());
1069 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1070 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1071 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1072 ok(AccessStatus,
1073 "AccessCheck failed to grant any access with error %d\n",
1074 GetLastError());
1075 trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
1077 /* Access denied by SD */
1078 SetLastError(0xdeadbeef);
1079 Access = AccessStatus = 0xdeadbeef;
1080 ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
1081 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1082 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1083 err = GetLastError();
1084 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1085 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1086 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1088 SetLastError(0);
1089 PrivSet->PrivilegeCount = 16;
1090 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1091 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1092 ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
1093 "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
1094 GetLastError());
1096 ret = ImpersonateLoggedOnUser(Token);
1097 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1098 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
1099 if (!ret)
1101 SetLastError(0);
1102 PrivSet->PrivilegeCount = 16;
1103 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1104 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1105 ok(ret && AccessStatus && GetLastError() == 0,
1106 "AccessCheck should have succeeded, error %d\n",
1107 GetLastError());
1108 ok(Access == ACCESS_SYSTEM_SECURITY,
1109 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1110 Access);
1112 else
1113 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1114 ret);
1115 ret = RevertToSelf();
1116 ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1118 /* test INHERIT_ONLY_ACE */
1119 ret = InitializeAcl(Acl, 256, ACL_REVISION);
1120 ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
1122 /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
1123 * the next ones.
1125 if (pAddAccessAllowedAceEx)
1127 ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
1128 ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1130 else
1131 win_skip("AddAccessAllowedAceEx is not available\n");
1133 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1134 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1135 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1136 err = GetLastError();
1137 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1138 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1139 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1141 CloseHandle(Token);
1143 res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
1144 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1146 SetLastError(0xdeadbeef);
1147 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1148 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1149 err = GetLastError();
1150 ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
1151 "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
1153 CloseHandle(Token);
1155 SetLastError(0xdeadbeef);
1156 ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
1157 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1158 err = GetLastError();
1159 ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
1160 "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
1162 CloseHandle(ProcessToken);
1164 if (EveryoneSid)
1165 FreeSid(EveryoneSid);
1166 if (AdminSid)
1167 FreeSid(AdminSid);
1168 if (UsersSid)
1169 FreeSid(UsersSid);
1170 HeapFree(GetProcessHeap(), 0, Acl);
1171 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1172 HeapFree(GetProcessHeap(), 0, PrivSet);
1175 /* test GetTokenInformation for the various attributes */
1176 static void test_token_attr(void)
1178 HANDLE Token, ImpersonationToken;
1179 DWORD Size, Size2;
1180 TOKEN_PRIVILEGES *Privileges;
1181 TOKEN_GROUPS *Groups;
1182 TOKEN_USER *User;
1183 TOKEN_DEFAULT_DACL *Dacl;
1184 BOOL ret;
1185 DWORD i, GLE;
1186 LPSTR SidString;
1187 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1188 ACL *acl;
1190 /* cygwin-like use case */
1191 SetLastError(0xdeadbeef);
1192 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1193 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1195 win_skip("OpenProcessToken is not implemented\n");
1196 return;
1198 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1199 if (ret)
1201 DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1202 Size = sizeof(buf);
1203 ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1204 ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1205 Size = sizeof(ImpersonationLevel);
1206 ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1207 GLE = GetLastError();
1208 ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1209 CloseHandle(Token);
1212 if(!pConvertSidToStringSidA)
1214 win_skip("ConvertSidToStringSidA is not available\n");
1215 return;
1218 SetLastError(0xdeadbeef);
1219 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1220 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1222 /* groups */
1223 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1224 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1225 ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1226 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1227 trace("TokenGroups:\n");
1228 for (i = 0; i < Groups->GroupCount; i++)
1230 DWORD NameLength = 255;
1231 TCHAR Name[255];
1232 DWORD DomainLength = 255;
1233 TCHAR Domain[255];
1234 SID_NAME_USE SidNameUse;
1235 pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1236 Name[0] = '\0';
1237 Domain[0] = '\0';
1238 ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1239 if (ret)
1240 trace("\t%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
1241 else
1242 trace("\t%s, attr: 0x%08x LookupAccountSid failed with error %d\n", SidString, Groups->Groups[i].Attributes, GetLastError());
1243 LocalFree(SidString);
1245 HeapFree(GetProcessHeap(), 0, Groups);
1247 /* user */
1248 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1249 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1250 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1251 User = HeapAlloc(GetProcessHeap(), 0, Size);
1252 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1253 ok(ret,
1254 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1256 pConvertSidToStringSidA(User->User.Sid, &SidString);
1257 trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1258 LocalFree(SidString);
1259 HeapFree(GetProcessHeap(), 0, User);
1261 /* privileges */
1262 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1263 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1264 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1265 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1266 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1267 ok(ret,
1268 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1269 trace("TokenPrivileges:\n");
1270 for (i = 0; i < Privileges->PrivilegeCount; i++)
1272 TCHAR Name[256];
1273 DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
1274 LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1275 trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1277 HeapFree(GetProcessHeap(), 0, Privileges);
1279 ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
1280 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1282 Size = sizeof(ImpersonationLevel);
1283 ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1284 ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1285 ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
1287 CloseHandle(ImpersonationToken);
1289 /* default dacl */
1290 ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
1291 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1292 "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1294 Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
1295 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
1296 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1298 SetLastError(0xdeadbeef);
1299 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
1300 GLE = GetLastError();
1301 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1302 ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);
1304 SetLastError(0xdeadbeef);
1305 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
1306 GLE = GetLastError();
1307 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1308 ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);
1310 acl = Dacl->DefaultDacl;
1311 Dacl->DefaultDacl = NULL;
1313 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1314 ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1316 Size2 = 0;
1317 Dacl->DefaultDacl = (ACL *)0xdeadbeef;
1318 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1319 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1320 ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
1321 ok(Size2 == sizeof(TOKEN_DEFAULT_DACL), "got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
1323 Dacl->DefaultDacl = acl;
1324 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1325 ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1327 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1328 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1330 HeapFree(GetProcessHeap(), 0, Dacl);
1331 CloseHandle(Token);
1334 typedef union _MAX_SID
1336 SID sid;
1337 char max[SECURITY_MAX_SID_SIZE];
1338 } MAX_SID;
1340 static void test_sid_str(PSID * sid)
1342 char *str_sid;
1343 BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
1344 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
1345 if (ret)
1347 char account[MAX_PATH], domain[MAX_PATH];
1348 SID_NAME_USE use;
1349 DWORD acc_size = MAX_PATH;
1350 DWORD dom_size = MAX_PATH;
1351 ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
1352 ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
1353 "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
1354 if (ret)
1355 trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
1356 else if (GetLastError() == ERROR_NONE_MAPPED)
1357 trace(" %s couldn't be mapped\n", str_sid);
1358 LocalFree(str_sid);
1362 struct well_known_sid_value
1364 BOOL without_domain;
1365 const char *sid_string;
1366 } well_known_sid_values[] = {
1367 /* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
1368 /* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
1369 /* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
1370 /* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
1371 /* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
1372 /* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
1373 /* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
1374 /* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
1375 /* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
1376 /* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
1377 /* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
1378 /* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
1379 /* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
1380 /* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
1381 /* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
1382 /* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
1383 /* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
1384 /* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
1385 /* Added in Windows Server 2003 */
1386 /* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
1387 /* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
1388 /* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
1389 /* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
1390 /* Added in Windows Vista: */
1391 /* 62 */ {TRUE, "S-1-5-32-568"},
1392 /* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
1393 /* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
1394 /* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
1395 /* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
1396 /* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"}
1399 static void test_CreateWellKnownSid(void)
1401 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1402 PSID domainsid, sid;
1403 DWORD size, error;
1404 BOOL ret;
1405 int i;
1407 if (!pCreateWellKnownSid)
1409 win_skip("CreateWellKnownSid not available\n");
1410 return;
1413 size = 0;
1414 SetLastError(0xdeadbeef);
1415 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
1416 error = GetLastError();
1417 ok(!ret, "CreateWellKnownSid succeeded\n");
1418 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
1419 ok(size, "expected size > 0\n");
1421 SetLastError(0xdeadbeef);
1422 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
1423 error = GetLastError();
1424 ok(!ret, "CreateWellKnownSid succeeded\n");
1425 ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);
1427 sid = HeapAlloc(GetProcessHeap(), 0, size);
1428 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
1429 ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
1430 HeapFree(GetProcessHeap(), 0, sid);
1432 /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
1433 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
1435 for (i = 0; i < sizeof(well_known_sid_values)/sizeof(well_known_sid_values[0]); i++)
1437 struct well_known_sid_value *value = &well_known_sid_values[i];
1438 char sid_buffer[SECURITY_MAX_SID_SIZE];
1439 LPSTR str;
1440 DWORD cb;
1442 if (value->sid_string == NULL)
1443 continue;
1445 if (i > WinAccountRasAndIasServersSid)
1447 /* These SIDs aren't implemented by all Windows versions - detect it and break the loop */
1448 cb = sizeof(sid_buffer);
1449 if (!pCreateWellKnownSid(i, domainsid, sid_buffer, &cb))
1451 skip("Well known SIDs starting from %d are not implemented\n", i);
1452 break;
1456 cb = sizeof(sid_buffer);
1457 ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %d\n", i);
1458 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1459 ok(IsValidSid(sid_buffer), "The sid is not valid\n");
1460 ok(pConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
1461 ok(strcmp(str, value->sid_string) == 0, "SID mismatch - expected %s, got %s\n",
1462 value->sid_string, str);
1463 LocalFree(str);
1465 if (value->without_domain)
1467 char buf2[SECURITY_MAX_SID_SIZE];
1468 cb = sizeof(buf2);
1469 ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %d with optional domain\n", i);
1470 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1471 ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%d)\n", i);
1476 static void test_LookupAccountSid(void)
1478 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1479 CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
1480 DWORD acc_sizeA, dom_sizeA, user_sizeA;
1481 DWORD real_acc_sizeA, real_dom_sizeA;
1482 WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
1483 DWORD acc_sizeW, dom_sizeW;
1484 DWORD real_acc_sizeW, real_dom_sizeW;
1485 PSID pUsersSid = NULL;
1486 SID_NAME_USE use;
1487 BOOL ret;
1488 DWORD size,cbti = 0;
1489 MAX_SID max_sid;
1490 CHAR *str_sidA;
1491 int i;
1492 HANDLE hToken;
1493 PTOKEN_USER ptiUser = NULL;
1495 /* native windows crashes if account size, domain size, or name use is NULL */
1497 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1498 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
1499 ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
1500 "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1502 /* not running on NT so give up */
1503 if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1504 return;
1506 real_acc_sizeA = MAX_PATH;
1507 real_dom_sizeA = MAX_PATH;
1508 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1509 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1511 /* try NULL account */
1512 acc_sizeA = MAX_PATH;
1513 dom_sizeA = MAX_PATH;
1514 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1515 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1517 /* try NULL domain */
1518 acc_sizeA = MAX_PATH;
1519 dom_sizeA = MAX_PATH;
1520 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1521 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1523 /* try a small account buffer */
1524 acc_sizeA = 1;
1525 dom_sizeA = MAX_PATH;
1526 accountA[0] = 0;
1527 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1528 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1529 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1530 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1532 /* try a 0 sized account buffer */
1533 acc_sizeA = 0;
1534 dom_sizeA = MAX_PATH;
1535 accountA[0] = 0;
1536 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1537 /* this can fail or succeed depending on OS version but the size will always be returned */
1538 ok(acc_sizeA == real_acc_sizeA + 1,
1539 "LookupAccountSidA() Expected acc_size = %u, got %u\n",
1540 real_acc_sizeA + 1, acc_sizeA);
1542 /* try a 0 sized account buffer */
1543 acc_sizeA = 0;
1544 dom_sizeA = MAX_PATH;
1545 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1546 /* this can fail or succeed depending on OS version but the size will always be returned */
1547 ok(acc_sizeA == real_acc_sizeA + 1,
1548 "LookupAccountSid() Expected acc_size = %u, got %u\n",
1549 real_acc_sizeA + 1, acc_sizeA);
1551 /* try a small domain buffer */
1552 dom_sizeA = 1;
1553 acc_sizeA = MAX_PATH;
1554 accountA[0] = 0;
1555 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1556 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1557 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1558 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1560 /* try a 0 sized domain buffer */
1561 dom_sizeA = 0;
1562 acc_sizeA = MAX_PATH;
1563 accountA[0] = 0;
1564 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1565 /* this can fail or succeed depending on OS version but the size will always be returned */
1566 ok(dom_sizeA == real_dom_sizeA + 1,
1567 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1568 real_dom_sizeA + 1, dom_sizeA);
1570 /* try a 0 sized domain buffer */
1571 dom_sizeA = 0;
1572 acc_sizeA = MAX_PATH;
1573 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1574 /* this can fail or succeed depending on OS version but the size will always be returned */
1575 ok(dom_sizeA == real_dom_sizeA + 1,
1576 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1577 real_dom_sizeA + 1, dom_sizeA);
1579 real_acc_sizeW = MAX_PATH;
1580 real_dom_sizeW = MAX_PATH;
1581 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
1582 ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
1584 /* try an invalid system name */
1585 real_acc_sizeA = MAX_PATH;
1586 real_dom_sizeA = MAX_PATH;
1587 ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1588 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1589 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
1590 "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
1592 /* native windows crashes if domainW or accountW is NULL */
1594 /* try a small account buffer */
1595 acc_sizeW = 1;
1596 dom_sizeW = MAX_PATH;
1597 accountW[0] = 0;
1598 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1599 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1600 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1601 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1603 /* try a 0 sized account buffer */
1604 acc_sizeW = 0;
1605 dom_sizeW = MAX_PATH;
1606 accountW[0] = 0;
1607 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1608 /* this can fail or succeed depending on OS version but the size will always be returned */
1609 ok(acc_sizeW == real_acc_sizeW + 1,
1610 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1611 real_acc_sizeW + 1, acc_sizeW);
1613 /* try a 0 sized account buffer */
1614 acc_sizeW = 0;
1615 dom_sizeW = MAX_PATH;
1616 ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1617 /* this can fail or succeed depending on OS version but the size will always be returned */
1618 ok(acc_sizeW == real_acc_sizeW + 1,
1619 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1620 real_acc_sizeW + 1, acc_sizeW);
1622 /* try a small domain buffer */
1623 dom_sizeW = 1;
1624 acc_sizeW = MAX_PATH;
1625 accountW[0] = 0;
1626 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1627 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1628 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1629 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1631 /* try a 0 sized domain buffer */
1632 dom_sizeW = 0;
1633 acc_sizeW = MAX_PATH;
1634 accountW[0] = 0;
1635 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1636 /* this can fail or succeed depending on OS version but the size will always be returned */
1637 ok(dom_sizeW == real_dom_sizeW + 1,
1638 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1639 real_dom_sizeW + 1, dom_sizeW);
1641 /* try a 0 sized domain buffer */
1642 dom_sizeW = 0;
1643 acc_sizeW = MAX_PATH;
1644 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1645 /* this can fail or succeed depending on OS version but the size will always be returned */
1646 ok(dom_sizeW == real_dom_sizeW + 1,
1647 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1648 real_dom_sizeW + 1, dom_sizeW);
1650 FreeSid(pUsersSid);
1652 /* Test LookupAccountSid with Sid retrieved from token information.
1653 This assumes this process is running under the account of the current user.*/
1654 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
1655 ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
1656 ptiUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), 0, cbti);
1657 if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
1659 acc_sizeA = dom_sizeA = MAX_PATH;
1660 ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1661 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1662 user_sizeA = MAX_PATH;
1663 ret = GetUserNameA(usernameA , &user_sizeA);
1664 ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
1665 todo_wine
1667 ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
1670 HeapFree(GetProcessHeap(), 0, ptiUser);
1672 if (pCreateWellKnownSid && pConvertSidToStringSidA)
1674 trace("Well Known SIDs:\n");
1675 for (i = 0; i <= 60; i++)
1677 size = SECURITY_MAX_SID_SIZE;
1678 if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
1680 if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1682 acc_sizeA = MAX_PATH;
1683 dom_sizeA = MAX_PATH;
1684 if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
1685 trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
1686 LocalFree(str_sidA);
1689 else
1691 if (GetLastError() != ERROR_INVALID_PARAMETER)
1692 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1693 else
1694 trace(" %d: not supported\n", i);
1698 pLsaQueryInformationPolicy = (fnLsaQueryInformationPolicy)GetProcAddress( hmod, "LsaQueryInformationPolicy");
1699 pLsaOpenPolicy = (fnLsaOpenPolicy)GetProcAddress( hmod, "LsaOpenPolicy");
1700 pLsaFreeMemory = (fnLsaFreeMemory)GetProcAddress( hmod, "LsaFreeMemory");
1701 pLsaClose = (fnLsaClose)GetProcAddress( hmod, "LsaClose");
1703 if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
1705 NTSTATUS status;
1706 LSA_HANDLE handle;
1707 LSA_OBJECT_ATTRIBUTES object_attributes;
1709 ZeroMemory(&object_attributes, sizeof(object_attributes));
1710 object_attributes.Length = sizeof(object_attributes);
1712 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1713 ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1714 "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1716 /* try a more restricted access mask if necessary */
1717 if (status == STATUS_ACCESS_DENIED) {
1718 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
1719 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1720 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
1723 if (status == STATUS_SUCCESS)
1725 PPOLICY_ACCOUNT_DOMAIN_INFO info;
1726 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
1727 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
1728 if (status == STATUS_SUCCESS)
1730 ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
1731 if (info->DomainSid)
1733 int count = *GetSidSubAuthorityCount(info->DomainSid);
1734 CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
1735 test_sid_str((PSID)&max_sid.sid);
1736 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
1737 max_sid.sid.SubAuthorityCount = count + 1;
1738 test_sid_str((PSID)&max_sid.sid);
1739 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
1740 test_sid_str((PSID)&max_sid.sid);
1741 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
1742 test_sid_str((PSID)&max_sid.sid);
1743 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
1744 test_sid_str((PSID)&max_sid.sid);
1745 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
1746 test_sid_str((PSID)&max_sid.sid);
1747 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
1748 test_sid_str((PSID)&max_sid.sid);
1749 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
1750 test_sid_str((PSID)&max_sid.sid);
1751 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
1752 test_sid_str((PSID)&max_sid.sid);
1753 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
1754 test_sid_str((PSID)&max_sid.sid);
1755 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
1756 test_sid_str((PSID)&max_sid.sid);
1757 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
1758 test_sid_str((PSID)&max_sid.sid);
1759 max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
1760 test_sid_str((PSID)&max_sid.sid);
1761 max_sid.sid.SubAuthority[count] = 1000; /* first user account */
1762 test_sid_str((PSID)&max_sid.sid);
1765 pLsaFreeMemory((LPVOID)info);
1768 status = pLsaClose(handle);
1769 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
1775 static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
1777 static CHAR account[UNLEN + 1];
1778 static CHAR domain[UNLEN + 1];
1779 DWORD size, dom_size;
1780 SID_NAME_USE use;
1782 *user = account;
1783 *dom = domain;
1785 size = dom_size = UNLEN + 1;
1786 account[0] = '\0';
1787 domain[0] = '\0';
1788 SetLastError(0xdeadbeef);
1789 return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
1792 static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
1794 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1795 PSID domainsid;
1796 char wk_sid[SECURITY_MAX_SID_SIZE];
1797 DWORD cb;
1799 DWORD sid_size, domain_size;
1800 SID_NAME_USE sid_use;
1801 LPSTR domain, account, sid_domain, wk_domain, wk_account;
1802 PSID psid;
1803 BOOL ret ,ret2;
1805 sid_size = 0;
1806 domain_size = 0;
1807 ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
1808 psid = HeapAlloc(GetProcessHeap(),0,sid_size);
1809 domain = HeapAlloc(GetProcessHeap(),0,domain_size);
1810 ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);
1812 if (!result)
1814 ok(!ret, " %s Should have failed to lookup account name\n",name);
1815 goto cleanup;
1818 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
1819 cb = sizeof(wk_sid);
1820 if (!pCreateWellKnownSid(result, domainsid, wk_sid, &cb))
1822 win_skip("SID %i is not available on the system\n",result);
1823 goto cleanup;
1826 ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
1827 if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
1829 win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
1830 goto cleanup;
1833 get_sid_info(psid, &account, &sid_domain);
1835 ok(ret, "Failed to lookup account name %s\n",name);
1836 ok(sid_size != 0, "sid_size was zero\n");
1838 ok(EqualSid(psid,wk_sid),"(%s) Sids fail to match well known sid!\n",name);
1840 ok(!lstrcmp(account, wk_account), "Expected %s , got %s\n", account, wk_account);
1841 ok(!lstrcmp(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
1842 ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
1844 cleanup:
1845 HeapFree(GetProcessHeap(),0,psid);
1846 HeapFree(GetProcessHeap(),0,domain);
1849 static void test_LookupAccountName(void)
1851 DWORD sid_size, domain_size, user_size;
1852 DWORD sid_save, domain_save;
1853 CHAR user_name[UNLEN + 1];
1854 CHAR computer_name[UNLEN + 1];
1855 SID_NAME_USE sid_use;
1856 LPSTR domain, account, sid_dom;
1857 PSID psid;
1858 BOOL ret;
1860 /* native crashes if (assuming all other parameters correct):
1861 * - peUse is NULL
1862 * - Sid is NULL and cbSid is > 0
1863 * - cbSid or cchReferencedDomainName are NULL
1864 * - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
1867 user_size = UNLEN + 1;
1868 SetLastError(0xdeadbeef);
1869 ret = GetUserNameA(user_name, &user_size);
1870 if (!ret && (GetLastError() == ERROR_NOT_LOGGED_ON))
1872 /* Probably on win9x where the user used 'Cancel' instead of properly logging in */
1873 skip("Cannot get the user name (win9x and not logged in properly)\n");
1874 return;
1876 ok(ret, "Failed to get user name : %d\n", GetLastError());
1878 /* get sizes */
1879 sid_size = 0;
1880 domain_size = 0;
1881 sid_use = 0xcafebabe;
1882 SetLastError(0xdeadbeef);
1883 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
1884 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1886 win_skip("LookupAccountNameA is not implemented\n");
1887 return;
1889 ok(!ret, "Expected 0, got %d\n", ret);
1890 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1891 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1892 ok(sid_size != 0, "Expected non-zero sid size\n");
1893 ok(domain_size != 0, "Expected non-zero domain size\n");
1894 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1896 sid_save = sid_size;
1897 domain_save = domain_size;
1899 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1900 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1902 /* try valid account name */
1903 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
1904 get_sid_info(psid, &account, &sid_dom);
1905 ok(ret, "Failed to lookup account name\n");
1906 ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
1907 todo_wine
1909 ok(!lstrcmp(account, user_name), "Expected %s, got %s\n", user_name, account);
1910 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1912 ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
1913 ok(lstrlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
1914 ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
1915 domain_size = domain_save;
1916 sid_size = sid_save;
1918 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
1920 skip("Non-english locale (test with hardcoded 'Everyone')\n");
1922 else
1924 ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
1925 get_sid_info(psid, &account, &sid_dom);
1926 ok(ret, "Failed to lookup account name\n");
1927 ok(sid_size != 0, "sid_size was zero\n");
1928 ok(!lstrcmp(account, "Everyone"), "Expected Everyone, got %s\n", account);
1929 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1930 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
1931 ok(lstrlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
1932 ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
1933 domain_size = domain_save;
1936 /* NULL Sid with zero sid size */
1937 SetLastError(0xdeadbeef);
1938 sid_size = 0;
1939 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1940 ok(!ret, "Expected 0, got %d\n", ret);
1941 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1942 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1943 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1944 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1946 /* try cchReferencedDomainName - 1 */
1947 SetLastError(0xdeadbeef);
1948 domain_size--;
1949 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1950 ok(!ret, "Expected 0, got %d\n", ret);
1951 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1952 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1953 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1954 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1956 /* NULL ReferencedDomainName with zero domain name size */
1957 SetLastError(0xdeadbeef);
1958 domain_size = 0;
1959 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
1960 ok(!ret, "Expected 0, got %d\n", ret);
1961 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1962 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1963 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1964 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1966 HeapFree(GetProcessHeap(), 0, psid);
1967 HeapFree(GetProcessHeap(), 0, domain);
1969 /* get sizes for NULL account name */
1970 sid_size = 0;
1971 domain_size = 0;
1972 sid_use = 0xcafebabe;
1973 SetLastError(0xdeadbeef);
1974 ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
1975 if (!ret && GetLastError() == ERROR_NONE_MAPPED)
1976 win_skip("NULL account name doesn't work on NT4\n");
1977 else
1979 ok(!ret, "Expected 0, got %d\n", ret);
1980 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1981 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1982 ok(sid_size != 0, "Expected non-zero sid size\n");
1983 ok(domain_size != 0, "Expected non-zero domain size\n");
1984 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1986 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1987 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1989 /* try NULL account name */
1990 ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
1991 get_sid_info(psid, &account, &sid_dom);
1992 ok(ret, "Failed to lookup account name\n");
1993 /* Using a fixed string will not work on different locales */
1994 ok(!lstrcmp(account, domain),
1995 "Got %s for account and %s for domain, these should be the same\n",
1996 account, domain);
1997 ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
1999 HeapFree(GetProcessHeap(), 0, psid);
2000 HeapFree(GetProcessHeap(), 0, domain);
2003 /* try an invalid account name */
2004 SetLastError(0xdeadbeef);
2005 sid_size = 0;
2006 domain_size = 0;
2007 ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
2008 ok(!ret, "Expected 0, got %d\n", ret);
2009 ok(GetLastError() == ERROR_NONE_MAPPED ||
2010 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
2011 "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
2012 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2013 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2015 /* try an invalid system name */
2016 SetLastError(0xdeadbeef);
2017 sid_size = 0;
2018 domain_size = 0;
2019 ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2020 ok(!ret, "Expected 0, got %d\n", ret);
2021 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2022 "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
2023 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2024 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2026 /* try with the computer name as the account name */
2027 domain_size = sizeof(computer_name);
2028 GetComputerNameA(computer_name, &domain_size);
2029 sid_size = 0;
2030 domain_size = 0;
2031 ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2032 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
2033 GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
2034 broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
2035 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
2036 "LookupAccountNameA failed: %d\n", GetLastError());
2037 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2039 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2040 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2041 ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
2042 ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
2043 ok(sid_use == SidTypeDomain, "expected SidTypeDomain, got %d\n", sid_use);
2044 HeapFree(GetProcessHeap(), 0, domain);
2045 HeapFree(GetProcessHeap(), 0, psid);
2048 /* Well Known names */
2049 if (!pCreateWellKnownSid)
2051 win_skip("CreateWellKnownSid not available\n");
2052 return;
2055 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
2057 skip("Non-english locale (skipping well known name creation tests)\n");
2058 return;
2061 check_wellknown_name("LocalService", WinLocalServiceSid);
2062 check_wellknown_name("Local Service", WinLocalServiceSid);
2063 /* 2 spaces */
2064 check_wellknown_name("Local Service", 0);
2065 check_wellknown_name("NetworkService", WinNetworkServiceSid);
2066 check_wellknown_name("Network Service", WinNetworkServiceSid);
2068 /* example of some names where the spaces are not optional */
2069 check_wellknown_name("Terminal Server User", WinTerminalServerSid);
2070 check_wellknown_name("TerminalServer User", 0);
2071 check_wellknown_name("TerminalServerUser", 0);
2072 check_wellknown_name("Terminal ServerUser", 0);
2074 check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
2075 check_wellknown_name("enterprisedomain controllers", 0);
2076 check_wellknown_name("enterprise domaincontrollers", 0);
2077 check_wellknown_name("enterprisedomaincontrollers", 0);
2079 /* case insensitivity */
2080 check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
2082 /* fully qualified account names */
2083 check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
2084 check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
2085 check_wellknown_name("nt authority test\\Network Service", 0);
2086 check_wellknown_name("Dummy\\Network Service", 0);
2087 check_wellknown_name("ntauthority\\Network Service", 0);
2090 static void test_security_descriptor(void)
2092 SECURITY_DESCRIPTOR sd;
2093 char buf[8192];
2094 DWORD size;
2095 BOOL isDefault, isPresent, ret;
2096 PACL pacl;
2097 PSID psid;
2099 SetLastError(0xdeadbeef);
2100 ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
2101 if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2103 win_skip("InitializeSecurityDescriptor is not implemented\n");
2104 return;
2107 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2108 expect_eq(psid, NULL, PSID, "%p");
2109 expect_eq(isDefault, FALSE, BOOL, "%d");
2110 sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
2112 SetLastError(0xdeadbeef);
2113 size = 5;
2114 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
2115 expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
2116 ok(size > 5, "Size not increased\n");
2117 if (size <= 8192)
2119 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
2120 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2121 expect_eq(psid, NULL, PSID, "%p");
2122 expect_eq(isDefault, FALSE, BOOL, "%d");
2123 ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
2124 expect_eq(psid, NULL, PSID, "%p");
2125 expect_eq(isDefault, FALSE, BOOL, "%d");
2126 ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
2127 expect_eq(isPresent, TRUE, BOOL, "%d");
2128 expect_eq(psid, NULL, PSID, "%p");
2129 expect_eq(isDefault, FALSE, BOOL, "%d");
2130 ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
2131 expect_eq(isPresent, TRUE, BOOL, "%d");
2132 expect_eq(psid, NULL, PSID, "%p");
2133 expect_eq(isDefault, FALSE, BOOL, "%d");
2137 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
2138 #define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
2139 static void test_granted_access(HANDLE handle, ACCESS_MASK access,
2140 ACCESS_MASK alt, int line)
2142 OBJECT_BASIC_INFORMATION obj_info;
2143 NTSTATUS status;
2145 if (!pNtQueryObject)
2147 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
2148 return;
2151 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
2152 sizeof(obj_info), NULL );
2153 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2154 if (alt)
2155 ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
2156 obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
2157 "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
2158 else
2159 ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
2160 "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
2163 #define CHECK_SET_SECURITY(o,i,e) \
2164 do{ \
2165 BOOL res; \
2166 DWORD err; \
2167 SetLastError( 0xdeadbeef ); \
2168 res = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
2169 err = GetLastError(); \
2170 if (e == ERROR_SUCCESS) \
2171 ok(res, "SetKernelObjectSecurity failed with %d\n", err); \
2172 else \
2173 ok(!res && err == e, "SetKernelObjectSecurity should have failed " \
2174 "with %s, instead of %d\n", #e, err); \
2175 }while(0)
2177 static void test_process_security(void)
2179 BOOL res;
2180 PTOKEN_OWNER owner;
2181 PTOKEN_PRIMARY_GROUP group;
2182 PSID AdminSid = NULL, UsersSid = NULL;
2183 PACL Acl = NULL;
2184 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
2185 char buffer[MAX_PATH];
2186 PROCESS_INFORMATION info;
2187 STARTUPINFOA startup;
2188 SECURITY_ATTRIBUTES psa;
2189 HANDLE token, event;
2190 DWORD size;
2192 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
2193 res = InitializeAcl(Acl, 256, ACL_REVISION);
2194 if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2196 win_skip("ACLs not implemented - skipping tests\n");
2197 HeapFree(GetProcessHeap(), 0, Acl);
2198 return;
2200 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2202 /* get owner from the token we might be running as a user not admin */
2203 res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
2204 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
2205 if (!res)
2207 HeapFree(GetProcessHeap(), 0, Acl);
2208 return;
2211 res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
2212 ok(!res, "Expected failure, got %d\n", res);
2213 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2214 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2216 owner = HeapAlloc(GetProcessHeap(), 0, size);
2217 res = GetTokenInformation( token, TokenOwner, owner, size, &size );
2218 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2219 AdminSid = ((TOKEN_OWNER*)owner)->Owner;
2221 res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
2222 ok(!res, "Expected failure, got %d\n", res);
2223 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2224 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2226 group = HeapAlloc(GetProcessHeap(), 0, size);
2227 res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
2228 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2229 UsersSid = ((TOKEN_PRIMARY_GROUP*)group)->PrimaryGroup;
2231 CloseHandle( token );
2232 if (!res)
2234 HeapFree(GetProcessHeap(), 0, group);
2235 HeapFree(GetProcessHeap(), 0, owner);
2236 HeapFree(GetProcessHeap(), 0, Acl);
2237 return;
2240 res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
2241 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
2242 res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
2243 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2245 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
2246 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
2247 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
2249 event = CreateEvent( NULL, TRUE, TRUE, "test_event" );
2250 ok(event != NULL, "CreateEvent %d\n", GetLastError());
2252 SecurityDescriptor->Revision = 0;
2253 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
2254 SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
2256 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2257 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2258 CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
2259 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2260 /* NULL DACL is valid and means default DACL from token */
2261 SecurityDescriptor->Control |= SE_DACL_PRESENT;
2262 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2264 /* Set owner and group and dacl */
2265 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
2266 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2267 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
2268 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
2269 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2270 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
2271 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
2272 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
2273 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2275 sprintf(buffer, "%s tests/security.c test", myARGV[0]);
2276 memset(&startup, 0, sizeof(startup));
2277 startup.cb = sizeof(startup);
2278 startup.dwFlags = STARTF_USESHOWWINDOW;
2279 startup.wShowWindow = SW_SHOWNORMAL;
2281 psa.nLength = sizeof(psa);
2282 psa.lpSecurityDescriptor = SecurityDescriptor;
2283 psa.bInheritHandle = TRUE;
2285 /* Doesn't matter what ACL say we should get full access for ourselves */
2286 ok(CreateProcessA( NULL, buffer, &psa, NULL, FALSE, 0, NULL, NULL, &startup, &info ),
2287 "CreateProcess with err:%d\n", GetLastError());
2288 TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS,
2289 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2290 winetest_wait_child_process( info.hProcess );
2292 CloseHandle( info.hProcess );
2293 CloseHandle( info.hThread );
2294 CloseHandle( event );
2295 HeapFree(GetProcessHeap(), 0, group);
2296 HeapFree(GetProcessHeap(), 0, owner);
2297 HeapFree(GetProcessHeap(), 0, Acl);
2298 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
2301 static void test_process_security_child(void)
2303 HANDLE handle, handle1;
2304 BOOL ret;
2305 DWORD err;
2307 handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
2308 ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
2309 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
2311 ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2312 &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS ),
2313 "duplicating handle err:%d\n", GetLastError());
2314 TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
2316 CloseHandle( handle1 );
2318 SetLastError( 0xdeadbeef );
2319 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2320 &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
2321 err = GetLastError();
2322 todo_wine
2323 ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
2324 "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
2326 CloseHandle( handle );
2328 /* These two should fail - they are denied by ACL */
2329 handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
2330 todo_wine
2331 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
2332 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
2333 todo_wine
2334 ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
2336 /* Documented privilege elevation */
2337 ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
2338 &handle, 0, TRUE, DUPLICATE_SAME_ACCESS ),
2339 "duplicating handle err:%d\n", GetLastError());
2340 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS,
2341 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2343 CloseHandle( handle );
2345 /* Same only explicitly asking for all access rights */
2346 ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
2347 &handle, PROCESS_ALL_ACCESS, TRUE, 0 ),
2348 "duplicating handle err:%d\n", GetLastError());
2349 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS,
2350 PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
2351 ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2352 &handle1, PROCESS_VM_READ, TRUE, 0 ),
2353 "duplicating handle err:%d\n", GetLastError());
2354 TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
2355 CloseHandle( handle1 );
2356 CloseHandle( handle );
2359 static void test_impersonation_level(void)
2361 HANDLE Token, ProcessToken;
2362 HANDLE Token2;
2363 DWORD Size;
2364 TOKEN_PRIVILEGES *Privileges;
2365 TOKEN_USER *User;
2366 PRIVILEGE_SET *PrivilegeSet;
2367 BOOL AccessGranted;
2368 BOOL ret;
2369 HKEY hkey;
2370 DWORD error;
2372 pDuplicateTokenEx = (fnDuplicateTokenEx) GetProcAddress(hmod, "DuplicateTokenEx");
2373 if( !pDuplicateTokenEx ) {
2374 win_skip("DuplicateTokenEx is not available\n");
2375 return;
2377 SetLastError(0xdeadbeef);
2378 ret = ImpersonateSelf(SecurityAnonymous);
2379 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2381 win_skip("ImpersonateSelf is not implemented\n");
2382 return;
2384 ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
2385 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2386 ok(!ret, "OpenThreadToken should have failed\n");
2387 error = GetLastError();
2388 ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2389 /* can't perform access check when opening object against an anonymous impersonation token */
2390 todo_wine {
2391 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2392 ok(error == ERROR_INVALID_HANDLE, "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE instead of %d\n", error);
2394 RevertToSelf();
2396 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
2397 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
2399 ret = pDuplicateTokenEx(ProcessToken,
2400 TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
2401 SecurityAnonymous, TokenImpersonation, &Token);
2402 ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
2403 /* can't increase the impersonation level */
2404 ret = DuplicateToken(Token, SecurityIdentification, &Token2);
2405 error = GetLastError();
2406 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
2407 "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2408 /* we can query anything from an anonymous token, including the user */
2409 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
2410 error = GetLastError();
2411 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2412 User = HeapAlloc(GetProcessHeap(), 0, Size);
2413 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
2414 ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
2415 HeapFree(GetProcessHeap(), 0, User);
2417 /* PrivilegeCheck fails with SecurityAnonymous level */
2418 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
2419 error = GetLastError();
2420 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2421 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
2422 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
2423 ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
2425 PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
2426 PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
2427 memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
2428 PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
2429 HeapFree(GetProcessHeap(), 0, Privileges);
2431 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2432 error = GetLastError();
2433 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2435 CloseHandle(Token);
2437 ret = ImpersonateSelf(SecurityIdentification);
2438 ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
2439 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2440 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2442 /* can't perform access check when opening object against an identification impersonation token */
2443 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2444 todo_wine {
2445 ok(error == ERROR_INVALID_HANDLE, "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE instead of %d\n", error);
2447 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2448 ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
2449 CloseHandle(Token);
2450 RevertToSelf();
2452 ret = ImpersonateSelf(SecurityImpersonation);
2453 ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
2454 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2455 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2456 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2457 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
2458 RegCloseKey(hkey);
2459 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2460 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
2461 RevertToSelf();
2463 CloseHandle(Token);
2464 CloseHandle(ProcessToken);
2466 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
2469 static void test_SetEntriesInAcl(void)
2471 DWORD res;
2472 PSID EveryoneSid = NULL, UsersSid = NULL;
2473 PACL OldAcl = NULL, NewAcl;
2474 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2475 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2476 EXPLICIT_ACCESSW ExplicitAccess;
2477 static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
2479 if (!pSetEntriesInAclW)
2481 win_skip("SetEntriesInAclW is not available\n");
2482 return;
2485 NewAcl = (PACL)0xdeadbeef;
2486 res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
2487 if(res == ERROR_CALL_NOT_IMPLEMENTED)
2489 win_skip("SetEntriesInAclW is not implemented\n");
2490 return;
2492 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2493 ok(NewAcl == NULL ||
2494 broken(NewAcl != NULL), /* NT4 */
2495 "NewAcl=%p, expected NULL\n", NewAcl);
2496 LocalFree(NewAcl);
2498 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
2499 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
2500 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2502 win_skip("ACLs not implemented - skipping tests\n");
2503 HeapFree(GetProcessHeap(), 0, OldAcl);
2504 return;
2506 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2508 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2509 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2511 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2512 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
2513 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2515 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
2516 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2518 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
2519 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
2520 ExplicitAccess.grfInheritance = NO_INHERITANCE;
2521 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2522 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2523 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2524 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
2525 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
2526 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2527 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2528 ok(NewAcl != NULL, "returned acl was NULL\n");
2529 LocalFree(NewAcl);
2531 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
2533 skip("Non-english locale (test with hardcoded 'Everyone')\n");
2535 else
2537 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2538 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
2539 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2540 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2541 ok(NewAcl != NULL, "returned acl was NULL\n");
2542 LocalFree(NewAcl);
2544 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
2545 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2546 ok(res == ERROR_INVALID_PARAMETER ||
2547 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2548 "SetEntriesInAclW failed: %u\n", res);
2549 ok(NewAcl == NULL ||
2550 broken(NewAcl != NULL), /* NT4 */
2551 "returned acl wasn't NULL: %p\n", NewAcl);
2553 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2554 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
2555 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2556 ok(res == ERROR_INVALID_PARAMETER ||
2557 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2558 "SetEntriesInAclW failed: %u\n", res);
2559 ok(NewAcl == NULL ||
2560 broken(NewAcl != NULL), /* NT4 */
2561 "returned acl wasn't NULL: %p\n", NewAcl);
2563 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2564 ExplicitAccess.grfAccessMode = SET_ACCESS;
2565 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2566 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2567 ok(NewAcl != NULL, "returned acl was NULL\n");
2568 LocalFree(NewAcl);
2571 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
2572 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2573 ExplicitAccess.Trustee.ptstrName = UsersSid;
2574 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2575 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2576 ok(NewAcl != NULL, "returned acl was NULL\n");
2577 LocalFree(NewAcl);
2579 LocalFree(UsersSid);
2580 LocalFree(EveryoneSid);
2581 HeapFree(GetProcessHeap(), 0, OldAcl);
2584 static void test_GetNamedSecurityInfoA(void)
2586 PSECURITY_DESCRIPTOR pSecDesc;
2587 DWORD revision;
2588 SECURITY_DESCRIPTOR_CONTROL control;
2589 PSID owner;
2590 PSID group;
2591 BOOL owner_defaulted;
2592 BOOL group_defaulted;
2593 DWORD error;
2594 BOOL ret;
2595 CHAR windows_dir[MAX_PATH];
2597 if (!pGetNamedSecurityInfoA)
2599 win_skip("GetNamedSecurityInfoA is not available\n");
2600 return;
2603 ret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
2604 ok(ret, "GetWindowsDirectory failed with error %d\n", GetLastError());
2606 SetLastError(0xdeadbeef);
2607 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
2608 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
2609 NULL, NULL, NULL, NULL, &pSecDesc);
2610 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2612 win_skip("GetNamedSecurityInfoA is not implemented\n");
2613 return;
2615 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
2617 ret = GetSecurityDescriptorControl(pSecDesc, &control, &revision);
2618 ok(ret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
2619 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
2620 broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
2621 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
2622 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
2623 ret = GetSecurityDescriptorOwner(pSecDesc, &owner, &owner_defaulted);
2624 ok(ret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2625 ok(owner != NULL, "owner should not be NULL\n");
2626 ret = GetSecurityDescriptorGroup(pSecDesc, &group, &group_defaulted);
2627 ok(ret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2628 ok(group != NULL, "group should not be NULL\n");
2629 LocalFree(pSecDesc);
2632 static void test_ConvertStringSecurityDescriptor(void)
2634 BOOL ret;
2635 PSECURITY_DESCRIPTOR pSD;
2636 static const WCHAR Blank[] = { 0 };
2638 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
2640 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
2641 return;
2644 SetLastError(0xdeadbeef);
2645 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2646 "D:(A;;GA;;;WD)", 0xdeadbeef, &pSD, NULL);
2647 ok(!ret && GetLastError() == ERROR_UNKNOWN_REVISION,
2648 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_UNKNOWN_REVISION instead of %d\n",
2649 GetLastError());
2651 /* test ACE string type */
2652 SetLastError(0xdeadbeef);
2653 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2654 "D:(A;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2655 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2656 LocalFree(pSD);
2658 SetLastError(0xdeadbeef);
2659 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2660 "D:(D;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2661 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2662 LocalFree(pSD);
2664 SetLastError(0xdeadbeef);
2665 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2666 "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2667 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2668 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2669 GetLastError());
2671 /* test ACE string access rights */
2672 SetLastError(0xdeadbeef);
2673 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2674 "D:(A;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2675 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2676 LocalFree(pSD);
2677 SetLastError(0xdeadbeef);
2678 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2679 "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2680 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2681 LocalFree(pSD);
2682 SetLastError(0xdeadbeef);
2683 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2684 "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2685 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2686 LocalFree(pSD);
2687 SetLastError(0xdeadbeef);
2688 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2689 "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2690 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2691 LocalFree(pSD);
2692 SetLastError(0xdeadbeef);
2693 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2694 "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2695 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2696 LocalFree(pSD);
2697 SetLastError(0xdeadbeef);
2698 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2699 "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2700 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2701 LocalFree(pSD);
2702 SetLastError(0xdeadbeef);
2703 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2704 "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2705 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2706 LocalFree(pSD);
2707 SetLastError(0xdeadbeef);
2708 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2709 "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2710 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2711 LocalFree(pSD);
2713 /* test ACE string access right error case */
2714 SetLastError(0xdeadbeef);
2715 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2716 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, &pSD, NULL);
2717 ok(!ret && GetLastError() == ERROR_INVALID_ACL,
2718 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_ACL instead of %d\n",
2719 GetLastError());
2721 /* test behaviour with NULL parameters */
2722 SetLastError(0xdeadbeef);
2723 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2724 NULL, 0xdeadbeef, &pSD, NULL);
2725 todo_wine
2726 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2727 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2728 GetLastError());
2730 SetLastError(0xdeadbeef);
2731 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
2732 NULL, 0xdeadbeef, &pSD, NULL);
2733 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2734 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2735 GetLastError());
2737 SetLastError(0xdeadbeef);
2738 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2739 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
2740 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2741 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2742 GetLastError());
2744 SetLastError(0xdeadbeef);
2745 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2746 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
2747 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2748 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2749 GetLastError());
2751 /* test behaviour with empty strings */
2752 SetLastError(0xdeadbeef);
2753 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2754 "", SDDL_REVISION_1, &pSD, NULL);
2755 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2757 SetLastError(0xdeadbeef);
2758 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
2759 Blank, SDDL_REVISION_1, &pSD, NULL);
2760 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2762 /* test ACE string SID */
2763 SetLastError(0xdeadbeef);
2764 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2765 "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, &pSD, NULL);
2766 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2767 LocalFree(pSD);
2769 SetLastError(0xdeadbeef);
2770 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2771 "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, &pSD, NULL);
2772 ok(!ret, "Expected failure, got %d\n", ret);
2773 ok(GetLastError() == ERROR_INVALID_ACL || GetLastError() == ERROR_INVALID_SID,
2774 "Expected ERROR_INVALID_ACL or ERROR_INVALID_SID, got %d\n", GetLastError());
2777 static void test_ConvertSecurityDescriptorToString(void)
2779 SECURITY_DESCRIPTOR desc;
2780 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
2781 LPSTR string;
2782 DWORD size;
2783 PSID psid, psid2;
2784 PACL pacl;
2785 char sid_buf[256];
2786 char acl_buf[8192];
2787 ULONG len;
2789 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
2791 win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
2792 return;
2794 if (!pCreateWellKnownSid)
2796 win_skip("CreateWellKnownSid is not available\n");
2797 return;
2800 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
2801 * don't replicate this feature so we only test len >= strlen+1. */
2802 #define CHECK_RESULT_AND_FREE(exp_str) \
2803 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
2804 ok(len >= (lstrlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(exp_str) + 1, len); \
2805 LocalFree(string);
2807 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
2808 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); \
2809 ok(len >= (strlen(string) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(string) + 1, len); \
2810 LocalFree(string);
2812 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
2813 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2814 CHECK_RESULT_AND_FREE("");
2816 size = 4096;
2817 pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
2818 SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
2819 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2820 CHECK_RESULT_AND_FREE("O:S-1-2-0");
2822 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
2823 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2824 CHECK_RESULT_AND_FREE("O:S-1-2-0");
2826 size = sizeof(sid_buf);
2827 pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
2828 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
2829 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2830 CHECK_RESULT_AND_FREE("O:SY");
2832 pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
2833 SetSecurityDescriptorGroup(&desc, psid, TRUE);
2834 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2835 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
2837 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
2838 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
2840 pacl = (PACL)acl_buf;
2841 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
2842 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
2843 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2844 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
2846 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
2847 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2848 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
2850 pConvertStringSidToSidA("S-1-5-6", &psid2);
2851 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
2852 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2853 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
2855 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
2856 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2857 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
2859 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
2860 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2861 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)");
2864 pacl = (PACL)acl_buf;
2865 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
2866 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
2867 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2868 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
2870 /* fails in win2k */
2871 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
2872 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
2873 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
2875 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
2876 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
2879 /* fails in win2k */
2880 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
2881 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
2883 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
2884 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
2888 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
2890 SECURITY_DESCRIPTOR_CONTROL ref;
2891 SECURITY_DESCRIPTOR_CONTROL test;
2893 SECURITY_DESCRIPTOR_CONTROL const mutable
2894 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
2895 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
2896 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
2897 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
2899 SECURITY_DESCRIPTOR_CONTROL const immutable
2900 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
2901 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
2902 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
2903 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
2906 int bit;
2907 DWORD dwRevision;
2908 LPCSTR fmt = "Expected error %s, got %u\n";
2910 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
2912 /* The mutable bits are mutable regardless of the truth of
2913 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
2915 /* Check call barfs if any bit-of-interest is immutable */
2916 for (bit = 0; bit < 16; ++bit)
2918 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
2919 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
2921 SECURITY_DESCRIPTOR_CONTROL ctrl;
2923 DWORD dwExpect = (bitOfInterest & immutable)
2924 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
2925 LPCSTR strExpect = (bitOfInterest & immutable)
2926 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
2928 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
2929 setOrClear ^= bitOfInterest;
2930 SetLastError (0xbebecaca);
2931 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
2932 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2933 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2934 expect_eq(test, ctrl, int, "%x");
2936 ctrl = ref;
2937 setOrClear ^= bitOfInterest;
2938 SetLastError (0xbebecaca);
2939 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
2940 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2941 GetSecurityDescriptorControl (sec, &test, &dwRevision);
2942 expect_eq(test, ref, int, "%x");
2945 /* Check call barfs if any bit-to-set is immutable
2946 even when not a bit-of-interest */
2947 for (bit = 0; bit < 16; ++bit)
2949 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
2950 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
2952 SECURITY_DESCRIPTOR_CONTROL ctrl;
2954 DWORD dwExpect = ((1 << bit) & immutable)
2955 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
2956 LPCSTR strExpect = ((1 << bit) & immutable)
2957 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
2959 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
2960 setOrClear ^= bitsOfInterest;
2961 SetLastError (0xbebecaca);
2962 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
2963 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2964 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2965 expect_eq(test, ctrl, int, "%x");
2967 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
2968 setOrClear ^= bitsOfInterest;
2969 SetLastError (0xbebecaca);
2970 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
2971 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2972 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2973 expect_eq(test, ctrl, int, "%x");
2977 static void test_PrivateObjectSecurity(void)
2979 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
2980 SECURITY_DESCRIPTOR_CONTROL ctrl;
2981 PSECURITY_DESCRIPTOR sec;
2982 DWORD dwDescSize;
2983 DWORD dwRevision;
2984 DWORD retSize;
2985 LPSTR string;
2986 ULONG len;
2987 PSECURITY_DESCRIPTOR buf;
2989 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
2991 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
2992 return;
2995 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
2996 "O:SY"
2997 "G:S-1-5-21-93476-23408-4576"
2998 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
2999 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3000 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
3001 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3003 test_SetSecurityDescriptorControl(sec);
3005 LocalFree(sec);
3007 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3008 "O:SY"
3009 "G:S-1-5-21-93476-23408-4576",
3010 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3012 test_SetSecurityDescriptorControl(sec);
3014 LocalFree(sec);
3016 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3017 "O:SY"
3018 "G:S-1-5-21-93476-23408-4576"
3019 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3020 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3021 buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
3022 pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
3023 GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
3024 expect_eq(ctrl, 0x9014, int, "%x");
3026 ok(GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize),
3027 "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3028 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3029 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3030 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
3031 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3032 expect_eq(ctrl, 0x8000, int, "%x");
3034 ok(GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize),
3035 "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3036 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3037 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed err=%u\n", GetLastError());
3038 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)");
3039 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3040 expect_eq(ctrl, 0x8004, int, "%x");
3042 ok(GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize),
3043 "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
3044 ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
3045 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
3046 CHECK_RESULT_AND_FREE("O:SY"
3047 "G:S-1-5-21-93476-23408-4576"
3048 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3049 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)");
3050 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
3051 expect_eq(ctrl, 0x8014, int, "%x");
3053 SetLastError(0xdeadbeef);
3054 ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
3055 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
3057 LocalFree(sec);
3058 HeapFree(GetProcessHeap(), 0, buf);
3060 #undef CHECK_RESULT_AND_FREE
3061 #undef CHECK_ONE_OF_AND_FREE
3063 static void test_acls(void)
3065 char buffer[256];
3066 PACL pAcl = (PACL)buffer;
3067 BOOL ret;
3069 SetLastError(0xdeadbeef);
3070 ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
3071 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3073 win_skip("InitializeAcl is not implemented\n");
3074 return;
3077 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
3079 SetLastError(0xdeadbeef);
3080 ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
3081 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
3083 SetLastError(0xdeadbeef);
3084 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
3085 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
3087 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
3088 ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
3090 ret = IsValidAcl(pAcl);
3091 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3093 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
3094 ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
3096 ret = IsValidAcl(pAcl);
3097 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3099 SetLastError(0xdeadbeef);
3100 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
3101 if (GetLastError() != ERROR_INVALID_PARAMETER)
3103 ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
3105 ret = IsValidAcl(pAcl);
3106 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
3108 else
3109 win_skip("ACL_REVISION4 is not implemented on NT4\n");
3111 SetLastError(0xdeadbeef);
3112 ret = InitializeAcl(pAcl, sizeof(buffer), -1);
3113 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
3116 static void test_GetSecurityInfo(void)
3118 HANDLE obj;
3119 PSECURITY_DESCRIPTOR sd;
3120 PSID owner, group;
3121 PACL dacl;
3122 DWORD ret;
3124 if (!pGetSecurityInfo)
3126 win_skip("GetSecurityInfo is not available\n");
3127 return;
3130 /* Create something. Files have lots of associated security info. */
3131 obj = CreateFile(myARGV[0], GENERIC_READ, FILE_SHARE_READ, NULL,
3132 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3133 if (obj == INVALID_HANDLE_VALUE)
3135 skip("Couldn't create an object for GetSecurityInfo test\n");
3136 return;
3139 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3140 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3141 &owner, &group, &dacl, NULL, &sd);
3142 if (ret == ERROR_CALL_NOT_IMPLEMENTED)
3144 win_skip("GetSecurityInfo is not implemented\n");
3145 CloseHandle(obj);
3146 return;
3148 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3149 ok(sd != NULL, "GetSecurityInfo\n");
3150 ok(owner != NULL, "GetSecurityInfo\n");
3151 ok(group != NULL, "GetSecurityInfo\n");
3152 ok(dacl != NULL, "GetSecurityInfo\n");
3153 ok(IsValidAcl(dacl), "GetSecurityInfo\n");
3155 LocalFree(sd);
3157 if (!pCreateWellKnownSid)
3159 win_skip("NULL parameter test would crash on NT4\n");
3160 CloseHandle(obj);
3161 return;
3164 /* If we don't ask for the security descriptor, Windows will still give us
3165 the other stuff, leaving us no way to free it. */
3166 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
3167 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3168 &owner, &group, &dacl, NULL, NULL);
3169 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
3170 ok(owner != NULL, "GetSecurityInfo\n");
3171 ok(group != NULL, "GetSecurityInfo\n");
3172 ok(dacl != NULL, "GetSecurityInfo\n");
3173 ok(IsValidAcl(dacl), "GetSecurityInfo\n");
3175 CloseHandle(obj);
3178 START_TEST(security)
3180 init();
3181 if (!hmod) return;
3183 if (myARGC >= 3)
3185 test_process_security_child();
3186 return;
3188 test_sid();
3189 test_trustee();
3190 test_luid();
3191 test_CreateWellKnownSid();
3192 test_FileSecurity();
3193 test_AccessCheck();
3194 test_token_attr();
3195 test_LookupAccountSid();
3196 test_LookupAccountName();
3197 test_security_descriptor();
3198 test_process_security();
3199 test_impersonation_level();
3200 test_SetEntriesInAcl();
3201 test_GetNamedSecurityInfoA();
3202 test_ConvertStringSecurityDescriptor();
3203 test_ConvertSecurityDescriptorToString();
3204 test_PrivateObjectSecurity();
3205 test_acls();
3206 test_GetSecurityInfo();