makefiles: Don't use standard libs for programs that specify -nodefaultlibs.
[wine/zf.git] / dlls / advapi32 / tests / security.c
blobc6f5d4690aed9b47d5c5a5668f384b74410b6bcf
1 /*
2 * Unit tests for security functions
4 * Copyright (c) 2004 Mike McCormack
5 * Copyright (c) 2011 Dmitry Timoshkov
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include <stdarg.h>
23 #include <stdio.h>
25 #include "ntstatus.h"
26 #define WIN32_NO_STATUS
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "winternl.h"
31 #include "aclapi.h"
32 #include "winnt.h"
33 #include "sddl.h"
34 #include "ntsecapi.h"
35 #include "lmcons.h"
37 #include "wine/test.h"
39 #ifndef PROCESS_QUERY_LIMITED_INFORMATION
40 #define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
41 #endif
43 /* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
44 #define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)
45 #define PROCESS_ALL_ACCESS_VISTA (PROCESS_ALL_ACCESS | 0xf000)
47 #ifndef EVENT_QUERY_STATE
48 #define EVENT_QUERY_STATE 0x0001
49 #endif
51 #ifndef SEMAPHORE_QUERY_STATE
52 #define SEMAPHORE_QUERY_STATE 0x0001
53 #endif
55 #ifndef THREAD_SET_LIMITED_INFORMATION
56 #define THREAD_SET_LIMITED_INFORMATION 0x0400
57 #define THREAD_QUERY_LIMITED_INFORMATION 0x0800
58 #endif
60 #define THREAD_ALL_ACCESS_NT4 (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff)
61 #define THREAD_ALL_ACCESS_VISTA (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xffff)
63 #define expect_eq(expr, value, type, format) { type ret_ = expr; ok((value) == ret_, #expr " expected " format " got " format "\n", (value), (ret_)); }
65 static BOOL (WINAPI *pAddAccessAllowedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
66 static BOOL (WINAPI *pAddAccessDeniedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
67 static BOOL (WINAPI *pAddAuditAccessAceEx)(PACL, DWORD, DWORD, DWORD, PSID, BOOL, BOOL);
68 static BOOL (WINAPI *pAddMandatoryAce)(PACL,DWORD,DWORD,DWORD,PSID);
69 static VOID (WINAPI *pBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
70 static VOID (WINAPI *pBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
71 static VOID (WINAPI *pBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
72 POBJECTS_AND_NAME_A pObjName,
73 SE_OBJECT_TYPE ObjectType,
74 LPSTR ObjectTypeName,
75 LPSTR InheritedObjectTypeName,
76 LPSTR Name );
77 static VOID (WINAPI *pBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
78 POBJECTS_AND_SID pObjSid,
79 GUID* pObjectGuid,
80 GUID* pInheritedObjectGuid,
81 PSID pSid );
82 static LPSTR (WINAPI *pGetTrusteeNameA)( PTRUSTEEA pTrustee );
83 static BOOL (WINAPI *pCheckTokenMembership)(HANDLE, PSID, PBOOL);
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 static BOOL (WINAPI *pSetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
89 PSECURITY_DESCRIPTOR);
90 static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
91 PSID*, PSID*, PACL*, PACL*,
92 PSECURITY_DESCRIPTOR*);
93 static DWORD (WINAPI *pSetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
94 PSID, PSID, PACL, PACL);
95 static DWORD (WINAPI *pRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
96 static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
97 SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
99 static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
100 static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
101 static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
102 SECURITY_DESCRIPTOR_CONTROL);
103 static DWORD (WINAPI *pSetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
104 PSID, PSID, PACL, PACL);
105 static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
106 PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
107 static BOOL (WINAPI *pCreateRestrictedToken)(HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD,
108 PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
109 static NTSTATUS (WINAPI *pNtSetSecurityObject)(HANDLE,SECURITY_INFORMATION,PSECURITY_DESCRIPTOR);
110 static NTSTATUS (WINAPI *pNtCreateFile)(PHANDLE,ACCESS_MASK,POBJECT_ATTRIBUTES,PIO_STATUS_BLOCK,PLARGE_INTEGER,ULONG,ULONG,ULONG,ULONG,PVOID,ULONG);
111 static BOOL (WINAPI *pRtlDosPathNameToNtPathName_U)(LPCWSTR,PUNICODE_STRING,PWSTR*,CURDIR*);
112 static NTSTATUS (WINAPI *pRtlAnsiStringToUnicodeString)(PUNICODE_STRING,PCANSI_STRING,BOOLEAN);
113 static BOOL (WINAPI *pGetWindowsAccountDomainSid)(PSID,PSID,DWORD*);
114 static BOOL (WINAPI *pEqualDomainSid)(PSID,PSID,BOOL*);
115 static void (WINAPI *pRtlInitAnsiString)(PANSI_STRING,PCSZ);
116 static NTSTATUS (WINAPI *pRtlFreeUnicodeString)(PUNICODE_STRING);
117 static PSID_IDENTIFIER_AUTHORITY (WINAPI *pGetSidIdentifierAuthority)(PSID);
118 static DWORD (WINAPI *pGetExplicitEntriesFromAclW)(PACL,PULONG,PEXPLICIT_ACCESSW*);
120 static HMODULE hmod;
121 static int myARGC;
122 static char** myARGV;
124 static const char* debugstr_sid(PSID sid)
126 LPSTR sidstr;
127 DWORD le = GetLastError();
128 const char *res;
130 if (!ConvertSidToStringSidA(sid, &sidstr))
131 res = wine_dbg_sprintf("ConvertSidToStringSidA failed le=%u", GetLastError());
132 else
134 res = __wine_dbg_strdup(sidstr);
135 LocalFree(sidstr);
137 /* Restore the last error in case ConvertSidToStringSidA() modified it */
138 SetLastError(le);
139 return res;
142 struct sidRef
144 SID_IDENTIFIER_AUTHORITY auth;
145 const char *refStr;
148 static void init(void)
150 HMODULE hntdll;
152 hntdll = GetModuleHandleA("ntdll.dll");
153 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
154 pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
155 pNtSetSecurityObject = (void *)GetProcAddress(hntdll, "NtSetSecurityObject");
156 pNtCreateFile = (void *)GetProcAddress(hntdll, "NtCreateFile");
157 pRtlDosPathNameToNtPathName_U = (void *)GetProcAddress(hntdll, "RtlDosPathNameToNtPathName_U");
158 pRtlAnsiStringToUnicodeString = (void *)GetProcAddress(hntdll, "RtlAnsiStringToUnicodeString");
159 pRtlInitAnsiString = (void *)GetProcAddress(hntdll, "RtlInitAnsiString");
160 pRtlFreeUnicodeString = (void *)GetProcAddress(hntdll, "RtlFreeUnicodeString");
162 hmod = GetModuleHandleA("advapi32.dll");
163 pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
164 pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
165 pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
166 pAddMandatoryAce = (void *)GetProcAddress(hmod, "AddMandatoryAce");
167 pCheckTokenMembership = (void *)GetProcAddress(hmod, "CheckTokenMembership");
168 pConvertStringSecurityDescriptorToSecurityDescriptorW =
169 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
170 pConvertSecurityDescriptorToStringSecurityDescriptorA =
171 (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
172 pSetFileSecurityA = (void *)GetProcAddress(hmod, "SetFileSecurityA" );
173 pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
174 pSetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "SetNamedSecurityInfoA");
175 pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
176 pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
177 pSetSecurityInfo = (void *)GetProcAddress(hmod, "SetSecurityInfo");
178 pCreateRestrictedToken = (void *)GetProcAddress(hmod, "CreateRestrictedToken");
179 pGetWindowsAccountDomainSid = (void *)GetProcAddress(hmod, "GetWindowsAccountDomainSid");
180 pEqualDomainSid = (void *)GetProcAddress(hmod, "EqualDomainSid");
181 pGetSidIdentifierAuthority = (void *)GetProcAddress(hmod, "GetSidIdentifierAuthority");
182 pDuplicateTokenEx = (void *)GetProcAddress(hmod, "DuplicateTokenEx");
183 pGetExplicitEntriesFromAclW = (void *)GetProcAddress(hmod, "GetExplicitEntriesFromAclW");
185 myARGC = winetest_get_mainargs( &myARGV );
188 static SECURITY_DESCRIPTOR* test_get_security_descriptor(HANDLE handle, int line)
190 /* use HeapFree(GetProcessHeap(), 0, sd); when done */
191 DWORD ret, length, needed;
192 SECURITY_DESCRIPTOR *sd;
194 needed = 0xdeadbeef;
195 SetLastError(0xdeadbeef);
196 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
197 NULL, 0, &needed);
198 ok_(__FILE__, line)(!ret, "GetKernelObjectSecurity should fail\n");
199 ok_(__FILE__, line)(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
200 ok_(__FILE__, line)(needed != 0xdeadbeef, "GetKernelObjectSecurity should return required buffer length\n");
202 length = needed;
203 sd = HeapAlloc(GetProcessHeap(), 0, length);
205 needed = 0xdeadbeef;
206 SetLastError(0xdeadbeef);
207 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
208 sd, length, &needed);
209 ok_(__FILE__, line)(ret, "GetKernelObjectSecurity error %d\n", GetLastError());
210 ok_(__FILE__, line)(needed == length || needed == 0 /* file, pipe */, "GetKernelObjectSecurity should return %u instead of %u\n", length, needed);
211 return sd;
214 static void test_owner_equal(HANDLE Handle, PSID expected, int line)
216 BOOL res;
217 SECURITY_DESCRIPTOR *queriedSD = NULL;
218 PSID owner;
219 BOOL owner_defaulted;
221 queriedSD = test_get_security_descriptor( Handle, line );
223 res = GetSecurityDescriptorOwner(queriedSD, &owner, &owner_defaulted);
224 ok_(__FILE__, line)(res, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
226 ok_(__FILE__, line)(EqualSid(owner, expected), "Owner SIDs are not equal %s != %s\n",
227 debugstr_sid(owner), debugstr_sid(expected));
228 ok_(__FILE__, line)(!owner_defaulted, "Defaulted is true\n");
230 HeapFree(GetProcessHeap(), 0, queriedSD);
233 static void test_group_equal(HANDLE Handle, PSID expected, int line)
235 BOOL res;
236 SECURITY_DESCRIPTOR *queriedSD = NULL;
237 PSID group;
238 BOOL group_defaulted;
240 queriedSD = test_get_security_descriptor( Handle, line );
242 res = GetSecurityDescriptorGroup(queriedSD, &group, &group_defaulted);
243 ok_(__FILE__, line)(res, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
245 ok_(__FILE__, line)(EqualSid(group, expected), "Group SIDs are not equal %s != %s\n",
246 debugstr_sid(group), debugstr_sid(expected));
247 ok_(__FILE__, line)(!group_defaulted, "Defaulted is true\n");
249 HeapFree(GetProcessHeap(), 0, queriedSD);
252 static void test_sid(void)
254 struct sidRef refs[] = {
255 { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
256 { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
257 { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
258 { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
259 { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
260 { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
262 static const struct
264 const char *name;
265 const char *sid;
266 unsigned int optional;
268 str_to_sid_tests[] =
270 { "WD", "S-1-1-0" },
271 { "CO", "S-1-3-0" },
272 { "CG", "S-1-3-1" },
273 { "OW", "S-1-3-4", 1 }, /* Vista+ */
274 { "NU", "S-1-5-2" },
275 { "IU", "S-1-5-4" },
276 { "SU", "S-1-5-6" },
277 { "AN", "S-1-5-7" },
278 { "ED", "S-1-5-9" },
279 { "PS", "S-1-5-10" },
280 { "AU", "S-1-5-11" },
281 { "RC", "S-1-5-12" },
282 { "SY", "S-1-5-18" },
283 { "LS", "S-1-5-19" },
284 { "NS", "S-1-5-20" },
285 { "LA", "S-1-5-21-*-*-*-500" },
286 { "LG", "S-1-5-21-*-*-*-501" },
287 { "BO", "S-1-5-32-551" },
288 { "BA", "S-1-5-32-544" },
289 { "BU", "S-1-5-32-545" },
290 { "BG", "S-1-5-32-546" },
291 { "PU", "S-1-5-32-547" },
292 { "AO", "S-1-5-32-548" },
293 { "SO", "S-1-5-32-549" },
294 { "PO", "S-1-5-32-550" },
295 { "RE", "S-1-5-32-552" },
296 { "RU", "S-1-5-32-554" },
297 { "RD", "S-1-5-32-555" },
298 { "NO", "S-1-5-32-556" },
299 { "AC", "S-1-15-2-1", 1 }, /* Win8+ */
300 { "CA", "", 1 },
301 { "DA", "", 1 },
302 { "DC", "", 1 },
303 { "DD", "", 1 },
304 { "DG", "", 1 },
305 { "DU", "", 1 },
306 { "EA", "", 1 },
307 { "PA", "", 1 },
308 { "RS", "", 1 },
309 { "SA", "", 1 },
312 const char noSubAuthStr[] = "S-1-5";
313 unsigned int i;
314 PSID psid = NULL;
315 SID *pisid;
316 BOOL r, ret;
317 LPSTR str = NULL;
319 r = ConvertStringSidToSidA( NULL, NULL );
320 ok( !r, "expected failure with NULL parameters\n" );
321 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
322 return;
323 ok( GetLastError() == ERROR_INVALID_PARAMETER,
324 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
325 GetLastError() );
327 r = ConvertStringSidToSidA( refs[0].refStr, NULL );
328 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
329 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
330 GetLastError() );
332 r = ConvertStringSidToSidA( NULL, &psid );
333 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
334 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
335 GetLastError() );
337 r = ConvertStringSidToSidA( noSubAuthStr, &psid );
338 ok( !r,
339 "expected failure with no sub authorities\n" );
340 ok( GetLastError() == ERROR_INVALID_SID,
341 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
342 GetLastError() );
344 ok(ConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
345 pisid = psid;
346 ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
347 ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expected 21, got %d\n", pisid->SubAuthority[0]);
348 ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expected 4576, got %d\n", pisid->SubAuthority[3]);
349 LocalFree(str);
350 LocalFree(psid);
352 for( i = 0; i < ARRAY_SIZE(refs); i++ )
354 r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
355 &psid );
356 ok( r, "failed to allocate sid\n" );
357 r = ConvertSidToStringSidA( psid, &str );
358 ok( r, "failed to convert sid\n" );
359 if (r)
361 ok( !strcmp( str, refs[i].refStr ),
362 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
363 LocalFree( str );
365 if( psid )
366 FreeSid( psid );
368 r = ConvertStringSidToSidA( refs[i].refStr, &psid );
369 ok( r, "failed to parse sid string\n" );
370 pisid = psid;
371 ok( pisid &&
372 !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
373 sizeof(refs[i].auth) ),
374 "string sid %s didn't parse to expected value\n"
375 "(got 0x%04x%08x, expected 0x%04x%08x)\n",
376 refs[i].refStr,
377 MAKEWORD( pisid->IdentifierAuthority.Value[1],
378 pisid->IdentifierAuthority.Value[0] ),
379 MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
380 pisid->IdentifierAuthority.Value[4] ),
381 MAKEWORD( pisid->IdentifierAuthority.Value[3],
382 pisid->IdentifierAuthority.Value[2] ) ),
383 MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
384 MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
385 MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
386 if( psid )
387 LocalFree( psid );
390 for (i = 0; i < ARRAY_SIZE(str_to_sid_tests); i++)
392 char *str;
394 ret = ConvertStringSidToSidA(str_to_sid_tests[i].name, &psid);
395 if (!ret && str_to_sid_tests[i].optional)
397 skip("%u: failed to convert %s.\n", i, str_to_sid_tests[i].name);
398 continue;
400 ok(ret, "%u: failed to convert string to sid.\n", i);
402 if (str_to_sid_tests[i].optional || !strcmp(str_to_sid_tests[i].name, "LA") ||
403 !strcmp(str_to_sid_tests[i].name, "LG"))
405 LocalFree(psid);
406 continue;
409 ret = ConvertSidToStringSidA(psid, &str);
410 ok(ret, "%u: failed to convert SID to string.\n", i);
411 ok(!strcmp(str, str_to_sid_tests[i].sid), "%u: unexpected sid %s.\n", i, str);
412 LocalFree(psid);
413 LocalFree(str);
417 static void test_trustee(void)
419 GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
420 GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
421 GUID ZeroGuid;
422 OBJECTS_AND_NAME_A oan;
423 OBJECTS_AND_SID oas;
424 TRUSTEEA trustee;
425 PSID psid;
426 char szObjectTypeName[] = "ObjectTypeName";
427 char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
428 char szTrusteeName[] = "szTrusteeName";
429 SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
431 memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
433 pBuildTrusteeWithSidA = (void *)GetProcAddress( hmod, "BuildTrusteeWithSidA" );
434 pBuildTrusteeWithNameA = (void *)GetProcAddress( hmod, "BuildTrusteeWithNameA" );
435 pBuildTrusteeWithObjectsAndNameA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
436 pBuildTrusteeWithObjectsAndSidA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
437 pGetTrusteeNameA = (void *)GetProcAddress (hmod, "GetTrusteeNameA" );
438 if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
439 !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
440 !pGetTrusteeNameA )
441 return;
443 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
445 trace( "failed to init SID\n" );
446 return;
449 /* test BuildTrusteeWithSidA */
450 memset( &trustee, 0xff, sizeof trustee );
451 pBuildTrusteeWithSidA( &trustee, psid );
453 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
454 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
455 "MultipleTrusteeOperation wrong\n");
456 ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
457 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
458 ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
460 /* test BuildTrusteeWithObjectsAndSidA (test 1) */
461 memset( &trustee, 0xff, sizeof trustee );
462 memset( &oas, 0xff, sizeof(oas) );
463 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
464 &InheritedObjectType, psid);
466 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
467 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
468 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
469 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
470 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
472 ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
473 ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
474 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
475 ok(oas.pSid == psid, "pSid wrong\n");
477 /* test GetTrusteeNameA */
478 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
480 /* test BuildTrusteeWithObjectsAndSidA (test 2) */
481 memset( &trustee, 0xff, sizeof trustee );
482 memset( &oas, 0xff, sizeof(oas) );
483 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
484 &InheritedObjectType, psid);
486 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
487 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
488 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
489 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
490 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
492 ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
493 ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
494 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
495 ok(oas.pSid == psid, "pSid wrong\n");
497 FreeSid( psid );
499 /* test BuildTrusteeWithNameA */
500 memset( &trustee, 0xff, sizeof trustee );
501 pBuildTrusteeWithNameA( &trustee, szTrusteeName );
503 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
504 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
505 "MultipleTrusteeOperation wrong\n");
506 ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
507 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
508 ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
510 /* test BuildTrusteeWithObjectsAndNameA (test 1) */
511 memset( &trustee, 0xff, sizeof trustee );
512 memset( &oan, 0xff, sizeof(oan) );
513 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
514 szInheritedObjectTypeName, szTrusteeName);
516 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
517 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
518 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
519 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
520 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
522 ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
523 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
524 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
525 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
527 /* test GetTrusteeNameA */
528 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
530 /* test BuildTrusteeWithObjectsAndNameA (test 2) */
531 memset( &trustee, 0xff, sizeof trustee );
532 memset( &oan, 0xff, sizeof(oan) );
533 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
534 szInheritedObjectTypeName, szTrusteeName);
536 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
537 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
538 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
539 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
540 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
542 ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
543 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
544 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
545 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
547 /* test BuildTrusteeWithObjectsAndNameA (test 3) */
548 memset( &trustee, 0xff, sizeof trustee );
549 memset( &oan, 0xff, sizeof(oan) );
550 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
551 NULL, szTrusteeName);
553 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
554 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
555 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
556 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
557 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
559 ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
560 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
561 ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
562 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
565 /* If the first isn't defined, assume none is */
566 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
567 #define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
568 #define SE_CREATE_TOKEN_PRIVILEGE 2L
569 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
570 #define SE_LOCK_MEMORY_PRIVILEGE 4L
571 #define SE_INCREASE_QUOTA_PRIVILEGE 5L
572 #define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
573 #define SE_TCB_PRIVILEGE 7L
574 #define SE_SECURITY_PRIVILEGE 8L
575 #define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
576 #define SE_LOAD_DRIVER_PRIVILEGE 10L
577 #define SE_SYSTEM_PROFILE_PRIVILEGE 11L
578 #define SE_SYSTEMTIME_PRIVILEGE 12L
579 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
580 #define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
581 #define SE_CREATE_PAGEFILE_PRIVILEGE 15L
582 #define SE_CREATE_PERMANENT_PRIVILEGE 16L
583 #define SE_BACKUP_PRIVILEGE 17L
584 #define SE_RESTORE_PRIVILEGE 18L
585 #define SE_SHUTDOWN_PRIVILEGE 19L
586 #define SE_DEBUG_PRIVILEGE 20L
587 #define SE_AUDIT_PRIVILEGE 21L
588 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
589 #define SE_CHANGE_NOTIFY_PRIVILEGE 23L
590 #define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
591 #define SE_UNDOCK_PRIVILEGE 25L
592 #define SE_SYNC_AGENT_PRIVILEGE 26L
593 #define SE_ENABLE_DELEGATION_PRIVILEGE 27L
594 #define SE_MANAGE_VOLUME_PRIVILEGE 28L
595 #define SE_IMPERSONATE_PRIVILEGE 29L
596 #define SE_CREATE_GLOBAL_PRIVILEGE 30L
597 #define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
598 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
600 static void test_allocateLuid(void)
602 BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
603 LUID luid1, luid2;
604 BOOL ret;
606 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
607 if (!pAllocateLocallyUniqueId) return;
609 ret = pAllocateLocallyUniqueId(&luid1);
610 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
611 return;
613 ok(ret,
614 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
615 ret = pAllocateLocallyUniqueId(&luid2);
616 ok( ret,
617 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
618 ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
619 "AllocateLocallyUniqueId returned a well-known LUID\n");
620 ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
621 "AllocateLocallyUniqueId returned non-unique LUIDs\n");
622 ret = pAllocateLocallyUniqueId(NULL);
623 ok( !ret && GetLastError() == ERROR_NOACCESS,
624 "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
625 GetLastError());
628 static void test_lookupPrivilegeName(void)
630 BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
631 char buf[MAX_PATH]; /* arbitrary, seems long enough */
632 DWORD cchName = sizeof(buf);
633 LUID luid = { 0, 0 };
634 LONG i;
635 BOOL ret;
637 /* check whether it's available first */
638 pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
639 if (!pLookupPrivilegeNameA) return;
640 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
641 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
642 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
643 return;
645 /* check with a short buffer */
646 cchName = 0;
647 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
648 ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
649 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
650 "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
651 GetLastError());
652 ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
653 "LookupPrivilegeNameA returned an incorrect required length for\n"
654 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
655 lstrlenA("SeCreateTokenPrivilege") + 1);
656 /* check a known value and its returned length on success */
657 cchName = sizeof(buf);
658 ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
659 cchName == strlen("SeCreateTokenPrivilege"),
660 "LookupPrivilegeNameA returned an incorrect output length for\n"
661 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
662 (int)strlen("SeCreateTokenPrivilege"));
663 /* check known values */
664 for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
666 luid.LowPart = i;
667 cchName = sizeof(buf);
668 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
669 ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
670 "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
672 /* check a bogus LUID */
673 luid.LowPart = 0xdeadbeef;
674 cchName = sizeof(buf);
675 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
676 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
677 "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
678 GetLastError());
679 /* check on a bogus system */
680 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
681 cchName = sizeof(buf);
682 ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
683 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
684 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
685 "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
686 GetLastError());
689 struct NameToLUID
691 const char *name;
692 DWORD lowPart;
695 static void test_lookupPrivilegeValue(void)
697 static const struct NameToLUID privs[] = {
698 { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
699 { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
700 { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
701 { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
702 { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
703 { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
704 { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
705 { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
706 { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
707 { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
708 { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
709 { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
710 { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
711 { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
712 { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
713 { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
714 { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
715 { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
716 { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
717 { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
718 { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
719 { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
720 { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
721 { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
722 { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
723 { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
724 { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
725 { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
726 { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
728 BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
729 unsigned int i;
730 LUID luid;
731 BOOL ret;
733 /* check whether it's available first */
734 pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
735 if (!pLookupPrivilegeValueA) return;
736 ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
737 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
738 return;
740 /* check a bogus system name */
741 ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
742 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
743 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
744 "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
745 GetLastError());
746 /* check a NULL string */
747 ret = pLookupPrivilegeValueA(NULL, 0, &luid);
748 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
749 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
750 GetLastError());
751 /* check a bogus privilege name */
752 ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
753 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
754 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
755 GetLastError());
756 /* check case insensitive */
757 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
758 ok( ret,
759 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
760 GetLastError());
761 for (i = 0; i < ARRAY_SIZE(privs); i++)
763 /* Not all privileges are implemented on all Windows versions, so
764 * don't worry if the call fails
766 if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
768 ok(luid.LowPart == privs[i].lowPart,
769 "LookupPrivilegeValueA returned an invalid LUID for %s\n",
770 privs[i].name);
775 static void test_luid(void)
777 test_allocateLuid();
778 test_lookupPrivilegeName();
779 test_lookupPrivilegeValue();
782 static void test_FileSecurity(void)
784 char wintmpdir [MAX_PATH];
785 char path [MAX_PATH];
786 char file [MAX_PATH];
787 HANDLE fh, token;
788 DWORD sdSize, retSize, rc, granted, priv_set_len;
789 PRIVILEGE_SET priv_set;
790 BOOL status;
791 BYTE *sd;
792 GENERIC_MAPPING mapping = { FILE_READ_DATA, FILE_WRITE_DATA, FILE_EXECUTE, FILE_ALL_ACCESS };
793 const SECURITY_INFORMATION request = OWNER_SECURITY_INFORMATION
794 | GROUP_SECURITY_INFORMATION
795 | DACL_SECURITY_INFORMATION;
797 if (!pSetFileSecurityA) {
798 win_skip ("SetFileSecurity is not available\n");
799 return;
802 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
803 win_skip ("GetTempPathA failed\n");
804 return;
807 /* Create a temporary directory and in it a temporary file */
808 strcat (strcpy (path, wintmpdir), "rary");
809 SetLastError(0xdeadbeef);
810 rc = CreateDirectoryA (path, NULL);
811 ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
812 "failed for '%s' with %d\n", path, GetLastError());
814 strcat (strcpy (file, path), "\\ess");
815 SetLastError(0xdeadbeef);
816 fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
817 ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
818 "failed for '%s' with %d\n", file, GetLastError());
819 CloseHandle (fh);
821 /* For the temporary file ... */
823 /* Get size needed */
824 retSize = 0;
825 SetLastError(0xdeadbeef);
826 rc = GetFileSecurityA (file, request, NULL, 0, &retSize);
827 if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
828 win_skip("GetFileSecurityA is not implemented\n");
829 goto cleanup;
831 ok (!rc, "GetFileSecurityA "
832 "was expected to fail for '%s'\n", file);
833 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
834 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
835 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
837 sdSize = retSize;
838 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
840 /* Get security descriptor for real */
841 retSize = -1;
842 SetLastError(0xdeadbeef);
843 rc = GetFileSecurityA (file, request, sd, sdSize, &retSize);
844 ok (rc, "GetFileSecurityA "
845 "was not expected to fail '%s': %d\n", file, GetLastError());
846 ok (retSize == sdSize ||
847 broken(retSize == 0), /* NT4 */
848 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
850 /* Use it to set security descriptor */
851 SetLastError(0xdeadbeef);
852 rc = pSetFileSecurityA (file, request, sd);
853 ok (rc, "SetFileSecurityA "
854 "was not expected to fail '%s': %d\n", file, GetLastError());
856 HeapFree (GetProcessHeap (), 0, sd);
858 /* Repeat for the temporary directory ... */
860 /* Get size needed */
861 retSize = 0;
862 SetLastError(0xdeadbeef);
863 rc = GetFileSecurityA (path, request, NULL, 0, &retSize);
864 ok (!rc, "GetFileSecurityA "
865 "was expected to fail for '%s'\n", path);
866 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
867 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
868 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
870 sdSize = retSize;
871 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
873 /* Get security descriptor for real */
874 retSize = -1;
875 SetLastError(0xdeadbeef);
876 rc = GetFileSecurityA (path, request, sd, sdSize, &retSize);
877 ok (rc, "GetFileSecurityA "
878 "was not expected to fail '%s': %d\n", path, GetLastError());
879 ok (retSize == sdSize ||
880 broken(retSize == 0), /* NT4 */
881 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
883 /* Use it to set security descriptor */
884 SetLastError(0xdeadbeef);
885 rc = pSetFileSecurityA (path, request, sd);
886 ok (rc, "SetFileSecurityA "
887 "was not expected to fail '%s': %d\n", path, GetLastError());
888 HeapFree (GetProcessHeap (), 0, sd);
890 /* Old test */
891 strcpy (wintmpdir, "\\Should not exist");
892 SetLastError(0xdeadbeef);
893 rc = GetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
894 ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
895 ok (GetLastError() == ERROR_FILE_NOT_FOUND,
896 "last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());
898 cleanup:
899 /* Remove temporary file and directory */
900 DeleteFileA(file);
901 RemoveDirectoryA(path);
903 /* Test file access permissions for a file with FILE_ATTRIBUTE_ARCHIVE */
904 SetLastError(0xdeadbeef);
905 rc = GetTempPathA(sizeof(wintmpdir), wintmpdir);
906 ok(rc, "GetTempPath error %d\n", GetLastError());
908 SetLastError(0xdeadbeef);
909 rc = GetTempFileNameA(wintmpdir, "tmp", 0, file);
910 ok(rc, "GetTempFileName error %d\n", GetLastError());
912 rc = GetFileAttributesA(file);
913 rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
914 ok(rc == FILE_ATTRIBUTE_ARCHIVE, "expected FILE_ATTRIBUTE_ARCHIVE got %#x\n", rc);
916 rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
917 NULL, 0, &sdSize);
918 ok(!rc, "GetFileSecurity should fail\n");
919 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
920 "expected ERROR_INSUFFICIENT_BUFFER got %d\n", GetLastError());
921 ok(sdSize > sizeof(SECURITY_DESCRIPTOR), "got sd size %d\n", sdSize);
923 sd = HeapAlloc(GetProcessHeap (), 0, sdSize);
924 retSize = 0xdeadbeef;
925 SetLastError(0xdeadbeef);
926 rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
927 sd, sdSize, &retSize);
928 ok(rc, "GetFileSecurity error %d\n", GetLastError());
929 ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
931 SetLastError(0xdeadbeef);
932 rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
933 ok(!rc, "OpenThreadToken should fail\n");
934 ok(GetLastError() == ERROR_NO_TOKEN, "expected ERROR_NO_TOKEN, got %d\n", GetLastError());
936 SetLastError(0xdeadbeef);
937 rc = ImpersonateSelf(SecurityIdentification);
938 ok(rc, "ImpersonateSelf error %d\n", GetLastError());
940 SetLastError(0xdeadbeef);
941 rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
942 ok(rc, "OpenThreadToken error %d\n", GetLastError());
944 SetLastError(0xdeadbeef);
945 rc = RevertToSelf();
946 ok(rc, "RevertToSelf error %d\n", GetLastError());
948 priv_set_len = sizeof(priv_set);
949 granted = 0xdeadbeef;
950 status = 0xdeadbeef;
951 SetLastError(0xdeadbeef);
952 rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
953 ok(rc, "AccessCheck error %d\n", GetLastError());
954 ok(status == 1, "expected 1, got %d\n", status);
955 ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
957 granted = 0xdeadbeef;
958 status = 0xdeadbeef;
959 SetLastError(0xdeadbeef);
960 rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
961 ok(rc, "AccessCheck error %d\n", GetLastError());
962 ok(status == 1, "expected 1, got %d\n", status);
963 ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
965 granted = 0xdeadbeef;
966 status = 0xdeadbeef;
967 SetLastError(0xdeadbeef);
968 rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
969 ok(rc, "AccessCheck error %d\n", GetLastError());
970 ok(status == 1, "expected 1, got %d\n", status);
971 ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
973 granted = 0xdeadbeef;
974 status = 0xdeadbeef;
975 SetLastError(0xdeadbeef);
976 rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
977 ok(rc, "AccessCheck error %d\n", GetLastError());
978 ok(status == 1, "expected 1, got %d\n", status);
979 ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
981 granted = 0xdeadbeef;
982 status = 0xdeadbeef;
983 SetLastError(0xdeadbeef);
984 rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
985 ok(rc, "AccessCheck error %d\n", GetLastError());
986 ok(status == 1, "expected 1, got %d\n", status);
987 ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
989 granted = 0xdeadbeef;
990 status = 0xdeadbeef;
991 SetLastError(0xdeadbeef);
992 rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
993 ok(rc, "AccessCheck error %d\n", GetLastError());
994 ok(status == 1, "expected 1, got %d\n", status);
995 ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
997 granted = 0xdeadbeef;
998 status = 0xdeadbeef;
999 SetLastError(0xdeadbeef);
1000 rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
1001 ok(rc, "AccessCheck error %d\n", GetLastError());
1002 ok(status == 1, "expected 1, got %d\n", status);
1003 ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
1005 SetLastError(0xdeadbeef);
1006 rc = AccessCheck(sd, token, 0xffffffff, &mapping, &priv_set, &priv_set_len, &granted, &status);
1007 ok(!rc, "AccessCheck should fail\n");
1008 ok(GetLastError() == ERROR_GENERIC_NOT_MAPPED, "expected ERROR_GENERIC_NOT_MAPPED, got %d\n", GetLastError());
1010 /* Test file access permissions for a file with FILE_ATTRIBUTE_READONLY */
1011 SetLastError(0xdeadbeef);
1012 fh = CreateFileA(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
1013 ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
1014 retSize = 0xdeadbeef;
1015 SetLastError(0xdeadbeef);
1016 rc = WriteFile(fh, "1", 1, &retSize, NULL);
1017 ok(!rc, "WriteFile should fail\n");
1018 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1019 ok(retSize == 0, "expected 0, got %d\n", retSize);
1020 CloseHandle(fh);
1022 rc = GetFileAttributesA(file);
1023 rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
1024 todo_wine
1025 ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
1026 "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
1028 SetLastError(0xdeadbeef);
1029 rc = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
1030 ok(rc, "SetFileAttributes error %d\n", GetLastError());
1031 SetLastError(0xdeadbeef);
1032 rc = DeleteFileA(file);
1033 ok(rc, "DeleteFile error %d\n", GetLastError());
1035 SetLastError(0xdeadbeef);
1036 fh = CreateFileA(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
1037 ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
1038 retSize = 0xdeadbeef;
1039 SetLastError(0xdeadbeef);
1040 rc = WriteFile(fh, "1", 1, &retSize, NULL);
1041 ok(!rc, "WriteFile should fail\n");
1042 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1043 ok(retSize == 0, "expected 0, got %d\n", retSize);
1044 CloseHandle(fh);
1046 rc = GetFileAttributesA(file);
1047 rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
1048 ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
1049 "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
1051 retSize = 0xdeadbeef;
1052 SetLastError(0xdeadbeef);
1053 rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
1054 sd, sdSize, &retSize);
1055 ok(rc, "GetFileSecurity error %d\n", GetLastError());
1056 ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
1058 priv_set_len = sizeof(priv_set);
1059 granted = 0xdeadbeef;
1060 status = 0xdeadbeef;
1061 SetLastError(0xdeadbeef);
1062 rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1063 ok(rc, "AccessCheck error %d\n", GetLastError());
1064 ok(status == 1, "expected 1, got %d\n", status);
1065 ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
1067 granted = 0xdeadbeef;
1068 status = 0xdeadbeef;
1069 SetLastError(0xdeadbeef);
1070 rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1071 ok(rc, "AccessCheck error %d\n", GetLastError());
1072 todo_wine {
1073 ok(status == 1, "expected 1, got %d\n", status);
1074 ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
1076 granted = 0xdeadbeef;
1077 status = 0xdeadbeef;
1078 SetLastError(0xdeadbeef);
1079 rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1080 ok(rc, "AccessCheck error %d\n", GetLastError());
1081 ok(status == 1, "expected 1, got %d\n", status);
1082 ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
1084 granted = 0xdeadbeef;
1085 status = 0xdeadbeef;
1086 SetLastError(0xdeadbeef);
1087 rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1088 ok(rc, "AccessCheck error %d\n", GetLastError());
1089 todo_wine {
1090 ok(status == 1, "expected 1, got %d\n", status);
1091 ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
1093 granted = 0xdeadbeef;
1094 status = 0xdeadbeef;
1095 SetLastError(0xdeadbeef);
1096 rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
1097 ok(rc, "AccessCheck error %d\n", GetLastError());
1098 todo_wine {
1099 ok(status == 1, "expected 1, got %d\n", status);
1100 ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
1102 granted = 0xdeadbeef;
1103 status = 0xdeadbeef;
1104 SetLastError(0xdeadbeef);
1105 rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
1106 ok(rc, "AccessCheck error %d\n", GetLastError());
1107 todo_wine {
1108 ok(status == 1, "expected 1, got %d\n", status);
1109 ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
1111 granted = 0xdeadbeef;
1112 status = 0xdeadbeef;
1113 SetLastError(0xdeadbeef);
1114 rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
1115 ok(rc, "AccessCheck error %d\n", GetLastError());
1116 todo_wine {
1117 ok(status == 1, "expected 1, got %d\n", status);
1118 ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
1120 SetLastError(0xdeadbeef);
1121 rc = DeleteFileA(file);
1122 ok(!rc, "DeleteFile should fail\n");
1123 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1124 SetLastError(0xdeadbeef);
1125 rc = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
1126 ok(rc, "SetFileAttributes error %d\n", GetLastError());
1127 SetLastError(0xdeadbeef);
1128 rc = DeleteFileA(file);
1129 ok(rc, "DeleteFile error %d\n", GetLastError());
1131 CloseHandle(token);
1132 HeapFree(GetProcessHeap(), 0, sd);
1135 static void test_AccessCheck(void)
1137 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
1138 PACL Acl = NULL;
1139 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
1140 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
1141 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1142 GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
1143 ACCESS_MASK Access;
1144 BOOL AccessStatus;
1145 HANDLE Token;
1146 HANDLE ProcessToken;
1147 BOOL ret;
1148 DWORD PrivSetLen;
1149 PRIVILEGE_SET *PrivSet;
1150 BOOL res;
1151 HMODULE NtDllModule;
1152 BOOLEAN Enabled;
1153 DWORD err;
1154 NTSTATUS ntret, ntAccessStatus;
1156 NtDllModule = GetModuleHandleA("ntdll.dll");
1157 if (!NtDllModule)
1159 skip("not running on NT, skipping test\n");
1160 return;
1162 pRtlAdjustPrivilege = (void *)GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
1163 if (!pRtlAdjustPrivilege)
1165 win_skip("missing RtlAdjustPrivilege, skipping test\n");
1166 return;
1169 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
1170 res = InitializeAcl(Acl, 256, ACL_REVISION);
1171 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1173 skip("ACLs not implemented - skipping tests\n");
1174 HeapFree(GetProcessHeap(), 0, Acl);
1175 return;
1177 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
1179 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
1180 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1182 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1183 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
1184 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1186 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1187 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
1188 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1190 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
1192 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1193 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
1195 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1196 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1198 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1199 PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
1200 PrivSet->PrivilegeCount = 16;
1202 res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
1203 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
1205 pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
1207 res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
1208 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1210 /* SD without owner/group */
1211 SetLastError(0xdeadbeef);
1212 Access = AccessStatus = 0x1abe11ed;
1213 ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
1214 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1215 err = GetLastError();
1216 ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
1217 "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
1218 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1219 "Access and/or AccessStatus were changed!\n");
1221 /* Set owner and group */
1222 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
1223 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
1224 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
1225 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
1227 /* Generic access mask */
1228 SetLastError(0xdeadbeef);
1229 Access = AccessStatus = 0x1abe11ed;
1230 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1231 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1232 err = GetLastError();
1233 ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
1234 "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
1235 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1236 "Access and/or AccessStatus were changed!\n");
1238 /* Generic access mask - no privilegeset buffer */
1239 SetLastError(0xdeadbeef);
1240 Access = AccessStatus = 0x1abe11ed;
1241 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1242 NULL, &PrivSetLen, &Access, &AccessStatus);
1243 err = GetLastError();
1244 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1245 "with ERROR_NOACCESS, instead of %d\n", err);
1246 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1247 "Access and/or AccessStatus were changed!\n");
1249 /* Generic access mask - no returnlength */
1250 SetLastError(0xdeadbeef);
1251 Access = AccessStatus = 0x1abe11ed;
1252 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1253 PrivSet, NULL, &Access, &AccessStatus);
1254 err = GetLastError();
1255 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1256 "with ERROR_NOACCESS, instead of %d\n", err);
1257 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1258 "Access and/or AccessStatus were changed!\n");
1260 /* Generic access mask - no privilegeset buffer, no returnlength */
1261 SetLastError(0xdeadbeef);
1262 Access = AccessStatus = 0x1abe11ed;
1263 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1264 NULL, NULL, &Access, &AccessStatus);
1265 err = GetLastError();
1266 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1267 "with ERROR_NOACCESS, instead of %d\n", err);
1268 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1269 "Access and/or AccessStatus were changed!\n");
1271 /* sd with no dacl present */
1272 Access = AccessStatus = 0x1abe11ed;
1273 ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
1274 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1275 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1276 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1277 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1278 ok(AccessStatus && (Access == KEY_READ),
1279 "AccessCheck failed to grant access with error %d\n",
1280 GetLastError());
1282 /* sd with no dacl present - no privilegeset buffer */
1283 SetLastError(0xdeadbeef);
1284 Access = AccessStatus = 0x1abe11ed;
1285 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1286 NULL, &PrivSetLen, &Access, &AccessStatus);
1287 err = GetLastError();
1288 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1289 "with ERROR_NOACCESS, instead of %d\n", err);
1290 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1291 "Access and/or AccessStatus were changed!\n");
1293 if(pNtAccessCheck)
1295 DWORD ntPrivSetLen = sizeof(PRIVILEGE_SET);
1297 /* Generic access mask - no privilegeset buffer */
1298 SetLastError(0xdeadbeef);
1299 Access = ntAccessStatus = 0x1abe11ed;
1300 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1301 NULL, &ntPrivSetLen, &Access, &ntAccessStatus);
1302 err = GetLastError();
1303 ok(ntret == STATUS_ACCESS_VIOLATION,
1304 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1305 ok(err == 0xdeadbeef,
1306 "NtAccessCheck shouldn't set last error, got %d\n", err);
1307 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1308 "Access and/or AccessStatus were changed!\n");
1309 ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
1311 /* Generic access mask - no returnlength */
1312 SetLastError(0xdeadbeef);
1313 Access = ntAccessStatus = 0x1abe11ed;
1314 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1315 PrivSet, NULL, &Access, &ntAccessStatus);
1316 err = GetLastError();
1317 ok(ntret == STATUS_ACCESS_VIOLATION,
1318 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1319 ok(err == 0xdeadbeef,
1320 "NtAccessCheck shouldn't set last error, got %d\n", err);
1321 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1322 "Access and/or AccessStatus were changed!\n");
1324 /* Generic access mask - no privilegeset buffer, no returnlength */
1325 SetLastError(0xdeadbeef);
1326 Access = ntAccessStatus = 0x1abe11ed;
1327 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1328 NULL, NULL, &Access, &ntAccessStatus);
1329 err = GetLastError();
1330 ok(ntret == STATUS_ACCESS_VIOLATION,
1331 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1332 ok(err == 0xdeadbeef,
1333 "NtAccessCheck shouldn't set last error, got %d\n", err);
1334 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1335 "Access and/or AccessStatus were changed!\n");
1337 /* Generic access mask - zero returnlength */
1338 SetLastError(0xdeadbeef);
1339 Access = ntAccessStatus = 0x1abe11ed;
1340 ntPrivSetLen = 0;
1341 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1342 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1343 err = GetLastError();
1344 ok(ntret == STATUS_GENERIC_NOT_MAPPED,
1345 "NtAccessCheck should have failed with STATUS_GENERIC_NOT_MAPPED, got %x\n", ntret);
1346 ok(err == 0xdeadbeef,
1347 "NtAccessCheck shouldn't set last error, got %d\n", err);
1348 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1349 "Access and/or AccessStatus were changed!\n");
1350 todo_wine ok(ntPrivSetLen == 0, "PrivSetLen returns %d\n", ntPrivSetLen);
1352 /* Generic access mask - insufficient returnlength */
1353 SetLastError(0xdeadbeef);
1354 Access = ntAccessStatus = 0x1abe11ed;
1355 ntPrivSetLen = sizeof(PRIVILEGE_SET)-1;
1356 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1357 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1358 err = GetLastError();
1359 ok(ntret == STATUS_GENERIC_NOT_MAPPED,
1360 "NtAccessCheck should have failed with STATUS_GENERIC_NOT_MAPPED, got %x\n", ntret);
1361 ok(err == 0xdeadbeef,
1362 "NtAccessCheck shouldn't set last error, got %d\n", err);
1363 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1364 "Access and/or AccessStatus were changed!\n");
1365 todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET)-1, "PrivSetLen returns %d\n", ntPrivSetLen);
1367 /* Key access mask - zero returnlength */
1368 SetLastError(0xdeadbeef);
1369 Access = ntAccessStatus = 0x1abe11ed;
1370 ntPrivSetLen = 0;
1371 ntret = pNtAccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1372 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1373 err = GetLastError();
1374 todo_wine ok(ntret == STATUS_BUFFER_TOO_SMALL,
1375 "NtAccessCheck should have failed with STATUS_BUFFER_TOO_SMALL, got %x\n", ntret);
1376 ok(err == 0xdeadbeef,
1377 "NtAccessCheck shouldn't set last error, got %d\n", err);
1378 todo_wine ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1379 "Access and/or AccessStatus were changed!\n");
1380 todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
1382 /* Key access mask - insufficient returnlength */
1383 SetLastError(0xdeadbeef);
1384 Access = ntAccessStatus = 0x1abe11ed;
1385 ntPrivSetLen = sizeof(PRIVILEGE_SET)-1;
1386 ntret = pNtAccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1387 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1388 err = GetLastError();
1389 todo_wine ok(ntret == STATUS_BUFFER_TOO_SMALL,
1390 "NtAccessCheck should have failed with STATUS_BUFFER_TOO_SMALL, got %x\n", ntret);
1391 ok(err == 0xdeadbeef,
1392 "NtAccessCheck shouldn't set last error, got %d\n", err);
1393 todo_wine ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1394 "Access and/or AccessStatus were changed!\n");
1395 todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
1397 else
1398 win_skip("NtAccessCheck unavailable. Skipping.\n");
1400 /* sd with NULL dacl */
1401 Access = AccessStatus = 0x1abe11ed;
1402 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
1403 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1404 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1405 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1406 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1407 ok(AccessStatus && (Access == KEY_READ),
1408 "AccessCheck failed to grant access with error %d\n",
1409 GetLastError());
1410 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1411 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1412 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1413 ok(AccessStatus && (Access == KEY_ALL_ACCESS),
1414 "AccessCheck failed to grant access with error %d\n",
1415 GetLastError());
1417 /* sd with blank dacl */
1418 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1419 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1420 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1421 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1422 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1423 err = GetLastError();
1424 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1425 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1426 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1428 res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
1429 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1431 res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
1432 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1434 /* sd with dacl */
1435 Access = AccessStatus = 0x1abe11ed;
1436 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1437 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1438 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1439 ok(AccessStatus && (Access == KEY_READ),
1440 "AccessCheck failed to grant access with error %d\n",
1441 GetLastError());
1443 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1444 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1445 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1446 ok(AccessStatus,
1447 "AccessCheck failed to grant any access with error %d\n",
1448 GetLastError());
1449 trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
1451 /* Null PrivSet with null PrivSetLen pointer */
1452 SetLastError(0xdeadbeef);
1453 Access = AccessStatus = 0x1abe11ed;
1454 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1455 NULL, NULL, &Access, &AccessStatus);
1456 err = GetLastError();
1457 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1458 "failed with ERROR_NOACCESS, instead of %d\n", err);
1459 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1460 "Access and/or AccessStatus were changed!\n");
1462 /* Null PrivSet with zero PrivSetLen */
1463 SetLastError(0xdeadbeef);
1464 Access = AccessStatus = 0x1abe11ed;
1465 PrivSetLen = 0;
1466 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1467 0, &PrivSetLen, &Access, &AccessStatus);
1468 err = GetLastError();
1469 todo_wine
1470 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1471 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1472 todo_wine
1473 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1474 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1475 "Access and/or AccessStatus were changed!\n");
1477 /* Null PrivSet with insufficient PrivSetLen */
1478 SetLastError(0xdeadbeef);
1479 Access = AccessStatus = 0x1abe11ed;
1480 PrivSetLen = 1;
1481 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1482 0, &PrivSetLen, &Access, &AccessStatus);
1483 err = GetLastError();
1484 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1485 "failed with ERROR_NOACCESS, instead of %d\n", err);
1486 ok(PrivSetLen == 1, "PrivSetLen returns %d\n", PrivSetLen);
1487 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1488 "Access and/or AccessStatus were changed!\n");
1490 /* Null PrivSet with insufficient PrivSetLen */
1491 SetLastError(0xdeadbeef);
1492 Access = AccessStatus = 0x1abe11ed;
1493 PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
1494 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1495 0, &PrivSetLen, &Access, &AccessStatus);
1496 err = GetLastError();
1497 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1498 "failed with ERROR_NOACCESS, instead of %d\n", err);
1499 ok(PrivSetLen == sizeof(PRIVILEGE_SET) - 1, "PrivSetLen returns %d\n", PrivSetLen);
1500 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1501 "Access and/or AccessStatus were changed!\n");
1503 /* Null PrivSet with minimal sufficient PrivSetLen */
1504 SetLastError(0xdeadbeef);
1505 Access = AccessStatus = 0x1abe11ed;
1506 PrivSetLen = sizeof(PRIVILEGE_SET);
1507 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1508 0, &PrivSetLen, &Access, &AccessStatus);
1509 err = GetLastError();
1510 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1511 "failed with ERROR_NOACCESS, instead of %d\n", err);
1512 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1513 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1514 "Access and/or AccessStatus were changed!\n");
1516 /* Valid PrivSet with zero PrivSetLen */
1517 SetLastError(0xdeadbeef);
1518 Access = AccessStatus = 0x1abe11ed;
1519 PrivSetLen = 0;
1520 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1521 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1522 err = GetLastError();
1523 todo_wine
1524 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1525 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1526 todo_wine
1527 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1528 todo_wine
1529 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1530 "Access and/or AccessStatus were changed!\n");
1532 /* Valid PrivSet with insufficient PrivSetLen */
1533 SetLastError(0xdeadbeef);
1534 Access = AccessStatus = 0x1abe11ed;
1535 PrivSetLen = 1;
1536 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1537 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1538 err = GetLastError();
1539 todo_wine
1540 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1541 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1542 todo_wine
1543 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1544 todo_wine
1545 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1546 "Access and/or AccessStatus were changed!\n");
1548 /* Valid PrivSet with insufficient PrivSetLen */
1549 SetLastError(0xdeadbeef);
1550 Access = AccessStatus = 0x1abe11ed;
1551 PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
1552 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1553 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1554 err = GetLastError();
1555 todo_wine
1556 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1557 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1558 todo_wine
1559 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1560 todo_wine
1561 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1562 "Access and/or AccessStatus were changed!\n");
1564 /* Valid PrivSet with minimal sufficient PrivSetLen */
1565 SetLastError(0xdeadbeef);
1566 Access = AccessStatus = 0x1abe11ed;
1567 PrivSetLen = sizeof(PRIVILEGE_SET);
1568 memset(PrivSet, 0xcc, PrivSetLen);
1569 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1570 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1571 err = GetLastError();
1572 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1573 todo_wine
1574 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1575 ok(AccessStatus && (Access == KEY_READ),
1576 "AccessCheck failed to grant access with error %d\n", GetLastError());
1577 ok(PrivSet->PrivilegeCount == 0, "PrivilegeCount returns %d, expects 0\n",
1578 PrivSet->PrivilegeCount);
1580 /* Valid PrivSet with sufficient PrivSetLen */
1581 SetLastError(0xdeadbeef);
1582 Access = AccessStatus = 0x1abe11ed;
1583 PrivSetLen = sizeof(PRIVILEGE_SET) + 1;
1584 memset(PrivSet, 0xcc, PrivSetLen);
1585 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1586 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1587 err = GetLastError();
1588 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1589 todo_wine
1590 ok(PrivSetLen == sizeof(PRIVILEGE_SET) + 1, "PrivSetLen returns %d\n", PrivSetLen);
1591 ok(AccessStatus && (Access == KEY_READ),
1592 "AccessCheck failed to grant access with error %d\n", GetLastError());
1593 ok(PrivSet->PrivilegeCount == 0, "PrivilegeCount returns %d, expects 0\n",
1594 PrivSet->PrivilegeCount);
1596 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1598 /* Null PrivSet with valid PrivSetLen */
1599 SetLastError(0xdeadbeef);
1600 Access = AccessStatus = 0x1abe11ed;
1601 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1602 0, &PrivSetLen, &Access, &AccessStatus);
1603 err = GetLastError();
1604 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1605 "failed with ERROR_NOACCESS, instead of %d\n", err);
1606 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1607 "Access and/or AccessStatus were changed!\n");
1609 /* Access denied by SD */
1610 SetLastError(0xdeadbeef);
1611 Access = AccessStatus = 0x1abe11ed;
1612 ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
1613 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1614 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1615 err = GetLastError();
1616 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1617 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1618 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1620 SetLastError(0xdeadbeef);
1621 PrivSet->PrivilegeCount = 16;
1622 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1623 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1624 ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
1625 "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
1626 GetLastError());
1628 ret = ImpersonateLoggedOnUser(Token);
1629 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1630 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
1631 if (!ret)
1633 /* Valid PrivSet with zero PrivSetLen */
1634 SetLastError(0xdeadbeef);
1635 Access = AccessStatus = 0x1abe11ed;
1636 PrivSetLen = 0;
1637 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1638 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1639 err = GetLastError();
1640 todo_wine
1641 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1642 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1643 todo_wine
1644 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1645 todo_wine
1646 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1647 "Access and/or AccessStatus were changed!\n");
1649 /* Valid PrivSet with insufficient PrivSetLen */
1650 SetLastError(0xdeadbeef);
1651 Access = AccessStatus = 0x1abe11ed;
1652 PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
1653 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1654 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1655 err = GetLastError();
1656 todo_wine
1657 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1658 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1659 todo_wine
1660 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1661 todo_wine
1662 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1663 "Access and/or AccessStatus were changed!\n");
1665 /* Valid PrivSet with minimal sufficient PrivSetLen */
1666 SetLastError(0xdeadbeef);
1667 Access = AccessStatus = 0x1abe11ed;
1668 PrivSetLen = sizeof(PRIVILEGE_SET);
1669 memset(PrivSet, 0xcc, PrivSetLen);
1670 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1671 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1672 ok(ret && AccessStatus && GetLastError() == 0xdeadbeef,
1673 "AccessCheck should have succeeded, error %d\n",
1674 GetLastError());
1675 ok(Access == ACCESS_SYSTEM_SECURITY,
1676 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1677 Access);
1678 ok(PrivSet->PrivilegeCount == 1, "PrivilegeCount returns %d, expects 1\n",
1679 PrivSet->PrivilegeCount);
1681 /* Valid PrivSet with large PrivSetLen */
1682 SetLastError(0xdeadbeef);
1683 Access = AccessStatus = 0x1abe11ed;
1684 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1685 memset(PrivSet, 0xcc, PrivSetLen);
1686 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1687 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1688 ok(ret && AccessStatus && GetLastError() == 0xdeadbeef,
1689 "AccessCheck should have succeeded, error %d\n",
1690 GetLastError());
1691 ok(Access == ACCESS_SYSTEM_SECURITY,
1692 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1693 Access);
1694 ok(PrivSet->PrivilegeCount == 1, "PrivilegeCount returns %d, expects 1\n",
1695 PrivSet->PrivilegeCount);
1697 else
1698 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1699 ret);
1700 ret = RevertToSelf();
1701 ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1703 /* test INHERIT_ONLY_ACE */
1704 ret = InitializeAcl(Acl, 256, ACL_REVISION);
1705 ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
1707 /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
1708 * the next ones.
1710 if (pAddAccessAllowedAceEx)
1712 ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
1713 ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1715 else
1716 win_skip("AddAccessAllowedAceEx is not available\n");
1718 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1719 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1720 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1721 err = GetLastError();
1722 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1723 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1724 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1726 CloseHandle(Token);
1728 res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
1729 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1731 SetLastError(0xdeadbeef);
1732 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1733 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1734 err = GetLastError();
1735 ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
1736 "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
1738 CloseHandle(Token);
1740 SetLastError(0xdeadbeef);
1741 ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
1742 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1743 err = GetLastError();
1744 ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
1745 "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
1747 CloseHandle(ProcessToken);
1749 if (EveryoneSid)
1750 FreeSid(EveryoneSid);
1751 if (AdminSid)
1752 FreeSid(AdminSid);
1753 if (UsersSid)
1754 FreeSid(UsersSid);
1755 HeapFree(GetProcessHeap(), 0, Acl);
1756 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1757 HeapFree(GetProcessHeap(), 0, PrivSet);
1760 /* test GetTokenInformation for the various attributes */
1761 static void test_token_attr(void)
1763 HANDLE Token, ImpersonationToken;
1764 DWORD Size, Size2;
1765 TOKEN_PRIVILEGES *Privileges;
1766 TOKEN_GROUPS *Groups;
1767 TOKEN_USER *User;
1768 TOKEN_DEFAULT_DACL *Dacl;
1769 BOOL ret;
1770 DWORD i, GLE;
1771 LPSTR SidString;
1772 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1773 ACL *acl;
1775 /* cygwin-like use case */
1776 SetLastError(0xdeadbeef);
1777 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1778 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1780 win_skip("OpenProcessToken is not implemented\n");
1781 return;
1783 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1784 if (ret)
1786 DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1787 Size = sizeof(buf);
1788 ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1789 ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1790 Size = sizeof(ImpersonationLevel);
1791 ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1792 GLE = GetLastError();
1793 ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1794 CloseHandle(Token);
1797 SetLastError(0xdeadbeef);
1798 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1799 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1801 /* groups */
1802 /* insufficient buffer length */
1803 SetLastError(0xdeadbeef);
1804 Size2 = 0;
1805 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size2);
1806 ok(Size2 > 1, "got %d\n", Size2);
1807 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1808 "%d with error %d\n", ret, GetLastError());
1809 Size2 -= 1;
1810 Groups = HeapAlloc(GetProcessHeap(), 0, Size2);
1811 memset(Groups, 0xcc, Size2);
1812 Size = 0;
1813 ret = GetTokenInformation(Token, TokenGroups, Groups, Size2, &Size);
1814 ok(Size > 1, "got %d\n", Size);
1815 ok((!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER) || broken(ret) /* wow64 */,
1816 "%d with error %d\n", ret, GetLastError());
1817 if(!ret)
1818 ok(*((BYTE*)Groups) == 0xcc, "buffer altered\n");
1820 HeapFree(GetProcessHeap(), 0, Groups);
1822 SetLastError(0xdeadbeef);
1823 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1824 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1825 "GetTokenInformation(TokenGroups) %s with error %d\n",
1826 ret ? "succeeded" : "failed", GetLastError());
1827 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1828 SetLastError(0xdeadbeef);
1829 ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1830 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1831 ok(GetLastError() == 0xdeadbeef,
1832 "GetTokenInformation shouldn't have set last error to %d\n",
1833 GetLastError());
1834 trace("TokenGroups:\n");
1835 for (i = 0; i < Groups->GroupCount; i++)
1837 DWORD NameLength = 255;
1838 CHAR Name[255];
1839 DWORD DomainLength = 255;
1840 CHAR Domain[255];
1841 SID_NAME_USE SidNameUse;
1842 Name[0] = '\0';
1843 Domain[0] = '\0';
1844 ret = LookupAccountSidA(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1845 if (ret)
1847 ConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1848 trace("%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
1849 LocalFree(SidString);
1851 else trace("attr: 0x%08x LookupAccountSid failed with error %d\n", Groups->Groups[i].Attributes, GetLastError());
1853 HeapFree(GetProcessHeap(), 0, Groups);
1855 /* user */
1856 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1857 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1858 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1859 User = HeapAlloc(GetProcessHeap(), 0, Size);
1860 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1861 ok(ret,
1862 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1864 ConvertSidToStringSidA(User->User.Sid, &SidString);
1865 trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1866 LocalFree(SidString);
1867 HeapFree(GetProcessHeap(), 0, User);
1869 /* logon */
1870 ret = GetTokenInformation(Token, TokenLogonSid, NULL, 0, &Size);
1871 if (!ret && (GetLastError() == ERROR_INVALID_PARAMETER))
1872 todo_wine win_skip("TokenLogonSid not supported. Skipping tests\n");
1873 else
1875 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1876 "GetTokenInformation(TokenLogonSid) failed with error %d\n", GetLastError());
1877 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1878 ret = GetTokenInformation(Token, TokenLogonSid, Groups, Size, &Size);
1879 ok(ret,
1880 "GetTokenInformation(TokenLogonSid) failed with error %d\n", GetLastError());
1881 if (ret)
1883 ok(Groups->GroupCount == 1, "got %d\n", Groups->GroupCount);
1884 if(Groups->GroupCount == 1)
1886 ConvertSidToStringSidA(Groups->Groups[0].Sid, &SidString);
1887 trace("TokenLogon: %s\n", SidString);
1888 LocalFree(SidString);
1890 /* S-1-5-5-0-XXXXXX */
1891 ret = IsWellKnownSid(Groups->Groups[0].Sid, WinLogonIdsSid);
1892 ok(ret, "Unknown SID\n");
1896 HeapFree(GetProcessHeap(), 0, Groups);
1899 /* privileges */
1900 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1901 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1902 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1903 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1904 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1905 ok(ret,
1906 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1907 trace("TokenPrivileges:\n");
1908 for (i = 0; i < Privileges->PrivilegeCount; i++)
1910 CHAR Name[256];
1911 DWORD NameLen = ARRAY_SIZE(Name);
1912 LookupPrivilegeNameA(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1913 trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1915 HeapFree(GetProcessHeap(), 0, Privileges);
1917 ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
1918 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1920 Size = sizeof(ImpersonationLevel);
1921 ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1922 ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1923 ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
1925 CloseHandle(ImpersonationToken);
1927 /* default dacl */
1928 ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
1929 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1930 "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1932 Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
1933 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
1934 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1936 SetLastError(0xdeadbeef);
1937 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
1938 GLE = GetLastError();
1939 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1940 ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);
1942 SetLastError(0xdeadbeef);
1943 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
1944 GLE = GetLastError();
1945 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1946 ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);
1948 acl = Dacl->DefaultDacl;
1949 Dacl->DefaultDacl = NULL;
1951 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1952 ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1954 Size2 = 0;
1955 Dacl->DefaultDacl = (ACL *)0xdeadbeef;
1956 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1957 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1958 ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
1959 ok(Size2 == sizeof(TOKEN_DEFAULT_DACL) || broken(Size2 == 2*sizeof(TOKEN_DEFAULT_DACL)), /* WoW64 */
1960 "got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
1962 Dacl->DefaultDacl = acl;
1963 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1964 ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1966 if (Size2 == sizeof(TOKEN_DEFAULT_DACL)) {
1967 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1968 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1969 } else
1970 win_skip("TOKEN_DEFAULT_DACL size too small on WoW64\n");
1972 HeapFree(GetProcessHeap(), 0, Dacl);
1973 CloseHandle(Token);
1976 static void test_GetTokenInformation(void)
1978 DWORD is_app_container, size;
1979 HANDLE token;
1980 BOOL ret;
1982 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
1983 ok(ret, "OpenProcessToken failed: %u\n", GetLastError());
1985 size = 0;
1986 is_app_container = 0xdeadbeef;
1987 ret = GetTokenInformation(token, TokenIsAppContainer, &is_app_container,
1988 sizeof(is_app_container), &size);
1989 ok(ret || broken(GetLastError() == ERROR_INVALID_PARAMETER ||
1990 GetLastError() == ERROR_INVALID_FUNCTION), /* pre-win8 */
1991 "GetTokenInformation failed: %u\n", GetLastError());
1992 if(ret) {
1993 ok(size == sizeof(is_app_container), "size = %u\n", size);
1994 ok(!is_app_container, "is_app_container = %x\n", is_app_container);
1997 CloseHandle(token);
2000 typedef union _MAX_SID
2002 SID sid;
2003 char max[SECURITY_MAX_SID_SIZE];
2004 } MAX_SID;
2006 static void test_sid_str(PSID * sid)
2008 char *str_sid;
2009 BOOL ret = ConvertSidToStringSidA(sid, &str_sid);
2010 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
2011 if (ret)
2013 char account[MAX_PATH], domain[MAX_PATH];
2014 SID_NAME_USE use;
2015 DWORD acc_size = MAX_PATH;
2016 DWORD dom_size = MAX_PATH;
2017 ret = LookupAccountSidA (NULL, sid, account, &acc_size, domain, &dom_size, &use);
2018 ok(ret || GetLastError() == ERROR_NONE_MAPPED,
2019 "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
2020 if (ret)
2021 trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
2022 else if (GetLastError() == ERROR_NONE_MAPPED)
2023 trace(" %s couldn't be mapped\n", str_sid);
2024 LocalFree(str_sid);
2028 static const struct well_known_sid_value
2030 BOOL without_domain;
2031 const char *sid_string;
2032 } well_known_sid_values[] = {
2033 /* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
2034 /* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
2035 /* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
2036 /* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
2037 /* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
2038 /* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
2039 /* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
2040 /* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
2041 /* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
2042 /* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
2043 /* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
2044 /* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
2045 /* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
2046 /* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
2047 /* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
2048 /* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
2049 /* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
2050 /* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
2051 /* Added in Windows Server 2003 */
2052 /* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
2053 /* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
2054 /* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
2055 /* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
2056 /* Added in Windows Vista: */
2057 /* 62 */ {TRUE, "S-1-5-32-568"},
2058 /* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
2059 /* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
2060 /* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
2061 /* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
2062 /* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"},
2063 /* 77 */ {FALSE, "S-1-5-21-12-23-34-45-56-498"}, {TRUE, "S-1-5-32-574"}, {TRUE, "S-1-16-8448"},
2064 /* 80 */ {FALSE, NULL}, {TRUE, "S-1-2-1"}, {TRUE, "S-1-5-65-1"}, {FALSE, NULL},
2065 /* 84 */ {TRUE, "S-1-15-2-1"},
2068 static void test_CreateWellKnownSid(void)
2070 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
2071 PSID domainsid, sid;
2072 DWORD size, error;
2073 BOOL ret;
2074 unsigned int i;
2076 size = 0;
2077 SetLastError(0xdeadbeef);
2078 ret = CreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
2079 error = GetLastError();
2080 ok(!ret, "CreateWellKnownSid succeeded\n");
2081 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
2082 ok(size, "expected size > 0\n");
2084 SetLastError(0xdeadbeef);
2085 ret = CreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
2086 error = GetLastError();
2087 ok(!ret, "CreateWellKnownSid succeeded\n");
2088 ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);
2090 sid = HeapAlloc(GetProcessHeap(), 0, size);
2091 ret = CreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
2092 ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
2093 HeapFree(GetProcessHeap(), 0, sid);
2095 /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
2096 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
2098 for (i = 0; i < ARRAY_SIZE(well_known_sid_values); i++)
2100 const struct well_known_sid_value *value = &well_known_sid_values[i];
2101 char sid_buffer[SECURITY_MAX_SID_SIZE];
2102 LPSTR str;
2103 DWORD cb;
2105 if (value->sid_string == NULL)
2106 continue;
2108 /* some SIDs aren't implemented by all Windows versions - detect it */
2109 cb = sizeof(sid_buffer);
2110 if (!CreateWellKnownSid(i, NULL, sid_buffer, &cb))
2112 skip("Well known SID %u not implemented\n", i);
2113 continue;
2116 cb = sizeof(sid_buffer);
2117 ok(CreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %u\n", i);
2118 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
2119 ok(IsValidSid(sid_buffer), "The sid is not valid\n");
2120 ok(ConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
2121 ok(strcmp(str, value->sid_string) == 0, "%d: SID mismatch - expected %s, got %s\n", i,
2122 value->sid_string, str);
2123 LocalFree(str);
2125 if (value->without_domain)
2127 char buf2[SECURITY_MAX_SID_SIZE];
2128 cb = sizeof(buf2);
2129 ok(CreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %u with optional domain\n", i);
2130 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
2131 ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%u)\n", i);
2135 FreeSid(domainsid);
2138 static void test_LookupAccountSid(void)
2140 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2141 CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
2142 DWORD acc_sizeA, dom_sizeA, user_sizeA;
2143 DWORD real_acc_sizeA, real_dom_sizeA;
2144 WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
2145 LSA_OBJECT_ATTRIBUTES object_attributes;
2146 DWORD acc_sizeW, dom_sizeW;
2147 DWORD real_acc_sizeW, real_dom_sizeW;
2148 PSID pUsersSid = NULL;
2149 SID_NAME_USE use;
2150 BOOL ret;
2151 DWORD error, size, cbti = 0;
2152 MAX_SID max_sid;
2153 CHAR *str_sidA;
2154 int i;
2155 HANDLE hToken;
2156 PTOKEN_USER ptiUser = NULL;
2157 LSA_HANDLE handle;
2158 NTSTATUS status;
2160 /* native windows crashes if account size, domain size, or name use is NULL */
2162 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2163 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
2164 ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
2165 "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2167 /* not running on NT so give up */
2168 if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2169 return;
2171 real_acc_sizeA = MAX_PATH;
2172 real_dom_sizeA = MAX_PATH;
2173 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
2174 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2176 /* try NULL account */
2177 acc_sizeA = MAX_PATH;
2178 dom_sizeA = MAX_PATH;
2179 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
2180 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2182 /* try NULL domain */
2183 acc_sizeA = MAX_PATH;
2184 dom_sizeA = MAX_PATH;
2185 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
2186 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2188 /* try a small account buffer */
2189 acc_sizeA = 1;
2190 dom_sizeA = MAX_PATH;
2191 accountA[0] = 0;
2192 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2193 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
2194 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2195 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2197 /* try a 0 sized account buffer */
2198 acc_sizeA = 0;
2199 dom_sizeA = MAX_PATH;
2200 accountA[0] = 0;
2201 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2202 /* this can fail or succeed depending on OS version but the size will always be returned */
2203 ok(acc_sizeA == real_acc_sizeA + 1,
2204 "LookupAccountSidA() Expected acc_size = %u, got %u\n",
2205 real_acc_sizeA + 1, acc_sizeA);
2207 /* try a 0 sized account buffer */
2208 acc_sizeA = 0;
2209 dom_sizeA = MAX_PATH;
2210 LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
2211 /* this can fail or succeed depending on OS version but the size will always be returned */
2212 ok(acc_sizeA == real_acc_sizeA + 1,
2213 "LookupAccountSid() Expected acc_size = %u, got %u\n",
2214 real_acc_sizeA + 1, acc_sizeA);
2216 /* try a small domain buffer */
2217 dom_sizeA = 1;
2218 acc_sizeA = MAX_PATH;
2219 accountA[0] = 0;
2220 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2221 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
2222 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2223 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2225 /* try a 0 sized domain buffer */
2226 dom_sizeA = 0;
2227 acc_sizeA = MAX_PATH;
2228 accountA[0] = 0;
2229 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2230 /* this can fail or succeed depending on OS version but the size will always be returned */
2231 ok(dom_sizeA == real_dom_sizeA + 1,
2232 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
2233 real_dom_sizeA + 1, dom_sizeA);
2235 /* try a 0 sized domain buffer */
2236 dom_sizeA = 0;
2237 acc_sizeA = MAX_PATH;
2238 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
2239 /* this can fail or succeed depending on OS version but the size will always be returned */
2240 ok(dom_sizeA == real_dom_sizeA + 1,
2241 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
2242 real_dom_sizeA + 1, dom_sizeA);
2244 real_acc_sizeW = MAX_PATH;
2245 real_dom_sizeW = MAX_PATH;
2246 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
2247 ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
2249 /* try an invalid system name */
2250 real_acc_sizeA = MAX_PATH;
2251 real_dom_sizeA = MAX_PATH;
2252 ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
2253 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
2254 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2255 "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
2257 /* native windows crashes if domainW or accountW is NULL */
2259 /* try a small account buffer */
2260 acc_sizeW = 1;
2261 dom_sizeW = MAX_PATH;
2262 accountW[0] = 0;
2263 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2264 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
2265 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2266 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2268 /* try a 0 sized account buffer */
2269 acc_sizeW = 0;
2270 dom_sizeW = MAX_PATH;
2271 accountW[0] = 0;
2272 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2273 /* this can fail or succeed depending on OS version but the size will always be returned */
2274 ok(acc_sizeW == real_acc_sizeW + 1,
2275 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
2276 real_acc_sizeW + 1, acc_sizeW);
2278 /* try a 0 sized account buffer */
2279 acc_sizeW = 0;
2280 dom_sizeW = MAX_PATH;
2281 LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
2282 /* this can fail or succeed depending on OS version but the size will always be returned */
2283 ok(acc_sizeW == real_acc_sizeW + 1,
2284 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
2285 real_acc_sizeW + 1, acc_sizeW);
2287 /* try a small domain buffer */
2288 dom_sizeW = 1;
2289 acc_sizeW = MAX_PATH;
2290 accountW[0] = 0;
2291 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2292 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
2293 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2294 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2296 /* try a 0 sized domain buffer */
2297 dom_sizeW = 0;
2298 acc_sizeW = MAX_PATH;
2299 accountW[0] = 0;
2300 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2301 /* this can fail or succeed depending on OS version but the size will always be returned */
2302 ok(dom_sizeW == real_dom_sizeW + 1,
2303 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
2304 real_dom_sizeW + 1, dom_sizeW);
2306 /* try a 0 sized domain buffer */
2307 dom_sizeW = 0;
2308 acc_sizeW = MAX_PATH;
2309 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
2310 /* this can fail or succeed depending on OS version but the size will always be returned */
2311 ok(dom_sizeW == real_dom_sizeW + 1,
2312 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
2313 real_dom_sizeW + 1, dom_sizeW);
2315 acc_sizeW = dom_sizeW = use = 0;
2316 SetLastError(0xdeadbeef);
2317 ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, NULL, &dom_sizeW, &use);
2318 error = GetLastError();
2319 ok(!ret, "LookupAccountSidW failed %u\n", GetLastError());
2320 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
2321 ok(acc_sizeW, "expected non-zero account size\n");
2322 ok(dom_sizeW, "expected non-zero domain size\n");
2323 ok(!use, "expected zero use %u\n", use);
2325 FreeSid(pUsersSid);
2327 /* Test LookupAccountSid with Sid retrieved from token information.
2328 This assumes this process is running under the account of the current user.*/
2329 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
2330 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
2331 ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
2332 ok(!ret, "GetTokenInformation failed with error %d\n", GetLastError());
2333 ptiUser = HeapAlloc(GetProcessHeap(), 0, cbti);
2334 if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
2336 acc_sizeA = dom_sizeA = MAX_PATH;
2337 ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2338 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2339 user_sizeA = MAX_PATH;
2340 ret = GetUserNameA(usernameA , &user_sizeA);
2341 ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
2342 ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
2344 HeapFree(GetProcessHeap(), 0, ptiUser);
2346 trace("Well Known SIDs:\n");
2347 for (i = 0; i <= 60; i++)
2349 size = SECURITY_MAX_SID_SIZE;
2350 if (CreateWellKnownSid(i, NULL, &max_sid.sid, &size))
2352 if (ConvertSidToStringSidA(&max_sid.sid, &str_sidA))
2354 acc_sizeA = MAX_PATH;
2355 dom_sizeA = MAX_PATH;
2356 if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
2357 trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
2358 LocalFree(str_sidA);
2361 else
2363 if (GetLastError() != ERROR_INVALID_PARAMETER)
2364 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
2365 else
2366 trace(" %d: not supported\n", i);
2370 ZeroMemory(&object_attributes, sizeof(object_attributes));
2371 object_attributes.Length = sizeof(object_attributes);
2373 status = LsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
2374 ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
2375 "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
2377 /* try a more restricted access mask if necessary */
2378 if (status == STATUS_ACCESS_DENIED) {
2379 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
2380 status = LsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
2381 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
2384 if (status == STATUS_SUCCESS)
2386 PPOLICY_ACCOUNT_DOMAIN_INFO info;
2387 status = LsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
2388 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
2389 if (status == STATUS_SUCCESS)
2391 ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
2392 if (info->DomainSid)
2394 int count = *GetSidSubAuthorityCount(info->DomainSid);
2395 CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
2396 test_sid_str((PSID)&max_sid.sid);
2397 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
2398 max_sid.sid.SubAuthorityCount = count + 1;
2399 test_sid_str((PSID)&max_sid.sid);
2400 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
2401 test_sid_str((PSID)&max_sid.sid);
2402 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
2403 test_sid_str((PSID)&max_sid.sid);
2404 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
2405 test_sid_str((PSID)&max_sid.sid);
2406 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
2407 test_sid_str((PSID)&max_sid.sid);
2408 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
2409 test_sid_str((PSID)&max_sid.sid);
2410 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
2411 test_sid_str((PSID)&max_sid.sid);
2412 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
2413 test_sid_str((PSID)&max_sid.sid);
2414 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
2415 test_sid_str((PSID)&max_sid.sid);
2416 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
2417 test_sid_str((PSID)&max_sid.sid);
2418 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
2419 test_sid_str((PSID)&max_sid.sid);
2420 max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
2421 test_sid_str((PSID)&max_sid.sid);
2422 max_sid.sid.SubAuthority[count] = 1000; /* first user account */
2423 test_sid_str((PSID)&max_sid.sid);
2426 LsaFreeMemory(info);
2429 status = LsaClose(handle);
2430 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
2434 static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
2436 static CHAR account[UNLEN + 1];
2437 static CHAR domain[UNLEN + 1];
2438 DWORD size, dom_size;
2439 SID_NAME_USE use;
2441 *user = account;
2442 *dom = domain;
2444 size = dom_size = UNLEN + 1;
2445 account[0] = '\0';
2446 domain[0] = '\0';
2447 SetLastError(0xdeadbeef);
2448 return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
2451 static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
2453 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
2454 PSID domainsid = NULL;
2455 char wk_sid[SECURITY_MAX_SID_SIZE];
2456 DWORD cb;
2458 DWORD sid_size, domain_size;
2459 SID_NAME_USE sid_use;
2460 LPSTR domain, account, sid_domain, wk_domain, wk_account;
2461 PSID psid;
2462 BOOL ret ,ret2;
2464 sid_size = 0;
2465 domain_size = 0;
2466 ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2467 ok(!ret, " %s Should have failed to lookup account name\n", name);
2468 psid = HeapAlloc(GetProcessHeap(),0,sid_size);
2469 domain = HeapAlloc(GetProcessHeap(),0,domain_size);
2470 ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);
2472 if (!result)
2474 ok(!ret, " %s Should have failed to lookup account name\n",name);
2475 goto cleanup;
2478 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
2479 cb = sizeof(wk_sid);
2480 if (!CreateWellKnownSid(result, domainsid, wk_sid, &cb))
2482 win_skip("SID %i is not available on the system\n",result);
2483 goto cleanup;
2486 ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
2487 if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
2489 win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
2490 goto cleanup;
2493 get_sid_info(psid, &account, &sid_domain);
2495 ok(ret, "Failed to lookup account name %s\n",name);
2496 ok(sid_size != 0, "sid_size was zero\n");
2498 ok(EqualSid(psid,wk_sid),"%s Sid %s fails to match well known sid %s!\n",
2499 name, debugstr_sid(psid), debugstr_sid(wk_sid));
2501 ok(!lstrcmpA(account, wk_account), "Expected %s , got %s\n", account, wk_account);
2502 ok(!lstrcmpA(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
2503 ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
2505 cleanup:
2506 FreeSid(domainsid);
2507 HeapFree(GetProcessHeap(),0,psid);
2508 HeapFree(GetProcessHeap(),0,domain);
2511 static void test_LookupAccountName(void)
2513 DWORD sid_size, domain_size, user_size;
2514 DWORD sid_save, domain_save;
2515 CHAR user_name[UNLEN + 1];
2516 CHAR computer_name[UNLEN + 1];
2517 SID_NAME_USE sid_use;
2518 LPSTR domain, account, sid_dom;
2519 PSID psid;
2520 BOOL ret;
2522 /* native crashes if (assuming all other parameters correct):
2523 * - peUse is NULL
2524 * - Sid is NULL and cbSid is > 0
2525 * - cbSid or cchReferencedDomainName are NULL
2526 * - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
2529 user_size = UNLEN + 1;
2530 SetLastError(0xdeadbeef);
2531 ret = GetUserNameA(user_name, &user_size);
2532 ok(ret, "Failed to get user name : %d\n", GetLastError());
2534 /* get sizes */
2535 sid_size = 0;
2536 domain_size = 0;
2537 sid_use = 0xcafebabe;
2538 SetLastError(0xdeadbeef);
2539 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2540 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2542 win_skip("LookupAccountNameA is not implemented\n");
2543 return;
2545 ok(!ret, "Expected 0, got %d\n", ret);
2546 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2547 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2548 ok(sid_size != 0, "Expected non-zero sid size\n");
2549 ok(domain_size != 0, "Expected non-zero domain size\n");
2550 ok(sid_use == (SID_NAME_USE)0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2552 sid_save = sid_size;
2553 domain_save = domain_size;
2555 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2556 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2558 /* try valid account name */
2559 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
2560 get_sid_info(psid, &account, &sid_dom);
2561 ok(ret, "Failed to lookup account name\n");
2562 ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
2563 ok(!lstrcmpA(account, user_name), "Expected %s, got %s\n", user_name, account);
2564 ok(!lstrcmpiA(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2565 ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
2566 ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlenA(domain), domain_size);
2567 ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
2568 domain_size = domain_save;
2569 sid_size = sid_save;
2571 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2573 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2575 else
2577 ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
2578 get_sid_info(psid, &account, &sid_dom);
2579 ok(ret, "Failed to lookup account name\n");
2580 ok(sid_size != 0, "sid_size was zero\n");
2581 ok(!lstrcmpA(account, "Everyone"), "Expected Everyone, got %s\n", account);
2582 ok(!lstrcmpiA(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2583 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2584 ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlenA(domain), domain_size);
2585 ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
2586 domain_size = domain_save;
2589 /* NULL Sid with zero sid size */
2590 SetLastError(0xdeadbeef);
2591 sid_size = 0;
2592 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
2593 ok(!ret, "Expected 0, got %d\n", ret);
2594 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2595 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2596 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2597 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2599 /* try cchReferencedDomainName - 1 */
2600 SetLastError(0xdeadbeef);
2601 domain_size--;
2602 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
2603 ok(!ret, "Expected 0, got %d\n", ret);
2604 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2605 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2606 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2607 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2609 /* NULL ReferencedDomainName with zero domain name size */
2610 SetLastError(0xdeadbeef);
2611 domain_size = 0;
2612 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
2613 ok(!ret, "Expected 0, got %d\n", ret);
2614 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2615 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2616 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2617 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2619 HeapFree(GetProcessHeap(), 0, psid);
2620 HeapFree(GetProcessHeap(), 0, domain);
2622 /* get sizes for NULL account name */
2623 sid_size = 0;
2624 domain_size = 0;
2625 sid_use = 0xcafebabe;
2626 SetLastError(0xdeadbeef);
2627 ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2628 if (!ret && GetLastError() == ERROR_NONE_MAPPED)
2629 win_skip("NULL account name doesn't work on NT4\n");
2630 else
2632 ok(!ret, "Expected 0, got %d\n", ret);
2633 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2634 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2635 ok(sid_size != 0, "Expected non-zero sid size\n");
2636 ok(domain_size != 0, "Expected non-zero domain size\n");
2637 ok(sid_use == (SID_NAME_USE)0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2639 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2640 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2642 /* try NULL account name */
2643 ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
2644 get_sid_info(psid, &account, &sid_dom);
2645 ok(ret, "Failed to lookup account name\n");
2646 /* Using a fixed string will not work on different locales */
2647 ok(!lstrcmpiA(account, domain),
2648 "Got %s for account and %s for domain, these should be the same\n", account, domain);
2649 ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
2651 HeapFree(GetProcessHeap(), 0, psid);
2652 HeapFree(GetProcessHeap(), 0, domain);
2655 /* try an invalid account name */
2656 SetLastError(0xdeadbeef);
2657 sid_size = 0;
2658 domain_size = 0;
2659 ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
2660 ok(!ret, "Expected 0, got %d\n", ret);
2661 ok(GetLastError() == ERROR_NONE_MAPPED ||
2662 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
2663 "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
2664 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2665 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2667 /* try an invalid system name */
2668 SetLastError(0xdeadbeef);
2669 sid_size = 0;
2670 domain_size = 0;
2671 ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2672 ok(!ret, "Expected 0, got %d\n", ret);
2673 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2674 "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
2675 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2676 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2678 /* try with the computer name as the account name */
2679 domain_size = sizeof(computer_name);
2680 GetComputerNameA(computer_name, &domain_size);
2681 sid_size = 0;
2682 domain_size = 0;
2683 ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2684 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
2685 GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
2686 broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
2687 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
2688 "LookupAccountNameA failed: %d\n", GetLastError());
2689 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2691 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2692 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2693 ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
2694 ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
2695 ok(sid_use == SidTypeDomain ||
2696 (sid_use == SidTypeUser && ! strcmp(computer_name, user_name)), "expected SidTypeDomain for %s, got %d\n", computer_name, sid_use);
2697 HeapFree(GetProcessHeap(), 0, domain);
2698 HeapFree(GetProcessHeap(), 0, psid);
2701 /* Well Known names */
2702 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2704 skip("Non-English locale (skipping well known name creation tests)\n");
2705 return;
2708 check_wellknown_name("LocalService", WinLocalServiceSid);
2709 check_wellknown_name("Local Service", WinLocalServiceSid);
2710 /* 2 spaces */
2711 check_wellknown_name("Local Service", 0);
2712 check_wellknown_name("NetworkService", WinNetworkServiceSid);
2713 check_wellknown_name("Network Service", WinNetworkServiceSid);
2715 /* example of some names where the spaces are not optional */
2716 check_wellknown_name("Terminal Server User", WinTerminalServerSid);
2717 check_wellknown_name("TerminalServer User", 0);
2718 check_wellknown_name("TerminalServerUser", 0);
2719 check_wellknown_name("Terminal ServerUser", 0);
2721 check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
2722 check_wellknown_name("enterprisedomain controllers", 0);
2723 check_wellknown_name("enterprise domaincontrollers", 0);
2724 check_wellknown_name("enterprisedomaincontrollers", 0);
2726 /* case insensitivity */
2727 check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
2729 /* fully qualified account names */
2730 check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
2731 check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
2732 check_wellknown_name("nt authority test\\Network Service", 0);
2733 check_wellknown_name("Dummy\\Network Service", 0);
2734 check_wellknown_name("ntauthority\\Network Service", 0);
2737 static void test_security_descriptor(void)
2739 SECURITY_DESCRIPTOR sd, *sd_rel, *sd_rel2, *sd_abs;
2740 char buf[8192];
2741 DWORD size, size_dacl, size_sacl, size_owner, size_group;
2742 BOOL isDefault, isPresent, ret;
2743 PACL pacl, dacl, sacl;
2744 PSID psid, owner, group;
2746 SetLastError(0xdeadbeef);
2747 ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
2748 if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2750 win_skip("InitializeSecurityDescriptor is not implemented\n");
2751 return;
2754 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2755 expect_eq(psid, NULL, PSID, "%p");
2756 expect_eq(isDefault, FALSE, BOOL, "%d");
2757 sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
2759 SetLastError(0xdeadbeef);
2760 size = 5;
2761 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
2762 expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
2763 ok(size > 5, "Size not increased\n");
2764 if (size <= 8192)
2766 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
2767 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2768 expect_eq(psid, NULL, PSID, "%p");
2769 expect_eq(isDefault, FALSE, BOOL, "%d");
2770 ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
2771 expect_eq(psid, NULL, PSID, "%p");
2772 expect_eq(isDefault, FALSE, BOOL, "%d");
2773 ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
2774 expect_eq(isPresent, TRUE, BOOL, "%d");
2775 expect_eq(psid, NULL, PSID, "%p");
2776 expect_eq(isDefault, FALSE, BOOL, "%d");
2777 ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
2778 expect_eq(isPresent, TRUE, BOOL, "%d");
2779 expect_eq(psid, NULL, PSID, "%p");
2780 expect_eq(isDefault, FALSE, BOOL, "%d");
2783 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
2784 "O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
2785 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)"
2786 "(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, (void **)&sd_rel, NULL);
2787 ok(ret, "got %u\n", GetLastError());
2789 size = 0;
2790 ret = MakeSelfRelativeSD(sd_rel, NULL, &size);
2791 todo_wine ok(!ret && GetLastError() == ERROR_BAD_DESCRIPTOR_FORMAT, "got %u\n", GetLastError());
2793 /* convert to absolute form */
2794 size = size_dacl = size_sacl = size_owner = size_group = 0;
2795 ret = MakeAbsoluteSD(sd_rel, NULL, &size, NULL, &size_dacl, NULL, &size_sacl, NULL, &size_owner, NULL,
2796 &size_group);
2797 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %u\n", GetLastError());
2799 sd_abs = HeapAlloc(GetProcessHeap(), 0, size + size_dacl + size_sacl + size_owner + size_group);
2800 dacl = (PACL)(sd_abs + 1);
2801 sacl = (PACL)((char *)dacl + size_dacl);
2802 owner = (PSID)((char *)sacl + size_sacl);
2803 group = (PSID)((char *)owner + size_owner);
2804 ret = MakeAbsoluteSD(sd_rel, sd_abs, &size, dacl, &size_dacl, sacl, &size_sacl, owner, &size_owner,
2805 group, &size_group);
2806 ok(ret, "got %u\n", GetLastError());
2808 size = 0;
2809 ret = MakeSelfRelativeSD(sd_abs, NULL, &size);
2810 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %u\n", GetLastError());
2811 ok(size == 184, "got %u\n", size);
2813 size += 4;
2814 sd_rel2 = HeapAlloc(GetProcessHeap(), 0, size);
2815 ret = MakeSelfRelativeSD(sd_abs, sd_rel2, &size);
2816 ok(ret, "got %u\n", GetLastError());
2817 ok(size == 188, "got %u\n", size);
2819 HeapFree(GetProcessHeap(), 0, sd_abs);
2820 HeapFree(GetProcessHeap(), 0, sd_rel2);
2821 LocalFree(sd_rel);
2824 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
2825 #define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
2826 static void test_granted_access(HANDLE handle, ACCESS_MASK access,
2827 ACCESS_MASK alt, int line)
2829 OBJECT_BASIC_INFORMATION obj_info;
2830 NTSTATUS status;
2832 if (!pNtQueryObject)
2834 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
2835 return;
2838 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
2839 sizeof(obj_info), NULL );
2840 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2841 if (alt)
2842 ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
2843 obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
2844 "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
2845 else
2846 ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
2847 "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
2850 #define CHECK_SET_SECURITY(o,i,e) \
2851 do{ \
2852 BOOL res_; \
2853 DWORD err; \
2854 SetLastError( 0xdeadbeef ); \
2855 res_ = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
2856 err = GetLastError(); \
2857 if (e == ERROR_SUCCESS) \
2858 ok(res_, "SetKernelObjectSecurity failed with %d\n", err); \
2859 else \
2860 ok(!res_ && err == e, "SetKernelObjectSecurity should have failed " \
2861 "with %s, instead of %d\n", #e, err); \
2862 }while(0)
2864 static void test_process_security(void)
2866 BOOL res;
2867 PTOKEN_USER user;
2868 PTOKEN_OWNER owner;
2869 PTOKEN_PRIMARY_GROUP group;
2870 PSID AdminSid = NULL, UsersSid = NULL, UserSid = NULL;
2871 PACL Acl = NULL, ThreadAcl = NULL;
2872 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL, *ThreadSecurityDescriptor = NULL;
2873 char buffer[MAX_PATH], account[MAX_PATH], domain[MAX_PATH];
2874 PROCESS_INFORMATION info;
2875 STARTUPINFOA startup;
2876 SECURITY_ATTRIBUTES psa, tsa;
2877 HANDLE token, event;
2878 DWORD size, acc_size, dom_size, ret;
2879 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2880 PSID EveryoneSid = NULL;
2881 SID_NAME_USE use;
2883 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
2884 res = InitializeAcl(Acl, 256, ACL_REVISION);
2885 if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2887 win_skip("ACLs not implemented - skipping tests\n");
2888 HeapFree(GetProcessHeap(), 0, Acl);
2889 return;
2891 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2893 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2894 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2896 /* get owner from the token we might be running as a user not admin */
2897 res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
2898 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
2899 if (!res)
2901 HeapFree(GetProcessHeap(), 0, Acl);
2902 return;
2905 res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
2906 ok(!res, "Expected failure, got %d\n", res);
2907 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2908 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2910 owner = HeapAlloc(GetProcessHeap(), 0, size);
2911 res = GetTokenInformation( token, TokenOwner, owner, size, &size );
2912 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2913 AdminSid = owner->Owner;
2914 test_sid_str(AdminSid);
2916 res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
2917 ok(!res, "Expected failure, got %d\n", res);
2918 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2919 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2921 group = HeapAlloc(GetProcessHeap(), 0, size);
2922 res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
2923 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2924 UsersSid = group->PrimaryGroup;
2925 test_sid_str(UsersSid);
2927 acc_size = sizeof(account);
2928 dom_size = sizeof(domain);
2929 ret = LookupAccountSidA( NULL, UsersSid, account, &acc_size, domain, &dom_size, &use );
2930 ok(ret, "LookupAccountSid failed with %d\n", ret);
2931 ok(use == SidTypeGroup, "expect SidTypeGroup, got %d\n", use);
2932 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2933 skip("Non-English locale (test with hardcoded 'None')\n");
2934 else
2935 ok(!strcmp(account, "None"), "expect None, got %s\n", account);
2937 res = GetTokenInformation( token, TokenUser, NULL, 0, &size );
2938 ok(!res, "Expected failure, got %d\n", res);
2939 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2940 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2942 user = HeapAlloc(GetProcessHeap(), 0, size);
2943 res = GetTokenInformation( token, TokenUser, user, size, &size );
2944 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2945 UserSid = user->User.Sid;
2946 test_sid_str(UserSid);
2947 ok(EqualPrefixSid(UsersSid, UserSid), "TokenPrimaryGroup Sid and TokenUser Sid don't match.\n");
2949 CloseHandle( token );
2950 if (!res)
2952 HeapFree(GetProcessHeap(), 0, group);
2953 HeapFree(GetProcessHeap(), 0, owner);
2954 HeapFree(GetProcessHeap(), 0, user);
2955 HeapFree(GetProcessHeap(), 0, Acl);
2956 return;
2959 res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
2960 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
2961 res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
2962 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2964 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
2965 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
2966 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
2968 event = CreateEventA( NULL, TRUE, TRUE, "test_event" );
2969 ok(event != NULL, "CreateEvent %d\n", GetLastError());
2971 SecurityDescriptor->Revision = 0;
2972 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
2973 SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
2975 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2976 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2977 CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
2978 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2979 /* NULL DACL is valid and means that everyone has access */
2980 SecurityDescriptor->Control |= SE_DACL_PRESENT;
2981 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2983 /* Set owner and group and dacl */
2984 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
2985 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2986 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
2987 test_owner_equal( event, AdminSid, __LINE__ );
2989 res = SetSecurityDescriptorGroup(SecurityDescriptor, EveryoneSid, FALSE);
2990 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2991 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
2992 test_group_equal( event, EveryoneSid, __LINE__ );
2994 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
2995 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
2996 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2997 /* setting a dacl should not change the owner or group */
2998 test_owner_equal( event, AdminSid, __LINE__ );
2999 test_group_equal( event, EveryoneSid, __LINE__ );
3001 /* Test again with a different SID in case the previous SID also happens to
3002 * be the one that is incorrectly replacing the group. */
3003 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
3004 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3005 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
3006 test_group_equal( event, UsersSid, __LINE__ );
3008 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
3009 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
3010 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
3011 test_group_equal( event, UsersSid, __LINE__ );
3013 sprintf(buffer, "%s security test", myARGV[0]);
3014 memset(&startup, 0, sizeof(startup));
3015 startup.cb = sizeof(startup);
3016 startup.dwFlags = STARTF_USESHOWWINDOW;
3017 startup.wShowWindow = SW_SHOWNORMAL;
3019 psa.nLength = sizeof(psa);
3020 psa.lpSecurityDescriptor = SecurityDescriptor;
3021 psa.bInheritHandle = TRUE;
3023 ThreadSecurityDescriptor = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
3024 res = InitializeSecurityDescriptor( ThreadSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION );
3025 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
3027 ThreadAcl = HeapAlloc( GetProcessHeap(), 0, 256 );
3028 res = InitializeAcl( ThreadAcl, 256, ACL_REVISION );
3029 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
3030 res = AddAccessDeniedAce( ThreadAcl, ACL_REVISION, THREAD_SET_THREAD_TOKEN, AdminSid );
3031 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError() );
3032 res = AddAccessAllowedAce( ThreadAcl, ACL_REVISION, THREAD_ALL_ACCESS, AdminSid );
3033 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3035 res = SetSecurityDescriptorOwner( ThreadSecurityDescriptor, AdminSid, FALSE );
3036 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3037 res = SetSecurityDescriptorGroup( ThreadSecurityDescriptor, UsersSid, FALSE );
3038 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3039 res = SetSecurityDescriptorDacl( ThreadSecurityDescriptor, TRUE, ThreadAcl, FALSE );
3040 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
3042 tsa.nLength = sizeof(tsa);
3043 tsa.lpSecurityDescriptor = ThreadSecurityDescriptor;
3044 tsa.bInheritHandle = TRUE;
3046 /* Doesn't matter what ACL say we should get full access for ourselves */
3047 res = CreateProcessA( NULL, buffer, &psa, &tsa, FALSE, 0, NULL, NULL, &startup, &info );
3048 ok(res, "CreateProcess with err:%d\n", GetLastError());
3049 TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS_NT4,
3050 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
3051 TEST_GRANTED_ACCESS2( info.hThread, THREAD_ALL_ACCESS_NT4,
3052 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
3053 wait_child_process( info.hProcess );
3055 FreeSid(EveryoneSid);
3056 CloseHandle( info.hProcess );
3057 CloseHandle( info.hThread );
3058 CloseHandle( event );
3059 HeapFree(GetProcessHeap(), 0, group);
3060 HeapFree(GetProcessHeap(), 0, owner);
3061 HeapFree(GetProcessHeap(), 0, user);
3062 HeapFree(GetProcessHeap(), 0, Acl);
3063 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
3064 HeapFree(GetProcessHeap(), 0, ThreadAcl);
3065 HeapFree(GetProcessHeap(), 0, ThreadSecurityDescriptor);
3068 static void test_process_security_child(void)
3070 HANDLE handle, handle1;
3071 BOOL ret;
3072 DWORD err;
3074 handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
3075 ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
3076 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
3078 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
3079 &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS );
3080 ok(ret, "duplicating handle err:%d\n", GetLastError());
3081 TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
3083 CloseHandle( handle1 );
3085 SetLastError( 0xdeadbeef );
3086 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
3087 &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
3088 err = GetLastError();
3089 ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
3090 "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
3092 CloseHandle( handle );
3094 /* These two should fail - they are denied by ACL */
3095 handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
3096 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
3097 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
3098 ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
3100 /* Documented privilege elevation */
3101 ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
3102 &handle, 0, TRUE, DUPLICATE_SAME_ACCESS );
3103 ok(ret, "duplicating handle err:%d\n", GetLastError());
3104 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
3105 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
3107 CloseHandle( handle );
3109 /* Same only explicitly asking for all access rights */
3110 ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
3111 &handle, PROCESS_ALL_ACCESS, TRUE, 0 );
3112 ok(ret, "duplicating handle err:%d\n", GetLastError());
3113 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
3114 PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
3115 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
3116 &handle1, PROCESS_VM_READ, TRUE, 0 );
3117 ok(ret, "duplicating handle err:%d\n", GetLastError());
3118 TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
3119 CloseHandle( handle1 );
3120 CloseHandle( handle );
3122 /* Test thread security */
3123 handle = OpenThread( THREAD_TERMINATE, FALSE, GetCurrentThreadId() );
3124 ok(handle != NULL, "OpenThread(THREAD_TERMINATE) with err:%d\n", GetLastError());
3125 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
3126 CloseHandle( handle );
3128 handle = OpenThread( THREAD_SET_THREAD_TOKEN, FALSE, GetCurrentThreadId() );
3129 ok(handle == NULL, "OpenThread(THREAD_SET_THREAD_TOKEN) should have failed\n");
3132 static void test_impersonation_level(void)
3134 HANDLE Token, ProcessToken;
3135 HANDLE Token2;
3136 DWORD Size;
3137 TOKEN_PRIVILEGES *Privileges;
3138 TOKEN_USER *User;
3139 PRIVILEGE_SET *PrivilegeSet;
3140 BOOL AccessGranted;
3141 BOOL ret;
3142 HKEY hkey;
3143 DWORD error;
3145 if( !pDuplicateTokenEx ) {
3146 win_skip("DuplicateTokenEx is not available\n");
3147 return;
3149 SetLastError(0xdeadbeef);
3150 ret = ImpersonateSelf(SecurityAnonymous);
3151 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3153 win_skip("ImpersonateSelf is not implemented\n");
3154 return;
3156 ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
3157 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
3158 ok(!ret, "OpenThreadToken should have failed\n");
3159 error = GetLastError();
3160 ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
3161 /* can't perform access check when opening object against an anonymous impersonation token */
3162 todo_wine {
3163 error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
3164 ok(error == ERROR_INVALID_HANDLE || error == ERROR_CANT_OPEN_ANONYMOUS || error == ERROR_BAD_IMPERSONATION_LEVEL,
3165 "RegOpenKeyEx failed with %d\n", error);
3167 RevertToSelf();
3169 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
3170 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
3172 ret = pDuplicateTokenEx(ProcessToken,
3173 TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
3174 SecurityAnonymous, TokenImpersonation, &Token);
3175 ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
3176 /* can't increase the impersonation level */
3177 ret = DuplicateToken(Token, SecurityIdentification, &Token2);
3178 error = GetLastError();
3179 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
3180 "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
3181 /* we can query anything from an anonymous token, including the user */
3182 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
3183 error = GetLastError();
3184 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
3185 User = HeapAlloc(GetProcessHeap(), 0, Size);
3186 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
3187 ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3188 HeapFree(GetProcessHeap(), 0, User);
3190 /* PrivilegeCheck fails with SecurityAnonymous level */
3191 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
3192 error = GetLastError();
3193 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
3194 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
3195 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
3196 ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
3198 PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
3199 PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
3200 memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
3201 PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
3202 HeapFree(GetProcessHeap(), 0, Privileges);
3204 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
3205 error = GetLastError();
3206 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
3208 CloseHandle(Token);
3210 ret = ImpersonateSelf(SecurityIdentification);
3211 ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
3212 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
3213 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
3215 /* can't perform access check when opening object against an identification impersonation token */
3216 error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
3217 todo_wine {
3218 ok(error == ERROR_INVALID_HANDLE || error == ERROR_BAD_IMPERSONATION_LEVEL || error == ERROR_ACCESS_DENIED,
3219 "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE, ERROR_BAD_IMPERSONATION_LEVEL or ERROR_ACCESS_DENIED instead of %d\n", error);
3221 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
3222 ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
3223 CloseHandle(Token);
3224 RevertToSelf();
3226 ret = ImpersonateSelf(SecurityImpersonation);
3227 ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
3228 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
3229 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
3230 error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
3231 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
3232 RegCloseKey(hkey);
3233 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
3234 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
3235 RevertToSelf();
3237 CloseHandle(Token);
3238 CloseHandle(ProcessToken);
3240 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
3243 static void test_SetEntriesInAclW(void)
3245 DWORD res;
3246 PSID EveryoneSid = NULL, UsersSid = NULL;
3247 PACL OldAcl = NULL, NewAcl;
3248 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
3249 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3250 EXPLICIT_ACCESSW ExplicitAccess;
3251 static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
3252 static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
3254 if (!pSetEntriesInAclW)
3256 win_skip("SetEntriesInAclW is not available\n");
3257 return;
3260 NewAcl = (PACL)0xdeadbeef;
3261 res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
3262 if(res == ERROR_CALL_NOT_IMPLEMENTED)
3264 win_skip("SetEntriesInAclW is not implemented\n");
3265 return;
3267 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3268 ok(NewAcl == NULL ||
3269 broken(NewAcl != NULL), /* NT4 */
3270 "NewAcl=%p, expected NULL\n", NewAcl);
3271 LocalFree(NewAcl);
3273 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
3274 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
3275 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3277 win_skip("ACLs not implemented - skipping tests\n");
3278 HeapFree(GetProcessHeap(), 0, OldAcl);
3279 return;
3281 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
3283 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
3284 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3286 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
3287 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
3288 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3290 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
3291 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3293 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
3294 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
3295 ExplicitAccess.grfInheritance = NO_INHERITANCE;
3296 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
3297 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3298 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
3299 ExplicitAccess.Trustee.MultipleTrusteeOperation = 0xDEADBEEF;
3300 ExplicitAccess.Trustee.pMultipleTrustee = (PVOID)0xDEADBEEF;
3301 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3302 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3303 ok(NewAcl != NULL, "returned acl was NULL\n");
3304 LocalFree(NewAcl);
3306 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
3307 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
3308 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3309 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3310 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3311 ok(NewAcl != NULL, "returned acl was NULL\n");
3312 LocalFree(NewAcl);
3314 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
3316 skip("Non-English locale (test with hardcoded 'Everyone')\n");
3318 else
3320 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3321 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
3322 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3323 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3324 ok(NewAcl != NULL, "returned acl was NULL\n");
3325 LocalFree(NewAcl);
3327 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
3328 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3329 ok(res == ERROR_INVALID_PARAMETER ||
3330 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3331 "SetEntriesInAclW failed: %u\n", res);
3332 ok(NewAcl == NULL ||
3333 broken(NewAcl != NULL), /* NT4 */
3334 "returned acl wasn't NULL: %p\n", NewAcl);
3336 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3337 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
3338 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3339 ok(res == ERROR_INVALID_PARAMETER ||
3340 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3341 "SetEntriesInAclW failed: %u\n", res);
3342 ok(NewAcl == NULL ||
3343 broken(NewAcl != NULL), /* NT4 */
3344 "returned acl wasn't NULL: %p\n", NewAcl);
3346 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3347 ExplicitAccess.grfAccessMode = SET_ACCESS;
3348 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3349 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3350 ok(NewAcl != NULL, "returned acl was NULL\n");
3351 LocalFree(NewAcl);
3354 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3355 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
3356 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3357 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3358 ok(NewAcl != NULL, "returned acl was NULL\n");
3359 LocalFree(NewAcl);
3361 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
3362 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3363 ExplicitAccess.Trustee.ptstrName = UsersSid;
3364 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3365 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3366 ok(NewAcl != NULL, "returned acl was NULL\n");
3367 LocalFree(NewAcl);
3369 FreeSid(UsersSid);
3370 FreeSid(EveryoneSid);
3371 HeapFree(GetProcessHeap(), 0, OldAcl);
3374 static void test_SetEntriesInAclA(void)
3376 DWORD res;
3377 PSID EveryoneSid = NULL, UsersSid = NULL;
3378 PACL OldAcl = NULL, NewAcl;
3379 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
3380 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3381 EXPLICIT_ACCESSA ExplicitAccess;
3382 static const CHAR szEveryone[] = {'E','v','e','r','y','o','n','e',0};
3383 static const CHAR szCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
3385 NewAcl = (PACL)0xdeadbeef;
3386 res = SetEntriesInAclA(0, NULL, NULL, &NewAcl);
3387 if(res == ERROR_CALL_NOT_IMPLEMENTED)
3389 win_skip("SetEntriesInAclA is not implemented\n");
3390 return;
3392 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3393 ok(NewAcl == NULL ||
3394 broken(NewAcl != NULL), /* NT4 */
3395 "NewAcl=%p, expected NULL\n", NewAcl);
3396 LocalFree(NewAcl);
3398 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
3399 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
3400 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3402 win_skip("ACLs not implemented - skipping tests\n");
3403 HeapFree(GetProcessHeap(), 0, OldAcl);
3404 return;
3406 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
3408 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
3409 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3411 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
3412 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
3413 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3415 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
3416 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3418 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
3419 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
3420 ExplicitAccess.grfInheritance = NO_INHERITANCE;
3421 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
3422 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3423 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
3424 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3425 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
3426 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3427 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3428 ok(NewAcl != NULL, "returned acl was NULL\n");
3429 LocalFree(NewAcl);
3431 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
3432 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
3433 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3434 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3435 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3436 ok(NewAcl != NULL, "returned acl was NULL\n");
3437 LocalFree(NewAcl);
3439 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
3441 skip("Non-English locale (test with hardcoded 'Everyone')\n");
3443 else
3445 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3446 ExplicitAccess.Trustee.ptstrName = (LPSTR)szEveryone;
3447 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3448 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3449 ok(NewAcl != NULL, "returned acl was NULL\n");
3450 LocalFree(NewAcl);
3452 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
3453 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3454 ok(res == ERROR_INVALID_PARAMETER ||
3455 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3456 "SetEntriesInAclA failed: %u\n", res);
3457 ok(NewAcl == NULL ||
3458 broken(NewAcl != NULL), /* NT4 */
3459 "returned acl wasn't NULL: %p\n", NewAcl);
3461 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3462 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
3463 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3464 ok(res == ERROR_INVALID_PARAMETER ||
3465 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3466 "SetEntriesInAclA failed: %u\n", res);
3467 ok(NewAcl == NULL ||
3468 broken(NewAcl != NULL), /* NT4 */
3469 "returned acl wasn't NULL: %p\n", NewAcl);
3471 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3472 ExplicitAccess.grfAccessMode = SET_ACCESS;
3473 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3474 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3475 ok(NewAcl != NULL, "returned acl was NULL\n");
3476 LocalFree(NewAcl);
3479 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3480 ExplicitAccess.Trustee.ptstrName = (LPSTR)szCurrentUser;
3481 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3482 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3483 ok(NewAcl != NULL, "returned acl was NULL\n");
3484 LocalFree(NewAcl);
3486 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
3487 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3488 ExplicitAccess.Trustee.ptstrName = UsersSid;
3489 res = SetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3490 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3491 ok(NewAcl != NULL, "returned acl was NULL\n");
3492 LocalFree(NewAcl);
3494 FreeSid(UsersSid);
3495 FreeSid(EveryoneSid);
3496 HeapFree(GetProcessHeap(), 0, OldAcl);
3499 /* helper function for test_CreateDirectoryA */
3500 static void get_nt_pathW(const char *name, UNICODE_STRING *nameW)
3502 UNICODE_STRING strW;
3503 ANSI_STRING str;
3504 NTSTATUS status;
3505 BOOLEAN ret;
3507 pRtlInitAnsiString(&str, name);
3509 status = pRtlAnsiStringToUnicodeString(&strW, &str, TRUE);
3510 ok(!status, "RtlAnsiStringToUnicodeString failed with %08x\n", status);
3512 ret = pRtlDosPathNameToNtPathName_U(strW.Buffer, nameW, NULL, NULL);
3513 ok(ret, "RtlDosPathNameToNtPathName_U failed\n");
3515 pRtlFreeUnicodeString(&strW);
3518 static void test_inherited_dacl(PACL dacl, PSID admin_sid, PSID user_sid, DWORD flags, DWORD mask,
3519 BOOL todo_count, BOOL todo_sid, BOOL todo_flags, int line)
3521 ACL_SIZE_INFORMATION acl_size;
3522 ACCESS_ALLOWED_ACE *ace;
3523 BOOL bret;
3525 bret = GetAclInformation(dacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3526 ok_(__FILE__, line)(bret, "GetAclInformation failed\n");
3528 todo_wine_if (todo_count)
3529 ok_(__FILE__, line)(acl_size.AceCount == 2,
3530 "GetAclInformation returned unexpected entry count (%d != 2)\n",
3531 acl_size.AceCount);
3533 if (acl_size.AceCount > 0)
3535 bret = GetAce(dacl, 0, (VOID **)&ace);
3536 ok_(__FILE__, line)(bret, "Failed to get Current User ACE\n");
3538 bret = EqualSid(&ace->SidStart, user_sid);
3539 todo_wine_if (todo_sid)
3540 ok_(__FILE__, line)(bret, "Current User ACE (%s) != Current User SID (%s)\n", debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
3542 todo_wine_if (todo_flags)
3543 ok_(__FILE__, line)(((ACE_HEADER *)ace)->AceFlags == flags,
3544 "Current User ACE has unexpected flags (0x%x != 0x%x)\n",
3545 ((ACE_HEADER *)ace)->AceFlags, flags);
3547 ok_(__FILE__, line)(ace->Mask == mask,
3548 "Current User ACE has unexpected mask (0x%x != 0x%x)\n",
3549 ace->Mask, mask);
3551 if (acl_size.AceCount > 1)
3553 bret = GetAce(dacl, 1, (VOID **)&ace);
3554 ok_(__FILE__, line)(bret, "Failed to get Administators Group ACE\n");
3556 bret = EqualSid(&ace->SidStart, admin_sid);
3557 todo_wine_if (todo_sid)
3558 ok_(__FILE__, line)(bret, "Administators Group ACE (%s) != Administators Group SID (%s)\n", debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
3560 todo_wine_if (todo_flags)
3561 ok_(__FILE__, line)(((ACE_HEADER *)ace)->AceFlags == flags,
3562 "Administators Group ACE has unexpected flags (0x%x != 0x%x)\n",
3563 ((ACE_HEADER *)ace)->AceFlags, flags);
3565 ok_(__FILE__, line)(ace->Mask == mask,
3566 "Administators Group ACE has unexpected mask (0x%x != 0x%x)\n",
3567 ace->Mask, mask);
3571 static void test_CreateDirectoryA(void)
3573 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
3574 DWORD sid_size = sizeof(admin_ptr), user_size;
3575 PSID admin_sid = (PSID) admin_ptr, user_sid;
3576 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3577 PSECURITY_DESCRIPTOR pSD = &sd;
3578 ACL_SIZE_INFORMATION acl_size;
3579 UNICODE_STRING tmpfileW;
3580 SECURITY_ATTRIBUTES sa;
3581 OBJECT_ATTRIBUTES attr;
3582 char tmpfile[MAX_PATH];
3583 char tmpdir[MAX_PATH];
3584 HANDLE token, hTemp;
3585 IO_STATUS_BLOCK io;
3586 struct _SID *owner;
3587 BOOL bret = TRUE;
3588 NTSTATUS status;
3589 DWORD error;
3590 PACL pDacl;
3592 if (!pGetNamedSecurityInfoA)
3594 win_skip("Required functions are not available\n");
3595 return;
3598 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3600 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3601 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3603 if (!bret)
3605 win_skip("Failed to get current user token\n");
3606 return;
3608 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3609 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3610 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3611 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3612 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3613 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3614 CloseHandle( token );
3615 user_sid = ((TOKEN_USER *)user)->User.Sid;
3617 sa.nLength = sizeof(sa);
3618 sa.lpSecurityDescriptor = pSD;
3619 sa.bInheritHandle = TRUE;
3620 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3621 CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3622 pDacl = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 100);
3623 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
3624 ok(bret, "Failed to initialize ACL.\n");
3625 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3626 GENERIC_ALL, user_sid);
3627 ok(bret, "Failed to add Current User to ACL.\n");
3628 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3629 GENERIC_ALL, admin_sid);
3630 ok(bret, "Failed to add Administrator Group to ACL.\n");
3631 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3632 ok(bret, "Failed to add ACL to security descriptor.\n");
3634 GetTempPathA(MAX_PATH, tmpdir);
3635 lstrcatA(tmpdir, "Please Remove Me");
3636 bret = CreateDirectoryA(tmpdir, &sa);
3637 ok(bret == TRUE, "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
3638 HeapFree(GetProcessHeap(), 0, pDacl);
3640 SetLastError(0xdeadbeef);
3641 error = pGetNamedSecurityInfoA(tmpdir, SE_FILE_OBJECT,
3642 OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, (PSID*)&owner,
3643 NULL, &pDacl, NULL, &pSD);
3644 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3646 win_skip("GetNamedSecurityInfoA is not implemented\n");
3647 goto done;
3649 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3650 test_inherited_dacl(pDacl, admin_sid, user_sid, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3651 0x1f01ff, FALSE, TRUE, FALSE, __LINE__);
3652 LocalFree(pSD);
3654 /* Test inheritance of ACLs in CreateFile without security descriptor */
3655 strcpy(tmpfile, tmpdir);
3656 lstrcatA(tmpfile, "/tmpfile");
3658 hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3659 CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
3660 ok(hTemp != INVALID_HANDLE_VALUE, "CreateFile error %u\n", GetLastError());
3662 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3663 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3664 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3665 ok(error == ERROR_SUCCESS, "Failed to get permissions on file\n");
3666 test_inherited_dacl(pDacl, admin_sid, user_sid, INHERITED_ACE,
3667 0x1f01ff, TRUE, TRUE, TRUE, __LINE__);
3668 LocalFree(pSD);
3669 CloseHandle(hTemp);
3671 /* Test inheritance of ACLs in CreateFile with security descriptor -
3672 * When a security descriptor is set, then inheritance doesn't take effect */
3673 pSD = &sd;
3674 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3675 pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
3676 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
3677 ok(bret, "Failed to initialize ACL\n");
3678 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3679 ok(bret, "Failed to add ACL to security descriptor\n");
3681 strcpy(tmpfile, tmpdir);
3682 lstrcatA(tmpfile, "/tmpfile");
3684 sa.nLength = sizeof(sa);
3685 sa.lpSecurityDescriptor = pSD;
3686 sa.bInheritHandle = TRUE;
3687 hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, &sa,
3688 CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
3689 ok(hTemp != INVALID_HANDLE_VALUE, "CreateFile error %u\n", GetLastError());
3690 HeapFree(GetProcessHeap(), 0, pDacl);
3692 error = GetSecurityInfo(hTemp, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3693 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3694 ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
3695 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3696 ok(bret, "GetAclInformation failed\n");
3697 todo_wine
3698 ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
3699 acl_size.AceCount);
3700 LocalFree(pSD);
3702 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3703 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3704 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3705 todo_wine
3706 ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
3707 if (error == ERROR_SUCCESS)
3709 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3710 ok(bret, "GetAclInformation failed\n");
3711 todo_wine
3712 ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
3713 acl_size.AceCount);
3714 LocalFree(pSD);
3716 CloseHandle(hTemp);
3718 /* Test inheritance of ACLs in NtCreateFile without security descriptor */
3719 strcpy(tmpfile, tmpdir);
3720 lstrcatA(tmpfile, "/tmpfile");
3721 get_nt_pathW(tmpfile, &tmpfileW);
3723 attr.Length = sizeof(attr);
3724 attr.RootDirectory = 0;
3725 attr.ObjectName = &tmpfileW;
3726 attr.Attributes = OBJ_CASE_INSENSITIVE;
3727 attr.SecurityDescriptor = NULL;
3728 attr.SecurityQualityOfService = NULL;
3730 status = pNtCreateFile(&hTemp, GENERIC_WRITE | DELETE, &attr, &io, NULL, 0,
3731 FILE_SHARE_READ, FILE_CREATE, FILE_DELETE_ON_CLOSE, NULL, 0);
3732 ok(!status, "NtCreateFile failed with %08x\n", status);
3733 pRtlFreeUnicodeString(&tmpfileW);
3735 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3736 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3737 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3738 ok(error == ERROR_SUCCESS, "Failed to get permissions on file\n");
3739 test_inherited_dacl(pDacl, admin_sid, user_sid, INHERITED_ACE,
3740 0x1f01ff, TRUE, TRUE, TRUE, __LINE__);
3741 LocalFree(pSD);
3742 CloseHandle(hTemp);
3744 /* Test inheritance of ACLs in NtCreateFile with security descriptor -
3745 * When a security descriptor is set, then inheritance doesn't take effect */
3746 pSD = &sd;
3747 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3748 pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
3749 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
3750 ok(bret, "Failed to initialize ACL\n");
3751 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3752 ok(bret, "Failed to add ACL to security descriptor\n");
3754 strcpy(tmpfile, tmpdir);
3755 lstrcatA(tmpfile, "/tmpfile");
3756 get_nt_pathW(tmpfile, &tmpfileW);
3758 attr.Length = sizeof(attr);
3759 attr.RootDirectory = 0;
3760 attr.ObjectName = &tmpfileW;
3761 attr.Attributes = OBJ_CASE_INSENSITIVE;
3762 attr.SecurityDescriptor = pSD;
3763 attr.SecurityQualityOfService = NULL;
3765 status = pNtCreateFile(&hTemp, GENERIC_WRITE | DELETE, &attr, &io, NULL, 0,
3766 FILE_SHARE_READ, FILE_CREATE, FILE_DELETE_ON_CLOSE, NULL, 0);
3767 ok(!status, "NtCreateFile failed with %08x\n", status);
3768 pRtlFreeUnicodeString(&tmpfileW);
3769 HeapFree(GetProcessHeap(), 0, pDacl);
3771 error = GetSecurityInfo(hTemp, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3772 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3773 ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
3774 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3775 ok(bret, "GetAclInformation failed\n");
3776 todo_wine
3777 ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
3778 acl_size.AceCount);
3779 LocalFree(pSD);
3781 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3782 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3783 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3784 todo_wine
3785 ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
3786 if (error == ERROR_SUCCESS)
3788 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3789 ok(bret, "GetAclInformation failed\n");
3790 todo_wine
3791 ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
3792 acl_size.AceCount);
3793 LocalFree(pSD);
3795 CloseHandle(hTemp);
3797 done:
3798 HeapFree(GetProcessHeap(), 0, user);
3799 bret = RemoveDirectoryA(tmpdir);
3800 ok(bret == TRUE, "RemoveDirectoryA should always succeed\n");
3803 static void test_GetNamedSecurityInfoA(void)
3805 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
3806 char system_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
3807 char users_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
3808 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3809 PSID admin_sid = (PSID) admin_ptr, users_sid = (PSID) users_ptr;
3810 PSID system_sid = (PSID) system_ptr, user_sid, localsys_sid;
3811 DWORD sid_size = sizeof(admin_ptr), user_size;
3812 char invalid_path[] = "/an invalid file path";
3813 int users_ace_id = -1, admins_ace_id = -1, i;
3814 char software_key[] = "MACHINE\\Software";
3815 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH+sizeof(void*)];
3816 SECURITY_DESCRIPTOR_CONTROL control;
3817 ACL_SIZE_INFORMATION acl_size;
3818 CHAR windows_dir[MAX_PATH];
3819 PSECURITY_DESCRIPTOR pSD;
3820 ACCESS_ALLOWED_ACE *ace;
3821 BOOL bret = TRUE, isNT4;
3822 char tmpfile[MAX_PATH];
3823 DWORD error, revision;
3824 BOOL owner_defaulted;
3825 BOOL group_defaulted;
3826 BOOL dacl_defaulted;
3827 HANDLE token, hTemp, h;
3828 PSID owner, group;
3829 BOOL dacl_present;
3830 PACL pDacl;
3831 BYTE flags;
3832 NTSTATUS status;
3834 if (!pSetNamedSecurityInfoA || !pGetNamedSecurityInfoA)
3836 win_skip("Required functions are not available\n");
3837 return;
3840 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3842 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3843 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3845 if (!bret)
3847 win_skip("Failed to get current user token\n");
3848 return;
3850 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3851 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3852 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3853 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3854 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3855 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3856 CloseHandle( token );
3857 user_sid = ((TOKEN_USER *)user)->User.Sid;
3859 bret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
3860 ok(bret, "GetWindowsDirectory failed with error %d\n", GetLastError());
3862 SetLastError(0xdeadbeef);
3863 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
3864 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
3865 NULL, NULL, NULL, NULL, &pSD);
3866 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3868 win_skip("GetNamedSecurityInfoA is not implemented\n");
3869 HeapFree(GetProcessHeap(), 0, user);
3870 return;
3872 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3874 bret = GetSecurityDescriptorControl(pSD, &control, &revision);
3875 ok(bret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
3876 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
3877 broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
3878 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
3879 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
3881 isNT4 = (control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT;
3883 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
3884 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3885 ok(owner != NULL, "owner should not be NULL\n");
3887 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
3888 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3889 ok(group != NULL, "group should not be NULL\n");
3890 LocalFree(pSD);
3893 /* NULL descriptor tests */
3894 if(isNT4)
3896 win_skip("NT4 does not support GetNamedSecutityInfo with a NULL descriptor\n");
3897 HeapFree(GetProcessHeap(), 0, user);
3898 return;
3901 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3902 NULL, NULL, NULL, NULL, NULL);
3903 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3905 pDacl = NULL;
3906 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3907 NULL, NULL, &pDacl, NULL, &pSD);
3908 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3909 ok(pDacl != NULL, "DACL should not be NULL\n");
3910 LocalFree(pSD);
3912 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,
3913 NULL, NULL, &pDacl, NULL, NULL);
3914 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3916 /* Test behavior of SetNamedSecurityInfo with an invalid path */
3917 SetLastError(0xdeadbeef);
3918 error = pSetNamedSecurityInfoA(invalid_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3919 NULL, NULL, NULL);
3920 ok(error == ERROR_FILE_NOT_FOUND, "Unexpected error returned: 0x%x\n", error);
3921 ok(GetLastError() == 0xdeadbeef, "Expected last error to remain unchanged.\n");
3923 /* Create security descriptor information and test that it comes back the same */
3924 pSD = &sd;
3925 pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
3926 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3927 CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3928 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
3929 ok(bret, "Failed to initialize ACL.\n");
3930 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
3931 ok(bret, "Failed to add Current User to ACL.\n");
3932 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
3933 ok(bret, "Failed to add Administrator Group to ACL.\n");
3934 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3935 ok(bret, "Failed to add ACL to security descriptor.\n");
3936 GetTempFileNameA(".", "foo", 0, tmpfile);
3937 hTemp = CreateFileA(tmpfile, WRITE_DAC|GENERIC_WRITE, FILE_SHARE_DELETE|FILE_SHARE_READ,
3938 NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);
3939 SetLastError(0xdeadbeef);
3940 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3941 NULL, pDacl, NULL);
3942 HeapFree(GetProcessHeap(), 0, pDacl);
3943 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3945 win_skip("SetNamedSecurityInfoA is not implemented\n");
3946 HeapFree(GetProcessHeap(), 0, user);
3947 CloseHandle(hTemp);
3948 return;
3950 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
3951 SetLastError(0xdeadbeef);
3952 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3953 NULL, NULL, &pDacl, NULL, &pSD);
3954 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3956 win_skip("GetNamedSecurityInfoA is not implemented\n");
3957 HeapFree(GetProcessHeap(), 0, user);
3958 CloseHandle(hTemp);
3959 return;
3961 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3963 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3964 ok(bret, "GetAclInformation failed\n");
3965 if (acl_size.AceCount > 0)
3967 bret = GetAce(pDacl, 0, (VOID **)&ace);
3968 ok(bret, "Failed to get Current User ACE.\n");
3969 bret = EqualSid(&ace->SidStart, user_sid);
3970 todo_wine ok(bret, "Current User ACE (%s) != Current User SID (%s).\n",
3971 debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
3972 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3973 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3974 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
3975 ace->Mask);
3977 if (acl_size.AceCount > 1)
3979 bret = GetAce(pDacl, 1, (VOID **)&ace);
3980 ok(bret, "Failed to get Administators Group ACE.\n");
3981 bret = EqualSid(&ace->SidStart, admin_sid);
3982 todo_wine ok(bret || broken(!bret) /* win2k */,
3983 "Administators Group ACE (%s) != Administators Group SID (%s).\n",
3984 debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
3985 ok(((ACE_HEADER *)ace)->AceFlags == 0,
3986 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
3987 ok(ace->Mask == 0x1f01ff || broken(ace->Mask == GENERIC_ALL) /* win2k */,
3988 "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n", ace->Mask);
3990 LocalFree(pSD);
3992 /* show that setting empty DACL is not removing all file permissions */
3993 pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
3994 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
3995 ok(bret, "Failed to initialize ACL.\n");
3996 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
3997 NULL, NULL, pDacl, NULL);
3998 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
3999 HeapFree(GetProcessHeap(), 0, pDacl);
4001 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4002 NULL, NULL, &pDacl, NULL, &pSD);
4003 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4005 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4006 ok(bret, "GetAclInformation failed\n");
4007 if (acl_size.AceCount > 0)
4009 bret = GetAce(pDacl, 0, (VOID **)&ace);
4010 ok(bret, "Failed to get ACE.\n");
4011 todo_wine ok(((ACE_HEADER *)ace)->AceFlags & INHERITED_ACE,
4012 "ACE has unexpected flags: 0x%x\n", ((ACE_HEADER *)ace)->AceFlags);
4014 LocalFree(pSD);
4016 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4017 NULL, OPEN_EXISTING, 0, NULL);
4018 ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4019 CloseHandle(h);
4021 /* test setting NULL DACL */
4022 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
4023 DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);
4024 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
4026 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4027 NULL, NULL, &pDacl, NULL, &pSD);
4028 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4029 todo_wine ok(!pDacl, "pDacl != NULL\n");
4030 LocalFree(pSD);
4032 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4033 NULL, OPEN_EXISTING, 0, NULL);
4034 ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4035 CloseHandle(h);
4037 /* NtSetSecurityObject doesn't inherit DACL entries */
4038 pSD = sd+sizeof(void*)-((ULONG_PTR)sd)%sizeof(void*);
4039 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
4040 pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
4041 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
4042 ok(bret, "Failed to initialize ACL.\n");
4043 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4044 ok(bret, "Failed to add ACL to security descriptor.\n");
4045 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4046 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4048 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4049 NULL, OPEN_EXISTING, 0, NULL);
4050 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4051 CloseHandle(h);
4053 pSetSecurityDescriptorControl(pSD, SE_DACL_AUTO_INHERIT_REQ, SE_DACL_AUTO_INHERIT_REQ);
4054 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4055 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4057 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4058 NULL, OPEN_EXISTING, 0, NULL);
4059 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4060 CloseHandle(h);
4062 pSetSecurityDescriptorControl(pSD, SE_DACL_AUTO_INHERIT_REQ|SE_DACL_AUTO_INHERITED,
4063 SE_DACL_AUTO_INHERIT_REQ|SE_DACL_AUTO_INHERITED);
4064 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4065 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4067 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4068 NULL, OPEN_EXISTING, 0, NULL);
4069 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4070 CloseHandle(h);
4072 /* test if DACL is properly mapped to permission */
4073 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
4074 ok(bret, "Failed to initialize ACL.\n");
4075 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4076 ok(bret, "Failed to add Current User to ACL.\n");
4077 bret = pAddAccessDeniedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4078 ok(bret, "Failed to add Current User to ACL.\n");
4079 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4080 ok(bret, "Failed to add ACL to security descriptor.\n");
4081 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4082 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4084 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4085 NULL, OPEN_EXISTING, 0, NULL);
4086 ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4087 CloseHandle(h);
4089 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
4090 ok(bret, "Failed to initialize ACL.\n");
4091 bret = pAddAccessDeniedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4092 ok(bret, "Failed to add Current User to ACL.\n");
4093 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4094 ok(bret, "Failed to add Current User to ACL.\n");
4095 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4096 ok(bret, "Failed to add ACL to security descriptor.\n");
4097 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4098 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4100 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4101 NULL, OPEN_EXISTING, 0, NULL);
4102 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4103 HeapFree(GetProcessHeap(), 0, pDacl);
4104 HeapFree(GetProcessHeap(), 0, user);
4105 CloseHandle(hTemp);
4107 /* Test querying the ownership of a built-in registry key */
4108 sid_size = sizeof(system_ptr);
4109 CreateWellKnownSid(WinLocalSystemSid, NULL, system_sid, &sid_size);
4110 error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY,
4111 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
4112 NULL, NULL, NULL, NULL, &pSD);
4113 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4115 bret = AllocateAndInitializeSid(&SIDAuthNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &localsys_sid);
4116 ok(bret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
4118 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
4119 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
4120 ok(owner != NULL, "owner should not be NULL\n");
4121 ok(EqualSid(owner, admin_sid) || EqualSid(owner, localsys_sid),
4122 "MACHINE\\Software owner SID (%s) != Administrators SID (%s) or Local System Sid (%s).\n",
4123 debugstr_sid(owner), debugstr_sid(admin_sid), debugstr_sid(localsys_sid));
4125 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
4126 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
4127 ok(group != NULL, "group should not be NULL\n");
4128 ok(EqualSid(group, admin_sid) || broken(EqualSid(group, system_sid)) /* before Win7 */
4129 || broken(((SID*)group)->SubAuthority[0] == SECURITY_NT_NON_UNIQUE) /* Vista */,
4130 "MACHINE\\Software group SID (%s) != Local System SID (%s or %s)\n",
4131 debugstr_sid(group), debugstr_sid(admin_sid), debugstr_sid(system_sid));
4132 LocalFree(pSD);
4134 /* Test querying the DACL of a built-in registry key */
4135 sid_size = sizeof(users_ptr);
4136 CreateWellKnownSid(WinBuiltinUsersSid, NULL, users_sid, &sid_size);
4137 error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
4138 NULL, NULL, NULL, NULL, &pSD);
4139 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4141 bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
4142 ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
4143 ok(dacl_present, "DACL should be present\n");
4144 ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
4145 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4146 ok(bret, "GetAclInformation failed\n");
4147 ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
4148 for (i=0; i<acl_size.AceCount; i++)
4150 bret = GetAce(pDacl, i, (VOID **)&ace);
4151 ok(bret, "Failed to get ACE %d.\n", i);
4152 bret = EqualSid(&ace->SidStart, users_sid);
4153 if (bret) users_ace_id = i;
4154 bret = EqualSid(&ace->SidStart, admin_sid);
4155 if (bret) admins_ace_id = i;
4157 ok(users_ace_id != -1 || broken(users_ace_id == -1) /* win2k */,
4158 "Builtin Users ACE not found.\n");
4159 if (users_ace_id != -1)
4161 bret = GetAce(pDacl, users_ace_id, (VOID **)&ace);
4162 ok(bret, "Failed to get Builtin Users ACE.\n");
4163 flags = ((ACE_HEADER *)ace)->AceFlags;
4164 ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)
4165 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */
4166 || broken(flags == (CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* win 10 wow64 */
4167 || broken(flags == CONTAINER_INHERIT_ACE), /* win 10 */
4168 "Builtin Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
4169 INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
4170 ok(ace->Mask == GENERIC_READ
4171 || broken(ace->Mask == KEY_READ), /* win 10 */
4172 "Builtin Users ACE has unexpected mask (0x%x != 0x%x)\n",
4173 ace->Mask, GENERIC_READ);
4175 ok(admins_ace_id != -1, "Builtin Admins ACE not found.\n");
4176 if (admins_ace_id != -1)
4178 bret = GetAce(pDacl, admins_ace_id, (VOID **)&ace);
4179 ok(bret, "Failed to get Builtin Admins ACE.\n");
4180 flags = ((ACE_HEADER *)ace)->AceFlags;
4181 ok(flags == 0x0
4182 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */
4183 || broken(flags == (OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE)) /* win7 */
4184 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)) /* win8+ */
4185 || broken(flags == (CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* win 10 wow64 */
4186 || broken(flags == CONTAINER_INHERIT_ACE), /* win 10 */
4187 "Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
4188 ok(ace->Mask == KEY_ALL_ACCESS || broken(ace->Mask == GENERIC_ALL) /* w2k8 */,
4189 "Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, KEY_ALL_ACCESS);
4192 FreeSid(localsys_sid);
4193 LocalFree(pSD);
4196 static void test_ConvertStringSecurityDescriptor(void)
4198 BOOL ret;
4199 PSECURITY_DESCRIPTOR pSD;
4200 static const WCHAR Blank[] = { 0 };
4201 unsigned int i;
4202 ULONG size;
4203 ACL *acl;
4204 static const struct
4206 const char *sidstring;
4207 DWORD revision;
4208 BOOL ret;
4209 DWORD GLE;
4210 DWORD altGLE;
4211 } cssd[] =
4213 { "D:(A;;GA;;;WD)", 0xdeadbeef, FALSE, ERROR_UNKNOWN_REVISION },
4214 /* test ACE string type */
4215 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4216 { "D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4217 { "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
4218 /* test ACE string with spaces */
4219 { " D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4220 { "D: (D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4221 { "D:( D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4222 { "D:(D ;;GA;;;WD)", SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
4223 { "D:(D; ;GA;;;WD)", SDDL_REVISION_1, TRUE },
4224 { "D:(D;; GA;;;WD)", SDDL_REVISION_1, TRUE },
4225 { "D:(D;;GA ;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
4226 { "D:(D;;GA; ;;WD)", SDDL_REVISION_1, TRUE },
4227 { "D:(D;;GA;; ;WD)", SDDL_REVISION_1, TRUE },
4228 { "D:(D;;GA;;; WD)", SDDL_REVISION_1, TRUE },
4229 { "D:(D;;GA;;;WD )", SDDL_REVISION_1, TRUE },
4230 /* test ACE string access rights */
4231 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4232 { "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, TRUE },
4233 { "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, TRUE },
4234 { "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, TRUE },
4235 { "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, TRUE },
4236 { "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, TRUE },
4237 { "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
4238 { "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
4239 /* test ACE string access right error case */
4240 { "D:(A;;ROB;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
4241 /* test behaviour with empty strings */
4242 { "", SDDL_REVISION_1, TRUE },
4243 /* test ACE string SID */
4244 { "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, TRUE },
4245 { "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
4248 for (i = 0; i < ARRAY_SIZE(cssd); i++)
4250 DWORD GLE;
4252 SetLastError(0xdeadbeef);
4253 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
4254 cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
4255 GLE = GetLastError();
4256 ok(ret == cssd[i].ret, "(%02u) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
4257 if (!cssd[i].ret)
4258 ok(GLE == cssd[i].GLE ||
4259 (cssd[i].altGLE && GLE == cssd[i].altGLE),
4260 "(%02u) Unexpected last error %d\n", i, GLE);
4261 if (ret)
4262 LocalFree(pSD);
4265 /* test behaviour with NULL parameters */
4266 SetLastError(0xdeadbeef);
4267 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
4268 NULL, 0xdeadbeef, &pSD, NULL);
4269 todo_wine
4270 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4271 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4272 GetLastError());
4274 SetLastError(0xdeadbeef);
4275 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
4276 NULL, 0xdeadbeef, &pSD, NULL);
4277 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4278 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4279 GetLastError());
4281 SetLastError(0xdeadbeef);
4282 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
4283 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
4284 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4285 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4286 GetLastError());
4288 SetLastError(0xdeadbeef);
4289 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
4290 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
4291 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4292 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4293 GetLastError());
4295 /* test behaviour with empty strings */
4296 SetLastError(0xdeadbeef);
4297 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
4298 Blank, SDDL_REVISION_1, &pSD, NULL);
4299 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
4300 LocalFree(pSD);
4302 SetLastError(0xdeadbeef);
4303 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
4304 "D:P(A;;GRGW;;;BA)(A;;GRGW;;;S-1-5-21-0-0-0-1000)S:(ML;;NWNR;;;S-1-16-12288)", SDDL_REVISION_1, &pSD, NULL);
4305 ok(ret || broken(!ret && GetLastError() == ERROR_INVALID_DATATYPE) /* win2k */,
4306 "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %u\n", GetLastError());
4307 if (ret) LocalFree(pSD);
4309 /* empty DACL */
4310 size = 0;
4311 SetLastError(0xdeadbeef);
4312 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA("D:", SDDL_REVISION_1, &pSD, &size);
4313 ok(ret, "unexpected error %u\n", GetLastError());
4314 ok(size == sizeof(SECURITY_DESCRIPTOR_RELATIVE) + sizeof(ACL), "got %u\n", size);
4315 acl = (ACL *)((char *)pSD + sizeof(SECURITY_DESCRIPTOR_RELATIVE));
4316 ok(acl->AclRevision == ACL_REVISION, "got %u\n", acl->AclRevision);
4317 ok(!acl->Sbz1, "got %u\n", acl->Sbz1);
4318 ok(acl->AclSize == sizeof(*acl), "got %u\n", acl->AclSize);
4319 ok(!acl->AceCount, "got %u\n", acl->AceCount);
4320 ok(!acl->Sbz2, "got %u\n", acl->Sbz2);
4321 LocalFree(pSD);
4323 /* empty SACL */
4324 size = 0;
4325 SetLastError(0xdeadbeef);
4326 ret = ConvertStringSecurityDescriptorToSecurityDescriptorA("S:", SDDL_REVISION_1, &pSD, &size);
4327 ok(ret, "unexpected error %u\n", GetLastError());
4328 ok(size == sizeof(SECURITY_DESCRIPTOR_RELATIVE) + sizeof(ACL), "got %u\n", size);
4329 acl = (ACL *)((char *)pSD + sizeof(SECURITY_DESCRIPTOR_RELATIVE));
4330 ok(!acl->Sbz1, "got %u\n", acl->Sbz1);
4331 ok(acl->AclSize == sizeof(*acl), "got %u\n", acl->AclSize);
4332 ok(!acl->AceCount, "got %u\n", acl->AceCount);
4333 ok(!acl->Sbz2, "got %u\n", acl->Sbz2);
4334 LocalFree(pSD);
4337 static void test_ConvertSecurityDescriptorToString(void)
4339 SECURITY_DESCRIPTOR desc;
4340 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
4341 LPSTR string;
4342 DWORD size;
4343 PSID psid, psid2;
4344 PACL pacl;
4345 char sid_buf[256];
4346 char acl_buf[8192];
4347 ULONG len;
4349 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
4351 win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
4352 return;
4355 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
4356 * don't replicate this feature so we only test len >= strlen+1. */
4357 #define CHECK_RESULT_AND_FREE(exp_str) \
4358 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
4359 ok(len >= (strlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlenA(exp_str) + 1, len); \
4360 LocalFree(string);
4362 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
4363 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); \
4364 ok(len >= (strlen(exp_str1) + 1) || len >= (strlen(exp_str2) + 1), "Length mismatch (expected %d or %d, got %d)\n", lstrlenA(exp_str1) + 1, lstrlenA(exp_str2) + 1, len); \
4365 LocalFree(string);
4367 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
4368 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4369 CHECK_RESULT_AND_FREE("");
4371 size = 4096;
4372 CreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
4373 SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
4374 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4375 CHECK_RESULT_AND_FREE("O:S-1-2-0");
4377 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
4378 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4379 CHECK_RESULT_AND_FREE("O:S-1-2-0");
4381 size = sizeof(sid_buf);
4382 CreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
4383 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
4384 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4385 CHECK_RESULT_AND_FREE("O:SY");
4387 ConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
4388 SetSecurityDescriptorGroup(&desc, psid, TRUE);
4389 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4390 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
4392 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
4393 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
4395 pacl = (PACL)acl_buf;
4396 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
4397 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
4398 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4399 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
4401 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
4402 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4403 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
4405 ConvertStringSidToSidA("S-1-5-6", &psid2);
4406 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
4407 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4408 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
4410 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
4411 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4412 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
4414 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
4415 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4416 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)");
4419 pacl = (PACL)acl_buf;
4420 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
4421 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
4422 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4423 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
4425 /* fails in win2k */
4426 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
4427 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
4428 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
4430 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
4431 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
4434 /* fails in win2k */
4435 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
4436 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
4438 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
4439 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
4442 LocalFree(psid2);
4443 LocalFree(psid);
4446 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
4448 SECURITY_DESCRIPTOR_CONTROL ref;
4449 SECURITY_DESCRIPTOR_CONTROL test;
4451 SECURITY_DESCRIPTOR_CONTROL const mutable
4452 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
4453 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
4454 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
4455 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
4457 SECURITY_DESCRIPTOR_CONTROL const immutable
4458 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
4459 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
4460 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
4461 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
4464 int bit;
4465 DWORD dwRevision;
4466 LPCSTR fmt = "Expected error %s, got %u\n";
4468 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
4470 /* The mutable bits are mutable regardless of the truth of
4471 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
4473 /* Check call barfs if any bit-of-interest is immutable */
4474 for (bit = 0; bit < 16; ++bit)
4476 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
4477 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
4479 SECURITY_DESCRIPTOR_CONTROL ctrl;
4481 DWORD dwExpect = (bitOfInterest & immutable)
4482 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
4483 LPCSTR strExpect = (bitOfInterest & immutable)
4484 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
4486 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
4487 setOrClear ^= bitOfInterest;
4488 SetLastError (0xbebecaca);
4489 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
4490 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4491 GetSecurityDescriptorControl(sec, &test, &dwRevision);
4492 expect_eq(test, ctrl, int, "%x");
4494 setOrClear ^= bitOfInterest;
4495 SetLastError (0xbebecaca);
4496 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
4497 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4498 GetSecurityDescriptorControl (sec, &test, &dwRevision);
4499 expect_eq(test, ref, int, "%x");
4502 /* Check call barfs if any bit-to-set is immutable
4503 even when not a bit-of-interest */
4504 for (bit = 0; bit < 16; ++bit)
4506 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
4507 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
4509 SECURITY_DESCRIPTOR_CONTROL ctrl;
4511 DWORD dwExpect = ((1 << bit) & immutable)
4512 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
4513 LPCSTR strExpect = ((1 << bit) & immutable)
4514 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
4516 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
4517 setOrClear ^= bitsOfInterest;
4518 SetLastError (0xbebecaca);
4519 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
4520 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4521 GetSecurityDescriptorControl(sec, &test, &dwRevision);
4522 expect_eq(test, ctrl, int, "%x");
4524 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
4525 setOrClear ^= bitsOfInterest;
4526 SetLastError (0xbebecaca);
4527 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
4528 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4529 GetSecurityDescriptorControl(sec, &test, &dwRevision);
4530 expect_eq(test, ctrl, int, "%x");
4534 static void test_PrivateObjectSecurity(void)
4536 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
4537 SECURITY_DESCRIPTOR_CONTROL ctrl;
4538 PSECURITY_DESCRIPTOR sec;
4539 DWORD dwDescSize;
4540 DWORD dwRevision;
4541 DWORD retSize;
4542 LPSTR string;
4543 ULONG len;
4544 PSECURITY_DESCRIPTOR buf;
4545 BOOL ret;
4547 ok(ConvertStringSecurityDescriptorToSecurityDescriptorA(
4548 "O:SY"
4549 "G:S-1-5-21-93476-23408-4576"
4550 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
4551 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4552 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
4553 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
4555 test_SetSecurityDescriptorControl(sec);
4557 LocalFree(sec);
4559 ok(ConvertStringSecurityDescriptorToSecurityDescriptorA(
4560 "O:SY"
4561 "G:S-1-5-21-93476-23408-4576",
4562 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
4564 test_SetSecurityDescriptorControl(sec);
4566 LocalFree(sec);
4568 ok(ConvertStringSecurityDescriptorToSecurityDescriptorA(
4569 "O:SY"
4570 "G:S-1-5-21-93476-23408-4576"
4571 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4572 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
4573 buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
4574 pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
4575 GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
4576 expect_eq(ctrl, 0x9014, int, "%x");
4578 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
4579 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
4580 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
4581 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4582 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
4583 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
4584 expect_eq(ctrl, 0x8000, int, "%x");
4586 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
4587 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
4588 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
4589 ret = pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len);
4590 ok(ret, "Conversion failed err=%u\n", GetLastError());
4591 CHECK_ONE_OF_AND_FREE("G:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)",
4592 "G:S-1-5-21-93476-23408-4576D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"); /* Win7 */
4593 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
4594 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8004, int, "%x");
4596 ret = GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize);
4597 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
4598 ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
4599 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4600 CHECK_ONE_OF_AND_FREE("O:SY"
4601 "G:S-1-5-21-93476-23408-4576"
4602 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4603 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
4604 "O:SY"
4605 "G:S-1-5-21-93476-23408-4576"
4606 "D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4607 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)"); /* Win7 */
4608 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
4609 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8014, int, "%x");
4611 SetLastError(0xdeadbeef);
4612 ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
4613 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
4615 LocalFree(sec);
4616 HeapFree(GetProcessHeap(), 0, buf);
4618 #undef CHECK_RESULT_AND_FREE
4619 #undef CHECK_ONE_OF_AND_FREE
4621 static void test_acls(void)
4623 char buffer[256];
4624 PACL pAcl = (PACL)buffer;
4625 BOOL ret;
4627 SetLastError(0xdeadbeef);
4628 ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
4629 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4631 win_skip("InitializeAcl is not implemented\n");
4632 return;
4635 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
4637 SetLastError(0xdeadbeef);
4638 ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
4639 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
4641 SetLastError(0xdeadbeef);
4642 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
4643 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
4645 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
4646 ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
4648 ret = IsValidAcl(pAcl);
4649 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
4651 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
4652 ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
4654 ret = IsValidAcl(pAcl);
4655 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
4657 SetLastError(0xdeadbeef);
4658 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
4659 if (GetLastError() != ERROR_INVALID_PARAMETER)
4661 ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
4663 ret = IsValidAcl(pAcl);
4664 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
4666 else
4667 win_skip("ACL_REVISION4 is not implemented on NT4\n");
4669 SetLastError(0xdeadbeef);
4670 ret = InitializeAcl(pAcl, sizeof(buffer), -1);
4671 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
4674 static void test_GetSecurityInfo(void)
4676 char domain_users_ptr[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
4677 char b[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
4678 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], dacl[100];
4679 PSID domain_users_sid = (PSID) domain_users_ptr, domain_sid;
4680 SID_IDENTIFIER_AUTHORITY sia = { SECURITY_NT_AUTHORITY };
4681 int domain_users_ace_id = -1, admins_ace_id = -1, i;
4682 DWORD sid_size = sizeof(admin_ptr), l = sizeof(b);
4683 PSID admin_sid = (PSID) admin_ptr, user_sid;
4684 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
4685 BOOL owner_defaulted, group_defaulted;
4686 BOOL dacl_defaulted, dacl_present;
4687 ACL_SIZE_INFORMATION acl_size;
4688 PSECURITY_DESCRIPTOR pSD;
4689 ACCESS_ALLOWED_ACE *ace;
4690 HANDLE token, obj;
4691 PSID owner, group;
4692 BOOL bret = TRUE;
4693 PACL pDacl;
4694 BYTE flags;
4695 DWORD ret;
4697 if (!pSetSecurityInfo)
4699 win_skip("[Get|Set]SecurityInfo is not available\n");
4700 return;
4703 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
4705 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
4706 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
4708 if (!bret)
4710 win_skip("Failed to get current user token\n");
4711 return;
4713 bret = GetTokenInformation(token, TokenUser, b, l, &l);
4714 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
4715 CloseHandle( token );
4716 user_sid = ((TOKEN_USER *)b)->User.Sid;
4718 /* Create something. Files have lots of associated security info. */
4719 obj = CreateFileA(myARGV[0], GENERIC_READ|WRITE_DAC, FILE_SHARE_READ, NULL,
4720 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
4721 if (obj == INVALID_HANDLE_VALUE)
4723 skip("Couldn't create an object for GetSecurityInfo test\n");
4724 return;
4727 ret = GetSecurityInfo(obj, SE_FILE_OBJECT,
4728 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4729 &owner, &group, &pDacl, NULL, &pSD);
4730 if (ret == ERROR_CALL_NOT_IMPLEMENTED)
4732 win_skip("GetSecurityInfo is not implemented\n");
4733 CloseHandle(obj);
4734 return;
4736 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
4737 ok(pSD != NULL, "GetSecurityInfo\n");
4738 ok(owner != NULL, "GetSecurityInfo\n");
4739 ok(group != NULL, "GetSecurityInfo\n");
4740 if (pDacl != NULL)
4741 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
4742 else
4743 win_skip("No ACL information returned\n");
4745 LocalFree(pSD);
4747 /* If we don't ask for the security descriptor, Windows will still give us
4748 the other stuff, leaving us no way to free it. */
4749 ret = GetSecurityInfo(obj, SE_FILE_OBJECT,
4750 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4751 &owner, &group, &pDacl, NULL, NULL);
4752 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
4753 ok(owner != NULL, "GetSecurityInfo\n");
4754 ok(group != NULL, "GetSecurityInfo\n");
4755 if (pDacl != NULL)
4756 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
4757 else
4758 win_skip("No ACL information returned\n");
4760 /* Create security descriptor information and test that it comes back the same */
4761 pSD = &sd;
4762 pDacl = (PACL)&dacl;
4763 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
4764 CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
4765 bret = InitializeAcl(pDacl, sizeof(dacl), ACL_REVISION);
4766 ok(bret, "Failed to initialize ACL.\n");
4767 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4768 ok(bret, "Failed to add Current User to ACL.\n");
4769 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
4770 ok(bret, "Failed to add Administrator Group to ACL.\n");
4771 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4772 ok(bret, "Failed to add ACL to security descriptor.\n");
4773 ret = pSetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4774 NULL, NULL, pDacl, NULL);
4775 ok(ret == ERROR_SUCCESS, "SetSecurityInfo returned %d\n", ret);
4776 ret = GetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4777 NULL, NULL, &pDacl, NULL, &pSD);
4778 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
4779 ok(pDacl && IsValidAcl(pDacl), "GetSecurityInfo returned invalid DACL.\n");
4780 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4781 ok(bret, "GetAclInformation failed\n");
4782 if (acl_size.AceCount > 0)
4784 bret = GetAce(pDacl, 0, (VOID **)&ace);
4785 ok(bret, "Failed to get Current User ACE.\n");
4786 bret = EqualSid(&ace->SidStart, user_sid);
4787 todo_wine ok(bret, "Current User ACE (%s) != Current User SID (%s).\n",
4788 debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
4789 ok(((ACE_HEADER *)ace)->AceFlags == 0,
4790 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
4791 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
4792 ace->Mask);
4794 if (acl_size.AceCount > 1)
4796 bret = GetAce(pDacl, 1, (VOID **)&ace);
4797 ok(bret, "Failed to get Administators Group ACE.\n");
4798 bret = EqualSid(&ace->SidStart, admin_sid);
4799 todo_wine ok(bret, "Administators Group ACE (%s) != Administators Group SID (%s).\n", debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
4800 ok(((ACE_HEADER *)ace)->AceFlags == 0,
4801 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
4802 ok(ace->Mask == 0x1f01ff, "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n",
4803 ace->Mask);
4805 LocalFree(pSD);
4806 CloseHandle(obj);
4808 /* Obtain the "domain users" SID from the user SID */
4809 if (!AllocateAndInitializeSid(&sia, 4, *GetSidSubAuthority(user_sid, 0),
4810 *GetSidSubAuthority(user_sid, 1),
4811 *GetSidSubAuthority(user_sid, 2),
4812 *GetSidSubAuthority(user_sid, 3), 0, 0, 0, 0, &domain_sid))
4814 win_skip("Failed to get current domain SID\n");
4815 return;
4817 sid_size = sizeof(domain_users_ptr);
4818 CreateWellKnownSid(WinAccountDomainUsersSid, domain_sid, domain_users_sid, &sid_size);
4819 FreeSid(domain_sid);
4821 /* Test querying the ownership of a process */
4822 ret = GetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT,
4823 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
4824 NULL, NULL, NULL, NULL, &pSD);
4825 ok(!ret, "GetNamedSecurityInfo failed with error %d\n", ret);
4827 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
4828 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
4829 ok(owner != NULL, "owner should not be NULL\n");
4830 ok(EqualSid(owner, admin_sid) || EqualSid(owner, user_sid),
4831 "Process owner SID != Administrators SID.\n");
4833 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
4834 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
4835 ok(group != NULL, "group should not be NULL\n");
4836 ok(EqualSid(group, domain_users_sid), "Process group SID != Domain Users SID.\n");
4837 LocalFree(pSD);
4839 /* Test querying the DACL of a process */
4840 ret = GetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
4841 NULL, NULL, NULL, NULL, &pSD);
4842 ok(!ret, "GetSecurityInfo failed with error %d\n", ret);
4844 bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
4845 ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
4846 ok(dacl_present, "DACL should be present\n");
4847 ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
4848 bret = GetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4849 ok(bret, "GetAclInformation failed\n");
4850 ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
4851 for (i=0; i<acl_size.AceCount; i++)
4853 bret = GetAce(pDacl, i, (VOID **)&ace);
4854 ok(bret, "Failed to get ACE %d.\n", i);
4855 bret = EqualSid(&ace->SidStart, domain_users_sid);
4856 if (bret) domain_users_ace_id = i;
4857 bret = EqualSid(&ace->SidStart, admin_sid);
4858 if (bret) admins_ace_id = i;
4860 ok(domain_users_ace_id != -1 || broken(domain_users_ace_id == -1) /* win2k */,
4861 "Domain Users ACE not found.\n");
4862 if (domain_users_ace_id != -1)
4864 bret = GetAce(pDacl, domain_users_ace_id, (VOID **)&ace);
4865 ok(bret, "Failed to get Domain Users ACE.\n");
4866 flags = ((ACE_HEADER *)ace)->AceFlags;
4867 ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE),
4868 "Domain Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
4869 INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
4870 ok(ace->Mask == GENERIC_READ, "Domain Users ACE has unexpected mask (0x%x != 0x%x)\n",
4871 ace->Mask, GENERIC_READ);
4873 ok(admins_ace_id != -1 || broken(admins_ace_id == -1) /* xp */,
4874 "Builtin Admins ACE not found.\n");
4875 if (admins_ace_id != -1)
4877 bret = GetAce(pDacl, admins_ace_id, (VOID **)&ace);
4878 ok(bret, "Failed to get Builtin Admins ACE.\n");
4879 flags = ((ACE_HEADER *)ace)->AceFlags;
4880 ok(flags == 0x0, "Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
4881 ok(ace->Mask == PROCESS_ALL_ACCESS || broken(ace->Mask == 0x1f0fff) /* win2k */,
4882 "Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, PROCESS_ALL_ACCESS);
4884 LocalFree(pSD);
4887 static void test_GetSidSubAuthority(void)
4889 PSID psid = NULL;
4891 /* Note: on windows passing in an invalid index like -1, lets GetSidSubAuthority return 0x05000000 but
4892 still GetLastError returns ERROR_SUCCESS then. We don't test these unlikely cornercases here for now */
4893 ok(ConvertStringSidToSidA("S-1-5-21-93476-23408-4576",&psid),"ConvertStringSidToSidA failed\n");
4894 ok(IsValidSid(psid),"Sid is not valid\n");
4895 SetLastError(0xbebecaca);
4896 ok(*GetSidSubAuthorityCount(psid) == 4,"GetSidSubAuthorityCount gave %d expected 4\n", *GetSidSubAuthorityCount(psid));
4897 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
4898 SetLastError(0xbebecaca);
4899 ok(*GetSidSubAuthority(psid,0) == 21,"GetSidSubAuthority gave %d expected 21\n", *GetSidSubAuthority(psid,0));
4900 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
4901 SetLastError(0xbebecaca);
4902 ok(*GetSidSubAuthority(psid,1) == 93476,"GetSidSubAuthority gave %d expected 93476\n", *GetSidSubAuthority(psid,1));
4903 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
4904 SetLastError(0xbebecaca);
4905 ok(GetSidSubAuthority(psid,4) != NULL,"Expected out of bounds GetSidSubAuthority to return a non-NULL pointer\n");
4906 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
4907 LocalFree(psid);
4910 static void test_CheckTokenMembership(void)
4912 PTOKEN_GROUPS token_groups;
4913 DWORD size;
4914 HANDLE process_token, token;
4915 BOOL is_member;
4916 BOOL ret;
4917 DWORD i;
4919 if (!pCheckTokenMembership)
4921 win_skip("CheckTokenMembership is not available\n");
4922 return;
4924 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
4925 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
4927 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
4928 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
4930 /* groups */
4931 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
4932 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
4933 "GetTokenInformation(TokenGroups) %s with error %d\n",
4934 ret ? "succeeded" : "failed", GetLastError());
4935 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
4936 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
4937 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
4939 for (i = 0; i < token_groups->GroupCount; i++)
4941 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
4942 break;
4945 if (i == token_groups->GroupCount)
4947 HeapFree(GetProcessHeap(), 0, token_groups);
4948 CloseHandle(token);
4949 skip("user not a member of any group\n");
4950 return;
4953 is_member = FALSE;
4954 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
4955 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
4956 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
4958 is_member = FALSE;
4959 ret = pCheckTokenMembership(NULL, token_groups->Groups[i].Sid, &is_member);
4960 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
4961 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
4963 is_member = TRUE;
4964 SetLastError(0xdeadbeef);
4965 ret = pCheckTokenMembership(process_token, token_groups->Groups[i].Sid, &is_member);
4966 ok(!ret && GetLastError() == ERROR_NO_IMPERSONATION_TOKEN,
4967 "CheckTokenMembership with process token %s with error %d\n",
4968 ret ? "succeeded" : "failed", GetLastError());
4969 ok(!is_member, "CheckTokenMembership should have cleared is_member\n");
4971 HeapFree(GetProcessHeap(), 0, token_groups);
4972 CloseHandle(token);
4973 CloseHandle(process_token);
4976 static void test_EqualSid(void)
4978 PSID sid1, sid2;
4979 BOOL ret;
4980 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
4981 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
4983 SetLastError(0xdeadbeef);
4984 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
4985 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid1);
4986 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4988 win_skip("AllocateAndInitializeSid is not implemented\n");
4989 return;
4991 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
4992 ok(GetLastError() == 0xdeadbeef,
4993 "AllocateAndInitializeSid shouldn't have set last error to %d\n",
4994 GetLastError());
4996 ret = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
4997 0, 0, 0, 0, 0, 0, 0, &sid2);
4998 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
5000 SetLastError(0xdeadbeef);
5001 ret = EqualSid(sid1, sid2);
5002 ok(!ret, "World and domain admins sids shouldn't have been equal\n");
5003 ok(GetLastError() == ERROR_SUCCESS ||
5004 broken(GetLastError() == 0xdeadbeef), /* NT4 */
5005 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
5006 GetLastError());
5008 SetLastError(0xdeadbeef);
5009 sid2 = FreeSid(sid2);
5010 ok(!sid2, "FreeSid should have returned NULL instead of %p\n", sid2);
5011 ok(GetLastError() == 0xdeadbeef,
5012 "FreeSid shouldn't have set last error to %d\n",
5013 GetLastError());
5015 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
5016 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid2);
5017 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
5019 SetLastError(0xdeadbeef);
5020 ret = EqualSid(sid1, sid2);
5021 ok(ret, "Same sids should have been equal %s != %s\n",
5022 debugstr_sid(sid1), debugstr_sid(sid2));
5023 ok(GetLastError() == ERROR_SUCCESS ||
5024 broken(GetLastError() == 0xdeadbeef), /* NT4 */
5025 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
5026 GetLastError());
5028 ((SID *)sid2)->Revision = 2;
5029 SetLastError(0xdeadbeef);
5030 ret = EqualSid(sid1, sid2);
5031 ok(!ret, "EqualSid with invalid sid should have returned FALSE\n");
5032 ok(GetLastError() == ERROR_SUCCESS ||
5033 broken(GetLastError() == 0xdeadbeef), /* NT4 */
5034 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
5035 GetLastError());
5036 ((SID *)sid2)->Revision = SID_REVISION;
5038 FreeSid(sid1);
5039 FreeSid(sid2);
5042 static void test_GetUserNameA(void)
5044 char buffer[UNLEN + 1], filler[UNLEN + 1];
5045 DWORD required_len, buffer_len;
5046 BOOL ret;
5048 /* Test crashes on Windows. */
5049 if (0)
5051 SetLastError(0xdeadbeef);
5052 GetUserNameA(NULL, NULL);
5055 SetLastError(0xdeadbeef);
5056 required_len = 0;
5057 ret = GetUserNameA(NULL, &required_len);
5058 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5059 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5060 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5062 SetLastError(0xdeadbeef);
5063 required_len = 1;
5064 ret = GetUserNameA(NULL, &required_len);
5065 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5066 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
5067 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5069 /* Tests crashes on Windows. */
5070 if (0)
5072 SetLastError(0xdeadbeef);
5073 required_len = UNLEN + 1;
5074 GetUserNameA(NULL, &required_len);
5076 SetLastError(0xdeadbeef);
5077 GetUserNameA(buffer, NULL);
5080 memset(filler, 'x', sizeof(filler));
5082 /* Note that GetUserNameA on XP and newer outputs the number of bytes
5083 * required for a Unicode string, which affects a test in the next block. */
5084 SetLastError(0xdeadbeef);
5085 memcpy(buffer, filler, sizeof(filler));
5086 required_len = 0;
5087 ret = GetUserNameA(buffer, &required_len);
5088 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5089 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
5090 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5091 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5093 SetLastError(0xdeadbeef);
5094 memcpy(buffer, filler, sizeof(filler));
5095 buffer_len = required_len;
5096 ret = GetUserNameA(buffer, &buffer_len);
5097 ok(ret == TRUE, "GetUserNameA returned %d, last error %u\n", ret, GetLastError());
5098 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
5099 ok(buffer_len == required_len ||
5100 broken(buffer_len == required_len / sizeof(WCHAR)), /* XP+ */
5101 "Outputted buffer length was %u\n", buffer_len);
5103 /* Use the reported buffer size from the last GetUserNameA call and pass
5104 * a length that is one less than the required value. */
5105 SetLastError(0xdeadbeef);
5106 memcpy(buffer, filler, sizeof(filler));
5107 buffer_len--;
5108 ret = GetUserNameA(buffer, &buffer_len);
5109 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5110 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was untouched\n");
5111 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
5112 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5115 static void test_GetUserNameW(void)
5117 WCHAR buffer[UNLEN + 1], filler[UNLEN + 1];
5118 DWORD required_len, buffer_len;
5119 BOOL ret;
5121 /* Test crashes on Windows. */
5122 if (0)
5124 SetLastError(0xdeadbeef);
5125 GetUserNameW(NULL, NULL);
5128 SetLastError(0xdeadbeef);
5129 required_len = 0;
5130 ret = GetUserNameW(NULL, &required_len);
5131 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5132 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5133 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5135 SetLastError(0xdeadbeef);
5136 required_len = 1;
5137 ret = GetUserNameW(NULL, &required_len);
5138 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5139 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
5140 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5142 /* Tests crash on Windows. */
5143 if (0)
5145 SetLastError(0xdeadbeef);
5146 required_len = UNLEN + 1;
5147 GetUserNameW(NULL, &required_len);
5149 SetLastError(0xdeadbeef);
5150 GetUserNameW(buffer, NULL);
5153 memset(filler, 'x', sizeof(filler));
5155 SetLastError(0xdeadbeef);
5156 memcpy(buffer, filler, sizeof(filler));
5157 required_len = 0;
5158 ret = GetUserNameW(buffer, &required_len);
5159 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5160 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
5161 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5162 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5164 SetLastError(0xdeadbeef);
5165 memcpy(buffer, filler, sizeof(filler));
5166 buffer_len = required_len;
5167 ret = GetUserNameW(buffer, &buffer_len);
5168 ok(ret == TRUE, "GetUserNameW returned %d, last error %u\n", ret, GetLastError());
5169 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
5170 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
5172 /* GetUserNameW on XP and newer writes a truncated portion of the username string to the buffer. */
5173 SetLastError(0xdeadbeef);
5174 memcpy(buffer, filler, sizeof(filler));
5175 buffer_len--;
5176 ret = GetUserNameW(buffer, &buffer_len);
5177 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5178 ok(!memcmp(buffer, filler, sizeof(filler)) ||
5179 broken(memcmp(buffer, filler, sizeof(filler)) != 0), /* XP+ */
5180 "Output buffer was altered\n");
5181 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
5182 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5185 static void test_CreateRestrictedToken(void)
5187 HANDLE process_token, token, r_token;
5188 PTOKEN_GROUPS token_groups, groups2;
5189 SID_AND_ATTRIBUTES sattr;
5190 SECURITY_IMPERSONATION_LEVEL level;
5191 TOKEN_TYPE type;
5192 BOOL is_member;
5193 DWORD size;
5194 BOOL ret;
5195 DWORD i, j;
5197 if (!pCreateRestrictedToken)
5199 win_skip("CreateRestrictedToken is not available\n");
5200 return;
5203 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
5204 ok(ret, "got error %d\n", GetLastError());
5206 ret = DuplicateTokenEx(process_token, TOKEN_DUPLICATE|TOKEN_ADJUST_GROUPS|TOKEN_QUERY,
5207 NULL, SecurityImpersonation, TokenImpersonation, &token);
5208 ok(ret, "got error %d\n", GetLastError());
5210 /* groups */
5211 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
5212 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
5213 "got %d with error %d\n", ret, GetLastError());
5214 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
5215 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
5216 ok(ret, "got error %d\n", GetLastError());
5218 for (i = 0; i < token_groups->GroupCount; i++)
5220 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
5221 break;
5224 if (i == token_groups->GroupCount)
5226 HeapFree(GetProcessHeap(), 0, token_groups);
5227 CloseHandle(token);
5228 skip("User not a member of any group\n");
5229 return;
5232 is_member = FALSE;
5233 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
5234 ok(ret, "got error %d\n", GetLastError());
5235 ok(is_member, "not a member\n");
5237 /* disable a SID in new token */
5238 sattr.Sid = token_groups->Groups[i].Sid;
5239 sattr.Attributes = 0;
5240 r_token = NULL;
5241 ret = pCreateRestrictedToken(token, 0, 1, &sattr, 0, NULL, 0, NULL, &r_token);
5242 ok(ret, "got error %d\n", GetLastError());
5244 if (ret)
5246 /* check if a SID is enabled */
5247 is_member = TRUE;
5248 ret = pCheckTokenMembership(r_token, token_groups->Groups[i].Sid, &is_member);
5249 ok(ret, "got error %d\n", GetLastError());
5250 todo_wine ok(!is_member, "not a member\n");
5252 ret = GetTokenInformation(r_token, TokenGroups, NULL, 0, &size);
5253 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d with error %d\n",
5254 ret, GetLastError());
5255 groups2 = HeapAlloc(GetProcessHeap(), 0, size);
5256 ret = GetTokenInformation(r_token, TokenGroups, groups2, size, &size);
5257 ok(ret, "got error %d\n", GetLastError());
5259 for (j = 0; j < groups2->GroupCount; j++)
5261 if (EqualSid(groups2->Groups[j].Sid, token_groups->Groups[i].Sid))
5262 break;
5265 todo_wine ok(groups2->Groups[j].Attributes & SE_GROUP_USE_FOR_DENY_ONLY,
5266 "got wrong attributes\n");
5267 todo_wine ok((groups2->Groups[j].Attributes & SE_GROUP_ENABLED) == 0,
5268 "got wrong attributes\n");
5270 HeapFree(GetProcessHeap(), 0, groups2);
5272 size = sizeof(type);
5273 ret = GetTokenInformation(r_token, TokenType, &type, size, &size);
5274 ok(ret, "got error %d\n", GetLastError());
5275 ok(type == TokenImpersonation, "got type %u\n", type);
5277 size = sizeof(level);
5278 ret = GetTokenInformation(r_token, TokenImpersonationLevel, &level, size, &size);
5279 ok(ret, "got error %d\n", GetLastError());
5280 ok(level == SecurityImpersonation, "got level %u\n", type);
5283 HeapFree(GetProcessHeap(), 0, token_groups);
5284 CloseHandle(r_token);
5285 CloseHandle(token);
5286 CloseHandle(process_token);
5289 static void validate_default_security_descriptor(SECURITY_DESCRIPTOR *sd)
5291 BOOL ret, present, defaulted;
5292 ACL *acl;
5293 void *sid;
5295 ret = IsValidSecurityDescriptor(sd);
5296 ok(ret, "security descriptor is not valid\n");
5298 present = -1;
5299 defaulted = -1;
5300 acl = (void *)0xdeadbeef;
5301 SetLastError(0xdeadbeef);
5302 ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
5303 ok(ret, "GetSecurityDescriptorDacl error %d\n", GetLastError());
5304 todo_wine
5305 ok(present == 1, "acl is not present\n");
5306 todo_wine
5307 ok(acl != (void *)0xdeadbeef && acl != NULL, "acl pointer is not set\n");
5308 ok(defaulted == 0, "defaulted is set to TRUE\n");
5310 defaulted = -1;
5311 sid = (void *)0xdeadbeef;
5312 SetLastError(0xdeadbeef);
5313 ret = GetSecurityDescriptorOwner(sd, &sid, &defaulted);
5314 ok(ret, "GetSecurityDescriptorOwner error %d\n", GetLastError());
5315 todo_wine
5316 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
5317 ok(defaulted == 0, "defaulted is set to TRUE\n");
5319 defaulted = -1;
5320 sid = (void *)0xdeadbeef;
5321 SetLastError(0xdeadbeef);
5322 ret = GetSecurityDescriptorGroup(sd, &sid, &defaulted);
5323 ok(ret, "GetSecurityDescriptorGroup error %d\n", GetLastError());
5324 todo_wine
5325 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
5326 ok(defaulted == 0, "defaulted is set to TRUE\n");
5329 static void test_default_handle_security(HANDLE token, HANDLE handle, GENERIC_MAPPING *mapping)
5331 DWORD ret, granted, priv_set_len;
5332 BOOL status;
5333 PRIVILEGE_SET priv_set;
5334 SECURITY_DESCRIPTOR *sd;
5336 sd = test_get_security_descriptor(handle, __LINE__);
5337 validate_default_security_descriptor(sd);
5339 priv_set_len = sizeof(priv_set);
5340 granted = 0xdeadbeef;
5341 status = 0xdeadbeef;
5342 SetLastError(0xdeadbeef);
5343 ret = AccessCheck(sd, token, MAXIMUM_ALLOWED, mapping, &priv_set, &priv_set_len, &granted, &status);
5344 todo_wine {
5345 ok(ret, "AccessCheck error %d\n", GetLastError());
5346 ok(status == 1, "expected 1, got %d\n", status);
5347 ok(granted == mapping->GenericAll, "expected all access %#x, got %#x\n", mapping->GenericAll, granted);
5349 priv_set_len = sizeof(priv_set);
5350 granted = 0xdeadbeef;
5351 status = 0xdeadbeef;
5352 SetLastError(0xdeadbeef);
5353 ret = AccessCheck(sd, token, 0, mapping, &priv_set, &priv_set_len, &granted, &status);
5354 todo_wine {
5355 ok(ret, "AccessCheck error %d\n", GetLastError());
5356 ok(status == 0 || broken(status == 1) /* NT4 */, "expected 0, got %d\n", status);
5357 ok(granted == 0 || broken(granted == mapping->GenericRead) /* NT4 */, "expected 0, got %#x\n", granted);
5359 priv_set_len = sizeof(priv_set);
5360 granted = 0xdeadbeef;
5361 status = 0xdeadbeef;
5362 SetLastError(0xdeadbeef);
5363 ret = AccessCheck(sd, token, ACCESS_SYSTEM_SECURITY, mapping, &priv_set, &priv_set_len, &granted, &status);
5364 todo_wine {
5365 ok(ret, "AccessCheck error %d\n", GetLastError());
5366 ok(status == 0, "expected 0, got %d\n", status);
5367 ok(granted == 0, "expected 0, got %#x\n", granted);
5369 priv_set_len = sizeof(priv_set);
5370 granted = 0xdeadbeef;
5371 status = 0xdeadbeef;
5372 SetLastError(0xdeadbeef);
5373 ret = AccessCheck(sd, token, mapping->GenericRead, mapping, &priv_set, &priv_set_len, &granted, &status);
5374 todo_wine {
5375 ok(ret, "AccessCheck error %d\n", GetLastError());
5376 ok(status == 1, "expected 1, got %d\n", status);
5377 ok(granted == mapping->GenericRead, "expected read access %#x, got %#x\n", mapping->GenericRead, granted);
5379 priv_set_len = sizeof(priv_set);
5380 granted = 0xdeadbeef;
5381 status = 0xdeadbeef;
5382 SetLastError(0xdeadbeef);
5383 ret = AccessCheck(sd, token, mapping->GenericWrite, mapping, &priv_set, &priv_set_len, &granted, &status);
5384 todo_wine {
5385 ok(ret, "AccessCheck error %d\n", GetLastError());
5386 ok(status == 1, "expected 1, got %d\n", status);
5387 ok(granted == mapping->GenericWrite, "expected write access %#x, got %#x\n", mapping->GenericWrite, granted);
5389 priv_set_len = sizeof(priv_set);
5390 granted = 0xdeadbeef;
5391 status = 0xdeadbeef;
5392 SetLastError(0xdeadbeef);
5393 ret = AccessCheck(sd, token, mapping->GenericExecute, mapping, &priv_set, &priv_set_len, &granted, &status);
5394 todo_wine {
5395 ok(ret, "AccessCheck error %d\n", GetLastError());
5396 ok(status == 1, "expected 1, got %d\n", status);
5397 ok(granted == mapping->GenericExecute, "expected execute access %#x, got %#x\n", mapping->GenericExecute, granted);
5399 HeapFree(GetProcessHeap(), 0, sd);
5402 static ACCESS_MASK get_obj_access(HANDLE obj)
5404 OBJECT_BASIC_INFORMATION info;
5405 NTSTATUS status;
5407 if (!pNtQueryObject) return 0;
5409 status = pNtQueryObject(obj, ObjectBasicInformation, &info, sizeof(info), NULL);
5410 ok(!status, "NtQueryObject error %#x\n", status);
5412 return info.GrantedAccess;
5415 static void test_mutex_security(HANDLE token)
5417 DWORD ret, i, access;
5418 HANDLE mutex, dup;
5419 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE | SYNCHRONIZE,
5420 STANDARD_RIGHTS_WRITE | MUTEX_MODIFY_STATE | SYNCHRONIZE,
5421 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
5422 STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS };
5423 static const struct
5425 int generic, mapped;
5426 } map[] =
5428 { 0, 0 },
5429 { GENERIC_READ, STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE },
5430 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE },
5431 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5432 { GENERIC_ALL, STANDARD_RIGHTS_ALL | MUTANT_QUERY_STATE }
5435 SetLastError(0xdeadbeef);
5436 mutex = OpenMutexA(0, FALSE, "WineTestMutex");
5437 ok(!mutex, "mutex should not exist\n");
5438 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
5440 SetLastError(0xdeadbeef);
5441 mutex = CreateMutexA(NULL, FALSE, "WineTestMutex");
5442 ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
5444 access = get_obj_access(mutex);
5445 ok(access == MUTANT_ALL_ACCESS, "expected MUTANT_ALL_ACCESS, got %#x\n", access);
5447 for (i = 0; i < ARRAY_SIZE(map); i++)
5449 SetLastError( 0xdeadbeef );
5450 ret = DuplicateHandle(GetCurrentProcess(), mutex, GetCurrentProcess(), &dup,
5451 map[i].generic, FALSE, 0);
5452 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5454 access = get_obj_access(dup);
5455 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5457 CloseHandle(dup);
5459 SetLastError(0xdeadbeef);
5460 dup = OpenMutexA(0, FALSE, "WineTestMutex");
5461 todo_wine
5462 ok(!dup, "OpenMutex should fail\n");
5463 todo_wine
5464 ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError());
5467 test_default_handle_security(token, mutex, &mapping);
5469 CloseHandle (mutex);
5472 static void test_event_security(HANDLE token)
5474 DWORD ret, i, access;
5475 HANDLE event, dup;
5476 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | EVENT_QUERY_STATE | SYNCHRONIZE,
5477 STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE | SYNCHRONIZE,
5478 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
5479 STANDARD_RIGHTS_ALL | EVENT_ALL_ACCESS };
5480 static const struct
5482 int generic, mapped;
5483 } map[] =
5485 { 0, 0 },
5486 { GENERIC_READ, STANDARD_RIGHTS_READ | EVENT_QUERY_STATE },
5487 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE },
5488 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5489 { GENERIC_ALL, STANDARD_RIGHTS_ALL | EVENT_QUERY_STATE | EVENT_MODIFY_STATE }
5492 SetLastError(0xdeadbeef);
5493 event = OpenEventA(0, FALSE, "WineTestEvent");
5494 ok(!event, "event should not exist\n");
5495 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
5497 SetLastError(0xdeadbeef);
5498 event = CreateEventA(NULL, FALSE, FALSE, "WineTestEvent");
5499 ok(event != 0, "CreateEvent error %d\n", GetLastError());
5501 access = get_obj_access(event);
5502 ok(access == EVENT_ALL_ACCESS, "expected EVENT_ALL_ACCESS, got %#x\n", access);
5504 for (i = 0; i < ARRAY_SIZE(map); i++)
5506 SetLastError( 0xdeadbeef );
5507 ret = DuplicateHandle(GetCurrentProcess(), event, GetCurrentProcess(), &dup,
5508 map[i].generic, FALSE, 0);
5509 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5511 access = get_obj_access(dup);
5512 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5514 CloseHandle(dup);
5516 SetLastError(0xdeadbeef);
5517 dup = OpenEventA(0, FALSE, "WineTestEvent");
5518 todo_wine
5519 ok(!dup, "OpenEvent should fail\n");
5520 todo_wine
5521 ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError());
5524 test_default_handle_security(token, event, &mapping);
5526 CloseHandle(event);
5529 static void test_semaphore_security(HANDLE token)
5531 DWORD ret, i, access;
5532 HANDLE sem, dup;
5533 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | SEMAPHORE_QUERY_STATE,
5534 STANDARD_RIGHTS_WRITE | SEMAPHORE_MODIFY_STATE,
5535 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
5536 STANDARD_RIGHTS_ALL | SEMAPHORE_ALL_ACCESS };
5537 static const struct
5539 int generic, mapped;
5540 } map[] =
5542 { 0, 0 },
5543 { GENERIC_READ, STANDARD_RIGHTS_READ | SEMAPHORE_QUERY_STATE },
5544 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | SEMAPHORE_MODIFY_STATE },
5545 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5546 { GENERIC_ALL, STANDARD_RIGHTS_ALL | SEMAPHORE_QUERY_STATE | SEMAPHORE_MODIFY_STATE }
5549 SetLastError(0xdeadbeef);
5550 sem = OpenSemaphoreA(0, FALSE, "WineTestSemaphore");
5551 ok(!sem, "semaphore should not exist\n");
5552 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
5554 SetLastError(0xdeadbeef);
5555 sem = CreateSemaphoreA(NULL, 0, 10, "WineTestSemaphore");
5556 ok(sem != 0, "CreateSemaphore error %d\n", GetLastError());
5558 access = get_obj_access(sem);
5559 ok(access == SEMAPHORE_ALL_ACCESS, "expected SEMAPHORE_ALL_ACCESS, got %#x\n", access);
5561 for (i = 0; i < ARRAY_SIZE(map); i++)
5563 SetLastError( 0xdeadbeef );
5564 ret = DuplicateHandle(GetCurrentProcess(), sem, GetCurrentProcess(), &dup,
5565 map[i].generic, FALSE, 0);
5566 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5568 access = get_obj_access(dup);
5569 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5571 CloseHandle(dup);
5574 test_default_handle_security(token, sem, &mapping);
5576 CloseHandle(sem);
5579 #define WINE_TEST_PIPE "\\\\.\\pipe\\WineTestPipe"
5580 static void test_named_pipe_security(HANDLE token)
5582 DWORD ret, i, access;
5583 HANDLE pipe, file, dup;
5584 GENERIC_MAPPING mapping = { FILE_GENERIC_READ,
5585 FILE_GENERIC_WRITE,
5586 FILE_GENERIC_EXECUTE,
5587 STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS };
5588 static const struct
5590 int generic, mapped;
5591 } map[] =
5593 { 0, 0 },
5594 { GENERIC_READ, FILE_GENERIC_READ },
5595 { GENERIC_WRITE, FILE_GENERIC_WRITE },
5596 { GENERIC_EXECUTE, FILE_GENERIC_EXECUTE },
5597 { GENERIC_ALL, STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS }
5599 static const struct
5601 DWORD open_mode;
5602 DWORD access;
5603 } creation_access[] =
5605 { PIPE_ACCESS_INBOUND, FILE_GENERIC_READ },
5606 { PIPE_ACCESS_OUTBOUND, FILE_GENERIC_WRITE },
5607 { PIPE_ACCESS_DUPLEX, FILE_GENERIC_READ|FILE_GENERIC_WRITE },
5608 { PIPE_ACCESS_INBOUND|WRITE_DAC, FILE_GENERIC_READ|WRITE_DAC },
5609 { PIPE_ACCESS_INBOUND|WRITE_OWNER, FILE_GENERIC_READ|WRITE_OWNER }
5610 /* ACCESS_SYSTEM_SECURITY is also valid, but will fail with ERROR_PRIVILEGE_NOT_HELD */
5613 /* Test the different security access options for pipes */
5614 for (i = 0; i < ARRAY_SIZE(creation_access); i++)
5616 SetLastError(0xdeadbeef);
5617 pipe = CreateNamedPipeA(WINE_TEST_PIPE, creation_access[i].open_mode,
5618 PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0,
5619 NMPWAIT_USE_DEFAULT_WAIT, NULL);
5620 ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe(0x%x) error %d\n",
5621 creation_access[i].open_mode, GetLastError());
5622 access = get_obj_access(pipe);
5623 ok(access == creation_access[i].access,
5624 "CreateNamedPipeA(0x%x) pipe expected access 0x%x (got 0x%x)\n",
5625 creation_access[i].open_mode, creation_access[i].access, access);
5626 CloseHandle(pipe);
5629 SetLastError(0xdeadbeef);
5630 pipe = CreateNamedPipeA(WINE_TEST_PIPE, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
5631 PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES,
5632 0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL);
5633 ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe error %d\n", GetLastError());
5635 test_default_handle_security(token, pipe, &mapping);
5637 SetLastError(0xdeadbeef);
5638 file = CreateFileA(WINE_TEST_PIPE, FILE_ALL_ACCESS, 0, NULL, OPEN_EXISTING, 0, 0);
5639 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5641 access = get_obj_access(file);
5642 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5644 for (i = 0; i < ARRAY_SIZE(map); i++)
5646 SetLastError( 0xdeadbeef );
5647 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5648 map[i].generic, FALSE, 0);
5649 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5651 access = get_obj_access(dup);
5652 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5654 CloseHandle(dup);
5657 CloseHandle(file);
5658 CloseHandle(pipe);
5660 SetLastError(0xdeadbeef);
5661 file = CreateFileA("\\\\.\\pipe\\", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
5662 ok(file != INVALID_HANDLE_VALUE || broken(file == INVALID_HANDLE_VALUE) /* before Vista */, "CreateFile error %d\n", GetLastError());
5664 if (file != INVALID_HANDLE_VALUE)
5666 access = get_obj_access(file);
5667 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5669 for (i = 0; i < ARRAY_SIZE(map); i++)
5671 SetLastError( 0xdeadbeef );
5672 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5673 map[i].generic, FALSE, 0);
5674 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5676 access = get_obj_access(dup);
5677 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5678 CloseHandle(dup);
5682 CloseHandle(file);
5685 static void test_file_security(HANDLE token)
5687 DWORD ret, i, access, bytes;
5688 HANDLE file, dup;
5689 static const struct
5691 int generic, mapped;
5692 } map[] =
5694 { 0, 0 },
5695 { GENERIC_READ, FILE_GENERIC_READ },
5696 { GENERIC_WRITE, FILE_GENERIC_WRITE },
5697 { GENERIC_EXECUTE, FILE_GENERIC_EXECUTE },
5698 { GENERIC_ALL, STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS }
5700 char temp_path[MAX_PATH];
5701 char file_name[MAX_PATH];
5702 char buf[16];
5704 GetTempPathA(MAX_PATH, temp_path);
5705 GetTempFileNameA(temp_path, "tmp", 0, file_name);
5707 /* file */
5708 SetLastError(0xdeadbeef);
5709 file = CreateFileA(file_name, GENERIC_ALL, 0, NULL, CREATE_ALWAYS, 0, NULL);
5710 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5712 access = get_obj_access(file);
5713 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5715 for (i = 0; i < ARRAY_SIZE(map); i++)
5717 SetLastError( 0xdeadbeef );
5718 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5719 map[i].generic, FALSE, 0);
5720 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5722 access = get_obj_access(dup);
5723 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5725 CloseHandle(dup);
5728 CloseHandle(file);
5730 SetLastError(0xdeadbeef);
5731 file = CreateFileA(file_name, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
5732 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5734 access = get_obj_access(file);
5735 ok(access == (FILE_READ_ATTRIBUTES | SYNCHRONIZE), "expected FILE_READ_ATTRIBUTES | SYNCHRONIZE, got %#x\n", access);
5737 bytes = 0xdeadbeef;
5738 SetLastError(0xdeadbeef);
5739 ret = ReadFile(file, buf, sizeof(buf), &bytes, NULL);
5740 ok(!ret, "ReadFile should fail\n");
5741 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
5742 ok(bytes == 0, "expected 0, got %u\n", bytes);
5744 CloseHandle(file);
5746 SetLastError(0xdeadbeef);
5747 file = CreateFileA(file_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
5748 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5750 access = get_obj_access(file);
5751 ok(access == (FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES), "expected FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES, got %#x\n", access);
5753 bytes = 0xdeadbeef;
5754 SetLastError(0xdeadbeef);
5755 ret = ReadFile(file, buf, sizeof(buf), &bytes, NULL);
5756 ok(!ret, "ReadFile should fail\n");
5757 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
5758 ok(bytes == 0, "expected 0, got %u\n", bytes);
5760 CloseHandle(file);
5761 DeleteFileA(file_name);
5763 /* directory */
5764 SetLastError(0xdeadbeef);
5765 file = CreateFileA(temp_path, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
5766 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5768 access = get_obj_access(file);
5769 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5771 for (i = 0; i < ARRAY_SIZE(map); i++)
5773 SetLastError( 0xdeadbeef );
5774 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5775 map[i].generic, FALSE, 0);
5776 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5778 access = get_obj_access(dup);
5779 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5781 CloseHandle(dup);
5784 CloseHandle(file);
5786 SetLastError(0xdeadbeef);
5787 file = CreateFileA(temp_path, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
5788 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5790 access = get_obj_access(file);
5791 ok(access == (FILE_READ_ATTRIBUTES | SYNCHRONIZE), "expected FILE_READ_ATTRIBUTES | SYNCHRONIZE, got %#x\n", access);
5793 CloseHandle(file);
5795 SetLastError(0xdeadbeef);
5796 file = CreateFileA(temp_path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
5797 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5799 access = get_obj_access(file);
5800 ok(access == (FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES), "expected FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES, got %#x\n", access);
5802 CloseHandle(file);
5805 static void test_filemap_security(void)
5807 char temp_path[MAX_PATH];
5808 char file_name[MAX_PATH];
5809 DWORD ret, i, access;
5810 HANDLE file, mapping, dup, created_mapping;
5811 static const struct
5813 int generic, mapped;
5814 BOOL open_only;
5815 } map[] =
5817 { 0, 0 },
5818 { GENERIC_READ, STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ },
5819 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE },
5820 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE },
5821 { GENERIC_ALL, STANDARD_RIGHTS_REQUIRED | SECTION_ALL_ACCESS },
5822 { SECTION_MAP_READ | SECTION_MAP_WRITE, SECTION_MAP_READ | SECTION_MAP_WRITE },
5823 { SECTION_MAP_WRITE, SECTION_MAP_WRITE },
5824 { SECTION_MAP_READ | SECTION_QUERY, SECTION_MAP_READ | SECTION_QUERY },
5825 { SECTION_QUERY, SECTION_MAP_READ, TRUE },
5826 { SECTION_QUERY | SECTION_MAP_READ, SECTION_QUERY | SECTION_MAP_READ }
5828 static const struct
5830 int prot, mapped;
5831 } prot_map[] =
5833 { 0, 0 },
5834 { PAGE_NOACCESS, 0 },
5835 { PAGE_READONLY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ },
5836 { PAGE_READWRITE, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE },
5837 { PAGE_WRITECOPY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ },
5838 { PAGE_EXECUTE, 0 },
5839 { PAGE_EXECUTE_READ, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE },
5840 { PAGE_EXECUTE_READWRITE, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE },
5841 { PAGE_EXECUTE_WRITECOPY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE }
5844 GetTempPathA(MAX_PATH, temp_path);
5845 GetTempFileNameA(temp_path, "tmp", 0, file_name);
5847 SetLastError(0xdeadbeef);
5848 file = CreateFileA(file_name, GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE, 0, NULL, CREATE_ALWAYS, 0, 0);
5849 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5850 SetFilePointer(file, 4096, NULL, FILE_BEGIN);
5851 SetEndOfFile(file);
5853 for (i = 0; i < ARRAY_SIZE(prot_map); i++)
5855 if (map[i].open_only) continue;
5857 SetLastError(0xdeadbeef);
5858 mapping = CreateFileMappingW(file, NULL, prot_map[i].prot, 0, 4096, NULL);
5859 if (prot_map[i].mapped)
5861 if (!mapping)
5863 /* NT4 and win2k don't support EXEC on file mappings */
5864 if (prot_map[i].prot == PAGE_EXECUTE_READ || prot_map[i].prot == PAGE_EXECUTE_READWRITE || prot_map[i].prot == PAGE_EXECUTE_WRITECOPY)
5866 win_skip("CreateFileMapping doesn't support PAGE_EXECUTE protection\n");
5867 continue;
5870 ok(mapping != 0, "CreateFileMapping(%04x) error %d\n", prot_map[i].prot, GetLastError());
5872 else
5874 ok(!mapping, "CreateFileMapping(%04x) should fail\n", prot_map[i].prot);
5875 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
5876 continue;
5879 access = get_obj_access(mapping);
5880 ok(access == prot_map[i].mapped, "%d: expected %#x, got %#x\n", i, prot_map[i].mapped, access);
5882 CloseHandle(mapping);
5885 SetLastError(0xdeadbeef);
5886 mapping = CreateFileMappingW(file, NULL, PAGE_EXECUTE_READWRITE, 0, 4096, NULL);
5887 if (!mapping)
5889 /* NT4 and win2k don't support EXEC on file mappings */
5890 win_skip("CreateFileMapping doesn't support PAGE_EXECUTE protection\n");
5891 CloseHandle(file);
5892 DeleteFileA(file_name);
5893 return;
5895 ok(mapping != 0, "CreateFileMapping error %d\n", GetLastError());
5897 access = get_obj_access(mapping);
5898 ok(access == (STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE),
5899 "expected STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, got %#x\n", access);
5901 for (i = 0; i < ARRAY_SIZE(map); i++)
5903 if (map[i].open_only) continue;
5905 SetLastError( 0xdeadbeef );
5906 ret = DuplicateHandle(GetCurrentProcess(), mapping, GetCurrentProcess(), &dup,
5907 map[i].generic, FALSE, 0);
5908 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5910 access = get_obj_access(dup);
5911 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5913 CloseHandle(dup);
5916 CloseHandle(mapping);
5917 CloseHandle(file);
5918 DeleteFileA(file_name);
5920 created_mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 0x1000,
5921 "Wine Test Open Mapping");
5922 ok(created_mapping != NULL, "CreateFileMapping failed with error %u\n", GetLastError());
5924 for (i = 0; i < ARRAY_SIZE(map); i++)
5926 if (!map[i].generic) continue;
5928 mapping = OpenFileMappingA(map[i].generic, FALSE, "Wine Test Open Mapping");
5929 ok(mapping != NULL, "OpenFileMapping failed with error %d\n", GetLastError());
5930 access = get_obj_access(mapping);
5931 ok(access == map[i].mapped, "%d: unexpected access flags %#x, expected %#x\n",
5932 i, access, map[i].mapped);
5933 CloseHandle(mapping);
5936 CloseHandle(created_mapping);
5939 static void test_thread_security(void)
5941 DWORD ret, i, access;
5942 HANDLE thread, dup;
5943 static const struct
5945 int generic, mapped;
5946 } map[] =
5948 { 0, 0 },
5949 { GENERIC_READ, STANDARD_RIGHTS_READ | THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT },
5950 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | THREAD_SET_INFORMATION | THREAD_SET_CONTEXT | THREAD_TERMINATE | THREAD_SUSPEND_RESUME | 0x4 },
5951 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5952 { GENERIC_ALL, THREAD_ALL_ACCESS_NT4 }
5955 SetLastError(0xdeadbeef);
5956 thread = CreateThread(NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
5957 ok(thread != 0, "CreateThread error %d\n", GetLastError());
5959 access = get_obj_access(thread);
5960 ok(access == THREAD_ALL_ACCESS_NT4 || access == THREAD_ALL_ACCESS_VISTA, "expected THREAD_ALL_ACCESS, got %#x\n", access);
5962 for (i = 0; i < ARRAY_SIZE(map); i++)
5964 SetLastError( 0xdeadbeef );
5965 ret = DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &dup,
5966 map[i].generic, FALSE, 0);
5967 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5969 access = get_obj_access(dup);
5970 switch (map[i].generic)
5972 case GENERIC_READ:
5973 case GENERIC_EXECUTE:
5974 ok(access == map[i].mapped ||
5975 access == (map[i].mapped | THREAD_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
5976 access == (map[i].mapped | THREAD_QUERY_LIMITED_INFORMATION | THREAD_RESUME) /* win8 */,
5977 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5978 break;
5979 case GENERIC_WRITE:
5980 todo_wine
5981 ok(access == map[i].mapped ||
5982 access == (map[i].mapped | THREAD_SET_LIMITED_INFORMATION) /* Vista+ */ ||
5983 access == (map[i].mapped | THREAD_SET_LIMITED_INFORMATION | THREAD_RESUME) /* win8 */,
5984 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5985 break;
5986 case GENERIC_ALL:
5987 ok(access == map[i].mapped || access == THREAD_ALL_ACCESS_VISTA,
5988 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5989 break;
5990 default:
5991 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5992 break;
5995 CloseHandle(dup);
5998 SetLastError( 0xdeadbeef );
5999 ret = DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &dup,
6000 THREAD_QUERY_INFORMATION, FALSE, 0);
6001 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6002 access = get_obj_access(dup);
6003 ok(access == (THREAD_QUERY_INFORMATION | THREAD_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
6004 access == THREAD_QUERY_INFORMATION /* before Vista */,
6005 "expected THREAD_QUERY_INFORMATION|THREAD_QUERY_LIMITED_INFORMATION, got %#x\n", access);
6006 CloseHandle(dup);
6008 TerminateThread(thread, 0);
6009 CloseHandle(thread);
6012 static void test_process_access(void)
6014 DWORD ret, i, access;
6015 HANDLE process, dup;
6016 STARTUPINFOA sti;
6017 PROCESS_INFORMATION pi;
6018 char cmdline[] = "winver.exe";
6019 static const struct
6021 int generic, mapped;
6022 } map[] =
6024 { 0, 0 },
6025 { GENERIC_READ, STANDARD_RIGHTS_READ | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ },
6026 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | PROCESS_SET_QUOTA | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME |
6027 PROCESS_VM_WRITE | PROCESS_DUP_HANDLE | PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION },
6028 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
6029 { GENERIC_ALL, PROCESS_ALL_ACCESS_NT4 }
6032 memset(&sti, 0, sizeof(sti));
6033 sti.cb = sizeof(sti);
6034 SetLastError(0xdeadbeef);
6035 ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
6036 ok(ret, "CreateProcess() error %d\n", GetLastError());
6038 CloseHandle(pi.hThread);
6039 process = pi.hProcess;
6041 access = get_obj_access(process);
6042 ok(access == PROCESS_ALL_ACCESS_NT4 || access == PROCESS_ALL_ACCESS_VISTA, "expected PROCESS_ALL_ACCESS, got %#x\n", access);
6044 for (i = 0; i < ARRAY_SIZE(map); i++)
6046 SetLastError( 0xdeadbeef );
6047 ret = DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &dup,
6048 map[i].generic, FALSE, 0);
6049 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6051 access = get_obj_access(dup);
6052 switch (map[i].generic)
6054 case GENERIC_READ:
6055 ok(access == map[i].mapped || access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION) /* Vista+ */,
6056 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6057 break;
6058 case GENERIC_WRITE:
6059 ok(access == map[i].mapped ||
6060 access == (map[i].mapped | PROCESS_TERMINATE) /* before Vista */ ||
6061 access == (map[i].mapped | PROCESS_SET_LIMITED_INFORMATION) /* win8 */ ||
6062 access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SET_LIMITED_INFORMATION) /* Win10 Anniversary Update */,
6063 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6064 break;
6065 case GENERIC_EXECUTE:
6066 ok(access == map[i].mapped || access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE) /* Vista+ */,
6067 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6068 break;
6069 case GENERIC_ALL:
6070 ok(access == map[i].mapped || access == PROCESS_ALL_ACCESS_VISTA,
6071 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6072 break;
6073 default:
6074 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6075 break;
6078 CloseHandle(dup);
6081 SetLastError( 0xdeadbeef );
6082 ret = DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &dup,
6083 PROCESS_QUERY_INFORMATION, FALSE, 0);
6084 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6085 access = get_obj_access(dup);
6086 ok(access == (PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
6087 access == PROCESS_QUERY_INFORMATION /* before Vista */,
6088 "expected PROCESS_QUERY_INFORMATION|PROCESS_QUERY_LIMITED_INFORMATION, got %#x\n", access);
6089 CloseHandle(dup);
6091 TerminateProcess(process, 0);
6092 CloseHandle(process);
6095 static BOOL validate_impersonation_token(HANDLE token, DWORD *token_type)
6097 DWORD ret, needed;
6098 TOKEN_TYPE type;
6099 SECURITY_IMPERSONATION_LEVEL sil;
6101 type = 0xdeadbeef;
6102 needed = 0;
6103 SetLastError(0xdeadbeef);
6104 ret = GetTokenInformation(token, TokenType, &type, sizeof(type), &needed);
6105 ok(ret, "GetTokenInformation error %d\n", GetLastError());
6106 ok(needed == sizeof(type), "GetTokenInformation should return required buffer length\n");
6107 ok(type == TokenPrimary || type == TokenImpersonation, "expected TokenPrimary or TokenImpersonation, got %d\n", type);
6109 *token_type = type;
6110 if (type != TokenImpersonation) return FALSE;
6112 needed = 0;
6113 SetLastError(0xdeadbeef);
6114 ret = GetTokenInformation(token, TokenImpersonationLevel, &sil, sizeof(sil), &needed);
6115 ok(ret, "GetTokenInformation error %d\n", GetLastError());
6116 ok(needed == sizeof(sil), "GetTokenInformation should return required buffer length\n");
6117 ok(sil == SecurityImpersonation, "expected SecurityImpersonation, got %d\n", sil);
6119 needed = 0xdeadbeef;
6120 SetLastError(0xdeadbeef);
6121 ret = GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &needed);
6122 ok(!ret, "GetTokenInformation should fail\n");
6123 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6124 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
6125 ok(needed > sizeof(TOKEN_DEFAULT_DACL), "GetTokenInformation returned empty default DACL\n");
6127 needed = 0xdeadbeef;
6128 SetLastError(0xdeadbeef);
6129 ret = GetTokenInformation(token, TokenOwner, NULL, 0, &needed);
6130 ok(!ret, "GetTokenInformation should fail\n");
6131 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6132 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
6133 ok(needed > sizeof(TOKEN_OWNER), "GetTokenInformation returned empty token owner\n");
6135 needed = 0xdeadbeef;
6136 SetLastError(0xdeadbeef);
6137 ret = GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &needed);
6138 ok(!ret, "GetTokenInformation should fail\n");
6139 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6140 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
6141 ok(needed > sizeof(TOKEN_PRIMARY_GROUP), "GetTokenInformation returned empty token primary group\n");
6143 return TRUE;
6146 static void test_kernel_objects_security(void)
6148 HANDLE token, process_token;
6149 DWORD ret, token_type;
6151 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process_token);
6152 ok(ret, "OpenProcessToken error %d\n", GetLastError());
6154 ret = validate_impersonation_token(process_token, &token_type);
6155 ok(token_type == TokenPrimary, "expected TokenPrimary, got %d\n", token_type);
6156 ok(!ret, "access token should not be an impersonation token\n");
6158 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
6159 ok(ret, "DuplicateToken error %d\n", GetLastError());
6161 ret = validate_impersonation_token(token, &token_type);
6162 ok(ret, "access token should be a valid impersonation token\n");
6163 ok(token_type == TokenImpersonation, "expected TokenImpersonation, got %d\n", token_type);
6165 test_mutex_security(token);
6166 test_event_security(token);
6167 test_named_pipe_security(token);
6168 test_semaphore_security(token);
6169 test_file_security(token);
6170 test_filemap_security();
6171 test_thread_security();
6172 test_process_access();
6173 /* FIXME: test other kernel object types */
6175 CloseHandle(process_token);
6176 CloseHandle(token);
6179 static void test_TokenIntegrityLevel(void)
6181 TOKEN_MANDATORY_LABEL *tml;
6182 BYTE buffer[64]; /* using max. 28 byte in win7 x64 */
6183 HANDLE token;
6184 DWORD size;
6185 DWORD res;
6186 static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6187 {SECURITY_MANDATORY_HIGH_RID}};
6188 static SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6189 {SECURITY_MANDATORY_MEDIUM_RID}};
6191 SetLastError(0xdeadbeef);
6192 res = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
6193 ok(res, "got %d with %d (expected TRUE)\n", res, GetLastError());
6195 SetLastError(0xdeadbeef);
6196 res = GetTokenInformation(token, TokenIntegrityLevel, buffer, sizeof(buffer), &size);
6198 /* not supported before Vista */
6199 if (!res && ((GetLastError() == ERROR_INVALID_PARAMETER) || GetLastError() == ERROR_INVALID_FUNCTION))
6201 win_skip("TokenIntegrityLevel not supported\n");
6202 CloseHandle(token);
6203 return;
6206 ok(res, "got %u with %u (expected TRUE)\n", res, GetLastError());
6207 if (!res)
6209 CloseHandle(token);
6210 return;
6213 tml = (TOKEN_MANDATORY_LABEL*) buffer;
6214 ok(tml->Label.Attributes == (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED),
6215 "got 0x%x (expected 0x%x)\n", tml->Label.Attributes, (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED));
6217 ok(EqualSid(tml->Label.Sid, &medium_level) || EqualSid(tml->Label.Sid, &high_level),
6218 "got %s (expected %s or %s)\n", debugstr_sid(tml->Label.Sid),
6219 debugstr_sid(&medium_level), debugstr_sid(&high_level));
6221 CloseHandle(token);
6224 static void test_default_dacl_owner_sid(void)
6226 HANDLE handle;
6227 BOOL ret, defaulted, present, found;
6228 DWORD size, index;
6229 SECURITY_DESCRIPTOR *sd;
6230 SECURITY_ATTRIBUTES sa;
6231 PSID owner;
6232 ACL *dacl;
6233 ACCESS_ALLOWED_ACE *ace;
6235 sd = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
6236 ret = InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION );
6237 ok( ret, "error %u\n", GetLastError() );
6239 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
6240 sa.lpSecurityDescriptor = sd;
6241 sa.bInheritHandle = FALSE;
6242 handle = CreateEventA( &sa, TRUE, TRUE, "test_event" );
6243 ok( handle != NULL, "error %u\n", GetLastError() );
6245 size = 0;
6246 ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, NULL, 0, &size );
6247 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "error %u\n", GetLastError() );
6249 sd = HeapAlloc( GetProcessHeap(), 0, size );
6250 ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, sd, size, &size );
6251 ok( ret, "error %u\n", GetLastError() );
6253 owner = (void *)0xdeadbeef;
6254 defaulted = TRUE;
6255 ret = GetSecurityDescriptorOwner( sd, &owner, &defaulted );
6256 ok( ret, "error %u\n", GetLastError() );
6257 ok( owner != (void *)0xdeadbeef, "owner not set\n" );
6258 ok( !defaulted, "owner defaulted\n" );
6260 dacl = (void *)0xdeadbeef;
6261 present = FALSE;
6262 defaulted = TRUE;
6263 ret = GetSecurityDescriptorDacl( sd, &present, &dacl, &defaulted );
6264 ok( ret, "error %u\n", GetLastError() );
6265 ok( present, "dacl not present\n" );
6266 ok( dacl != (void *)0xdeadbeef, "dacl not set\n" );
6267 ok( !defaulted, "dacl defaulted\n" );
6269 index = 0;
6270 found = FALSE;
6271 while (GetAce( dacl, index++, (void **)&ace ))
6273 if (EqualSid( &ace->SidStart, owner )) found = TRUE;
6275 ok( found, "owner sid not found in dacl\n" );
6277 HeapFree( GetProcessHeap(), 0, sa.lpSecurityDescriptor );
6278 HeapFree( GetProcessHeap(), 0, sd );
6279 CloseHandle( handle );
6282 static void test_AdjustTokenPrivileges(void)
6284 TOKEN_PRIVILEGES tp;
6285 HANDLE token;
6286 DWORD len;
6287 LUID luid;
6288 BOOL ret;
6290 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
6291 return;
6293 if (!LookupPrivilegeValueA(NULL, SE_BACKUP_NAME, &luid))
6295 CloseHandle(token);
6296 return;
6299 tp.PrivilegeCount = 1;
6300 tp.Privileges[0].Luid = luid;
6301 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
6303 len = 0xdeadbeef;
6304 ret = AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, &len);
6305 ok(ret, "got %d\n", ret);
6306 ok(len == 0xdeadbeef, "got length %d\n", len);
6308 /* revert */
6309 tp.PrivilegeCount = 1;
6310 tp.Privileges[0].Luid = luid;
6311 tp.Privileges[0].Attributes = 0;
6312 ret = AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
6313 ok(ret, "got %d\n", ret);
6315 CloseHandle(token);
6318 static void test_AddAce(void)
6320 static SID const sidWorld = { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY} , { SECURITY_WORLD_RID } };
6322 char acl_buf[1024], ace_buf[256];
6323 ACCESS_ALLOWED_ACE *ace = (ACCESS_ALLOWED_ACE*)ace_buf;
6324 PACL acl = (PACL)acl_buf;
6325 BOOL ret;
6327 memset(ace, 0, sizeof(ace_buf));
6328 ace->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
6329 ace->Header.AceSize = sizeof(ACCESS_ALLOWED_ACE)-sizeof(DWORD)+sizeof(SID);
6330 memcpy(&ace->SidStart, &sidWorld, sizeof(sidWorld));
6332 ret = InitializeAcl(acl, sizeof(acl_buf), ACL_REVISION2);
6333 ok(ret, "InitializeAcl failed: %d\n", GetLastError());
6335 ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
6336 ok(ret, "AddAce failed: %d\n", GetLastError());
6337 ret = AddAce(acl, ACL_REVISION2, MAXDWORD, ace, ace->Header.AceSize);
6338 ok(ret, "AddAce failed: %d\n", GetLastError());
6339 ret = AddAce(acl, ACL_REVISION3, MAXDWORD, ace, ace->Header.AceSize);
6340 ok(ret, "AddAce failed: %d\n", GetLastError());
6341 ok(acl->AclRevision == ACL_REVISION3, "acl->AclRevision = %d\n", acl->AclRevision);
6342 ret = AddAce(acl, ACL_REVISION4, MAXDWORD, ace, ace->Header.AceSize);
6343 ok(ret, "AddAce failed: %d\n", GetLastError());
6344 ok(acl->AclRevision == ACL_REVISION4, "acl->AclRevision = %d\n", acl->AclRevision);
6345 ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
6346 ok(ret, "AddAce failed: %d\n", GetLastError());
6347 ok(acl->AclRevision == ACL_REVISION4, "acl->AclRevision = %d\n", acl->AclRevision);
6348 ret = AddAce(acl, ACL_REVISION2, MAXDWORD, ace, ace->Header.AceSize);
6349 ok(ret, "AddAce failed: %d\n", GetLastError());
6351 ret = AddAce(acl, MIN_ACL_REVISION-1, MAXDWORD, ace, ace->Header.AceSize);
6352 ok(ret, "AddAce failed: %d\n", GetLastError());
6353 /* next test succeededs but corrupts ACL */
6354 ret = AddAce(acl, MAX_ACL_REVISION+1, MAXDWORD, ace, ace->Header.AceSize);
6355 ok(ret, "AddAce failed: %d\n", GetLastError());
6356 ok(acl->AclRevision == MAX_ACL_REVISION+1, "acl->AclRevision = %d\n", acl->AclRevision);
6357 SetLastError(0xdeadbeef);
6358 ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
6359 ok(!ret, "AddAce succeeded\n");
6360 ok(GetLastError() == ERROR_INVALID_PARAMETER, "GetLastError() = %d\n", GetLastError());
6363 static void test_AddMandatoryAce(void)
6365 static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6366 {SECURITY_MANDATORY_LOW_RID}};
6367 static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6368 {SECURITY_MANDATORY_MEDIUM_RID}};
6369 static SID_IDENTIFIER_AUTHORITY sia_world = {SECURITY_WORLD_SID_AUTHORITY};
6370 char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
6371 SECURITY_DESCRIPTOR *sd2, *sd = (SECURITY_DESCRIPTOR *)&buffer_sd;
6372 BOOL defaulted, present, ret, found, found2;
6373 ACL_SIZE_INFORMATION acl_size_info;
6374 SYSTEM_MANDATORY_LABEL_ACE *ace;
6375 char buffer_acl[256];
6376 ACL *acl = (ACL *)&buffer_acl;
6377 SECURITY_ATTRIBUTES sa;
6378 DWORD index, size;
6379 HANDLE handle;
6380 SID *everyone;
6381 ACL *sacl;
6383 if (!pAddMandatoryAce)
6385 win_skip("AddMandatoryAce not supported, skipping test\n");
6386 return;
6389 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
6390 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
6392 sa.nLength = sizeof(sa);
6393 sa.lpSecurityDescriptor = sd;
6394 sa.bInheritHandle = FALSE;
6396 handle = CreateEventA(&sa, TRUE, TRUE, "test_event");
6397 ok(handle != NULL, "CreateEventA failed with error %u\n", GetLastError());
6399 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6400 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6401 "Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
6403 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6404 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6405 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6407 sacl = (void *)0xdeadbeef;
6408 present = TRUE;
6409 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6410 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6411 ok(!present, "SACL is present\n");
6412 ok(sacl == (void *)0xdeadbeef, "SACL is set\n");
6414 HeapFree(GetProcessHeap(), 0, sd2);
6415 CloseHandle(handle);
6417 memset(buffer_acl, 0, sizeof(buffer_acl));
6418 ret = InitializeAcl(acl, 256, ACL_REVISION);
6419 ok(ret, "InitializeAcl failed with %u\n", GetLastError());
6421 SetLastError(0xdeadbeef);
6422 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, 0x1234, &low_level);
6423 ok(!ret, "AddMandatoryAce succeeded\n");
6424 ok(GetLastError() == ERROR_INVALID_PARAMETER,
6425 "Expected ERROR_INVALID_PARAMETER got %u\n", GetLastError());
6427 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &low_level);
6428 ok(ret, "AddMandatoryAce failed with %u\n", GetLastError());
6430 index = 0;
6431 found = FALSE;
6432 while (GetAce(acl, index++, (void **)&ace))
6434 if (ace->Header.AceType != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
6435 ok(ace->Header.AceFlags == 0, "Expected flags 0, got %x\n", ace->Header.AceFlags);
6436 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
6437 "Expected mask SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, got %x\n", ace->Mask);
6438 ok(EqualSid(&ace->SidStart, &low_level), "Expected low integrity level\n");
6439 found = TRUE;
6441 ok(found, "Could not find mandatory label ace\n");
6443 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
6444 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6446 handle = CreateEventA(&sa, TRUE, TRUE, "test_event");
6447 ok(handle != NULL, "CreateEventA failed with error %u\n", GetLastError());
6449 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6450 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6451 "Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
6453 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6454 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6455 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6457 sacl = (void *)0xdeadbeef;
6458 present = FALSE;
6459 defaulted = TRUE;
6460 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6461 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6462 ok(present, "SACL not present\n");
6463 ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
6464 ok(!defaulted, "SACL defaulted\n");
6465 ret = GetAclInformation(sacl, &acl_size_info, sizeof(acl_size_info), AclSizeInformation);
6466 ok(ret, "GetAclInformation failed with error %u\n", GetLastError());
6467 ok(acl_size_info.AceCount == 1, "SACL contains an unexpected ACE count %u\n", acl_size_info.AceCount);
6469 ret = GetAce(sacl, 0, (void **)&ace);
6470 ok(ret, "GetAce failed with error %u\n", GetLastError());
6471 ok (ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE, "Unexpected ACE type %#x\n", ace->Header.AceType);
6472 ok(!ace->Header.AceFlags, "Unexpected ACE flags %#x\n", ace->Header.AceFlags);
6473 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, "Unexpected ACE mask %#x\n", ace->Mask);
6474 ok(EqualSid(&ace->SidStart, &low_level), "Expected low integrity level\n");
6476 HeapFree(GetProcessHeap(), 0, sd2);
6478 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, &medium_level);
6479 ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
6481 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6482 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6484 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6485 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6486 "Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
6488 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6489 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6490 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6492 sacl = (void *)0xdeadbeef;
6493 present = FALSE;
6494 defaulted = TRUE;
6495 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6496 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6497 ok(present, "SACL not present\n");
6498 ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
6499 ok(sacl->AceCount == 2, "Expected 2 ACEs, got %d\n", sacl->AceCount);
6500 ok(!defaulted, "SACL defaulted\n");
6502 index = 0;
6503 found = found2 = FALSE;
6504 while (GetAce(sacl, index++, (void **)&ace))
6506 if (ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
6508 if (EqualSid(&ace->SidStart, &low_level))
6510 found = TRUE;
6511 ok(!ace->Header.AceFlags, "Expected 0 as flags, got %#x\n", ace->Header.AceFlags);
6512 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
6513 "Expected SYSTEM_MANDATORY_LABEL_NO_WRITE_UP as mask, got %#x\n", ace->Mask);
6515 if (EqualSid(&ace->SidStart, &medium_level))
6517 found2 = TRUE;
6518 ok(!ace->Header.AceFlags, "Expected 0 as flags, got %#x\n", ace->Header.AceFlags);
6519 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP,
6520 "Expected SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP as mask, got %#x\n", ace->Mask);
6524 ok(found, "Could not find low mandatory label\n");
6525 ok(found2, "Could not find medium mandatory label\n");
6527 HeapFree(GetProcessHeap(), 0, sd2);
6529 ret = SetSecurityDescriptorSacl(sd, FALSE, NULL, FALSE);
6530 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6532 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6533 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6535 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6536 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6537 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6539 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6540 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6541 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6543 sacl = (void *)0xdeadbeef;
6544 present = FALSE;
6545 defaulted = TRUE;
6546 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6547 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6548 ok(present, "SACL not present\n");
6549 ok(sacl && sacl != (void *)0xdeadbeef, "SACL not set\n");
6550 ok(!defaulted, "SACL defaulted\n");
6551 ok(!sacl->AceCount, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
6553 HeapFree(GetProcessHeap(), 0, sd2);
6555 ret = InitializeAcl(acl, 256, ACL_REVISION);
6556 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
6558 ret = pAddMandatoryAce(acl, ACL_REVISION3, 0, SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, &medium_level);
6559 ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
6561 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
6562 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6564 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6565 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6567 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6568 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6569 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6571 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6572 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6573 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6575 sacl = (void *)0xdeadbeef;
6576 present = FALSE;
6577 defaulted = TRUE;
6578 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6579 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6580 ok(present, "SACL not present\n");
6581 ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
6582 ok(sacl->AclRevision == ACL_REVISION3, "Expected revision 3, got %d\n", sacl->AclRevision);
6583 ok(!defaulted, "SACL defaulted\n");
6585 HeapFree(GetProcessHeap(), 0, sd2);
6587 ret = InitializeAcl(acl, 256, ACL_REVISION);
6588 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
6590 ret = AllocateAndInitializeSid(&sia_world, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, (void **)&everyone);
6591 ok(ret, "AllocateAndInitializeSid failed with error %u\n", GetLastError());
6593 ret = AddAccessAllowedAce(acl, ACL_REVISION, KEY_READ, everyone);
6594 ok(ret, "AddAccessAllowedAce failed with error %u\n", GetLastError());
6596 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
6597 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6599 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6600 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6602 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6603 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6604 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6606 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6607 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6608 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6610 sacl = (void *)0xdeadbeef;
6611 present = FALSE;
6612 defaulted = TRUE;
6613 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6614 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6615 ok(present, "SACL not present\n");
6616 ok(sacl && sacl != (void *)0xdeadbeef, "SACL not set\n");
6617 ok(!defaulted, "SACL defaulted\n");
6618 ok(!sacl->AceCount, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
6620 FreeSid(everyone);
6621 HeapFree(GetProcessHeap(), 0, sd2);
6622 CloseHandle(handle);
6625 static void test_system_security_access(void)
6627 static const WCHAR testkeyW[] =
6628 {'S','O','F','T','W','A','R','E','\\','W','i','n','e','\\','S','A','C','L','t','e','s','t',0};
6629 LONG res;
6630 HKEY hkey;
6631 PSECURITY_DESCRIPTOR sd;
6632 ACL *sacl;
6633 DWORD err, len = 128;
6634 TOKEN_PRIVILEGES priv, *priv_prev;
6635 HANDLE token;
6636 LUID luid;
6637 BOOL ret;
6639 if (!OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token )) return;
6640 if (!LookupPrivilegeValueA( NULL, SE_SECURITY_NAME, &luid ))
6642 CloseHandle( token );
6643 return;
6646 /* ACCESS_SYSTEM_SECURITY requires special privilege */
6647 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ|ACCESS_SYSTEM_SECURITY, NULL, &hkey, NULL );
6648 if (res == ERROR_ACCESS_DENIED)
6650 skip( "unprivileged user\n" );
6651 CloseHandle( token );
6652 return;
6654 todo_wine ok( res == ERROR_PRIVILEGE_NOT_HELD, "got %d\n", res );
6656 priv.PrivilegeCount = 1;
6657 priv.Privileges[0].Luid = luid;
6658 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
6660 priv_prev = HeapAlloc( GetProcessHeap(), 0, len );
6661 ret = AdjustTokenPrivileges( token, FALSE, &priv, len, priv_prev, &len );
6662 ok( ret, "got %u\n", GetLastError());
6664 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ|ACCESS_SYSTEM_SECURITY, NULL, &hkey, NULL );
6665 if (res == ERROR_PRIVILEGE_NOT_HELD)
6667 win_skip( "privilege not held\n" );
6668 HeapFree( GetProcessHeap(), 0, priv_prev );
6669 CloseHandle( token );
6670 return;
6672 ok( !res, "got %d\n", res );
6674 /* restore privileges */
6675 ret = AdjustTokenPrivileges( token, FALSE, priv_prev, 0, NULL, NULL );
6676 ok( ret, "got %u\n", GetLastError() );
6677 HeapFree( GetProcessHeap(), 0, priv_prev );
6679 /* privilege is checked on access */
6680 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6681 todo_wine ok( err == ERROR_PRIVILEGE_NOT_HELD || err == ERROR_ACCESS_DENIED, "got %u\n", err );
6682 if (err == ERROR_SUCCESS)
6683 LocalFree( sd );
6685 priv.PrivilegeCount = 1;
6686 priv.Privileges[0].Luid = luid;
6687 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
6689 priv_prev = HeapAlloc( GetProcessHeap(), 0, len );
6690 ret = AdjustTokenPrivileges( token, FALSE, &priv, len, priv_prev, &len );
6691 ok( ret, "got %u\n", GetLastError());
6693 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6694 ok( err == ERROR_SUCCESS, "got %u\n", err );
6695 RegCloseKey( hkey );
6696 LocalFree( sd );
6698 /* handle created without ACCESS_SYSTEM_SECURITY, privilege held */
6699 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ, NULL, &hkey, NULL );
6700 ok( res == ERROR_SUCCESS, "got %d\n", res );
6702 sd = NULL;
6703 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6704 todo_wine ok( err == ERROR_SUCCESS, "got %u\n", err );
6705 RegCloseKey( hkey );
6706 LocalFree( sd );
6708 /* restore privileges */
6709 ret = AdjustTokenPrivileges( token, FALSE, priv_prev, 0, NULL, NULL );
6710 ok( ret, "got %u\n", GetLastError() );
6711 HeapFree( GetProcessHeap(), 0, priv_prev );
6713 /* handle created without ACCESS_SYSTEM_SECURITY, privilege not held */
6714 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ, NULL, &hkey, NULL );
6715 ok( res == ERROR_SUCCESS, "got %d\n", res );
6717 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6718 ok( err == ERROR_PRIVILEGE_NOT_HELD || err == ERROR_ACCESS_DENIED, "got %u\n", err );
6719 RegCloseKey( hkey );
6721 res = RegDeleteKeyW( HKEY_LOCAL_MACHINE, testkeyW );
6722 ok( !res, "got %d\n", res );
6723 CloseHandle( token );
6726 static void test_GetWindowsAccountDomainSid(void)
6728 char *user, buffer1[SECURITY_MAX_SID_SIZE], buffer2[SECURITY_MAX_SID_SIZE];
6729 SID_IDENTIFIER_AUTHORITY domain_ident = { SECURITY_NT_AUTHORITY };
6730 PSID domain_sid = (PSID *)&buffer1;
6731 PSID domain_sid2 = (PSID *)&buffer2;
6732 DWORD sid_size;
6733 PSID user_sid;
6734 HANDLE token;
6735 BOOL bret = TRUE;
6736 int i;
6738 if (!pGetWindowsAccountDomainSid)
6740 win_skip("GetWindowsAccountDomainSid not available\n");
6741 return;
6744 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
6746 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
6747 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
6749 if (!bret)
6751 win_skip("Failed to get current user token\n");
6752 return;
6755 bret = GetTokenInformation(token, TokenUser, NULL, 0, &sid_size);
6756 ok(!bret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6757 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
6758 user = HeapAlloc(GetProcessHeap(), 0, sid_size);
6759 bret = GetTokenInformation(token, TokenUser, user, sid_size, &sid_size);
6760 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
6761 CloseHandle(token);
6762 user_sid = ((TOKEN_USER *)user)->User.Sid;
6764 SetLastError(0xdeadbeef);
6765 bret = pGetWindowsAccountDomainSid(0, 0, 0);
6766 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6767 ok(GetLastError() == ERROR_INVALID_SID, "expected ERROR_INVALID_SID, got %d\n", GetLastError());
6769 SetLastError(0xdeadbeef);
6770 bret = pGetWindowsAccountDomainSid(user_sid, 0, 0);
6771 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6772 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
6774 sid_size = SECURITY_MAX_SID_SIZE;
6775 SetLastError(0xdeadbeef);
6776 bret = pGetWindowsAccountDomainSid(user_sid, 0, &sid_size);
6777 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6778 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
6779 ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
6781 SetLastError(0xdeadbeef);
6782 bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, 0);
6783 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6784 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
6786 sid_size = 1;
6787 SetLastError(0xdeadbeef);
6788 bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, &sid_size);
6789 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6790 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6791 ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
6793 sid_size = SECURITY_MAX_SID_SIZE;
6794 bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, &sid_size);
6795 ok(bret, "GetWindowsAccountDomainSid failed with error %d\n", GetLastError());
6796 ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
6797 InitializeSid(domain_sid2, &domain_ident, 4);
6798 for (i = 0; i < 4; i++)
6799 *GetSidSubAuthority(domain_sid2, i) = *GetSidSubAuthority(user_sid, i);
6800 ok(EqualSid(domain_sid, domain_sid2), "unexpected domain sid %s != %s\n",
6801 debugstr_sid(domain_sid), debugstr_sid(domain_sid2));
6803 HeapFree(GetProcessHeap(), 0, user);
6806 static void test_GetSidIdentifierAuthority(void)
6808 char buffer[SECURITY_MAX_SID_SIZE];
6809 PSID authority_sid = (PSID *)buffer;
6810 PSID_IDENTIFIER_AUTHORITY id;
6811 BOOL ret;
6813 if (!pGetSidIdentifierAuthority)
6815 win_skip("GetSidIdentifierAuthority not available\n");
6816 return;
6819 memset(buffer, 0xcc, sizeof(buffer));
6820 ret = IsValidSid(authority_sid);
6821 ok(!ret, "expected FALSE, got %u\n", ret);
6823 SetLastError(0xdeadbeef);
6824 id = GetSidIdentifierAuthority(authority_sid);
6825 ok(id != NULL, "got NULL pointer as identifier authority\n");
6826 ok(GetLastError() == ERROR_SUCCESS, "expected ERROR_SUCCESS, got %u\n", GetLastError());
6828 SetLastError(0xdeadbeef);
6829 id = GetSidIdentifierAuthority(NULL);
6830 ok(id != NULL, "got NULL pointer as identifier authority\n");
6831 ok(GetLastError() == ERROR_SUCCESS, "expected ERROR_SUCCESS, got %u\n", GetLastError());
6834 static void test_pseudo_tokens(void)
6836 TOKEN_STATISTICS statistics1, statistics2;
6837 HANDLE token;
6838 DWORD retlen;
6839 BOOL ret;
6841 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
6842 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
6843 memset(&statistics1, 0x11, sizeof(statistics1));
6844 ret = GetTokenInformation(token, TokenStatistics, &statistics1, sizeof(statistics1), &retlen);
6845 ok(ret, "GetTokenInformation failed with %u\n", GetLastError());
6846 CloseHandle(token);
6848 /* test GetCurrentProcessToken() */
6849 SetLastError(0xdeadbeef);
6850 memset(&statistics2, 0x22, sizeof(statistics2));
6851 ret = GetTokenInformation(GetCurrentProcessToken(), TokenStatistics,
6852 &statistics2, sizeof(statistics2), &retlen);
6853 ok(ret || broken(GetLastError() == ERROR_INVALID_HANDLE),
6854 "GetTokenInformation failed with %u\n", GetLastError());
6855 if (ret)
6856 ok(!memcmp(&statistics1, &statistics2, sizeof(statistics1)), "Token statistics do not match\n");
6857 else
6858 win_skip("CurrentProcessToken not supported, skipping test\n");
6860 /* test GetCurrentThreadEffectiveToken() */
6861 SetLastError(0xdeadbeef);
6862 memset(&statistics2, 0x22, sizeof(statistics2));
6863 ret = GetTokenInformation(GetCurrentThreadEffectiveToken(), TokenStatistics,
6864 &statistics2, sizeof(statistics2), &retlen);
6865 ok(ret || broken(GetLastError() == ERROR_INVALID_HANDLE),
6866 "GetTokenInformation failed with %u\n", GetLastError());
6867 if (ret)
6868 ok(!memcmp(&statistics1, &statistics2, sizeof(statistics1)), "Token statistics do not match\n");
6869 else
6870 win_skip("CurrentThreadEffectiveToken not supported, skipping test\n");
6872 SetLastError(0xdeadbeef);
6873 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
6874 ok(!ret, "OpenThreadToken should have failed\n");
6875 ok(GetLastError() == ERROR_NO_TOKEN, "Expected ERROR_NO_TOKEN, got %u\n", GetLastError());
6877 /* test GetCurrentThreadToken() */
6878 SetLastError(0xdeadbeef);
6879 ret = GetTokenInformation(GetCurrentThreadToken(), TokenStatistics,
6880 &statistics2, sizeof(statistics2), &retlen);
6881 todo_wine ok(GetLastError() == ERROR_NO_TOKEN || broken(GetLastError() == ERROR_INVALID_HANDLE),
6882 "Expected ERROR_NO_TOKEN, got %u\n", GetLastError());
6885 static void test_maximum_allowed(void)
6887 HANDLE (WINAPI *pCreateEventExA)(SECURITY_ATTRIBUTES *, LPCSTR, DWORD, DWORD);
6888 char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH], buffer_acl[256];
6889 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&buffer_sd;
6890 SECURITY_ATTRIBUTES sa;
6891 ACL *acl = (ACL *)&buffer_acl;
6892 HMODULE hkernel32 = GetModuleHandleA("kernel32.dll");
6893 ACCESS_MASK mask;
6894 HANDLE handle;
6895 BOOL ret;
6897 pCreateEventExA = (void *)GetProcAddress(hkernel32, "CreateEventExA");
6898 if (!pCreateEventExA)
6900 win_skip("CreateEventExA is not available\n");
6901 return;
6904 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
6905 ok(ret, "InitializeSecurityDescriptor failed with %u\n", GetLastError());
6906 memset(buffer_acl, 0, sizeof(buffer_acl));
6907 ret = InitializeAcl(acl, 256, ACL_REVISION);
6908 ok(ret, "InitializeAcl failed with %u\n", GetLastError());
6909 ret = SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
6910 ok(ret, "SetSecurityDescriptorDacl failed with %u\n", GetLastError());
6912 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
6913 sa.lpSecurityDescriptor = sd;
6914 sa.bInheritHandle = FALSE;
6916 handle = pCreateEventExA(&sa, NULL, 0, MAXIMUM_ALLOWED | 0x4);
6917 ok(handle != NULL, "CreateEventExA failed with error %u\n", GetLastError());
6918 mask = get_obj_access(handle);
6919 ok(mask == EVENT_ALL_ACCESS, "Expected %x, got %x\n", EVENT_ALL_ACCESS, mask);
6920 CloseHandle(handle);
6923 static void test_token_label(void)
6925 static SID medium_sid = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6926 {SECURITY_MANDATORY_MEDIUM_RID}};
6927 static SID high_sid = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6928 {SECURITY_MANDATORY_HIGH_RID}};
6929 SECURITY_DESCRIPTOR_CONTROL control;
6930 SYSTEM_MANDATORY_LABEL_ACE *ace;
6931 BOOL ret, present, defaulted;
6932 SECURITY_DESCRIPTOR *sd;
6933 ACL *sacl = NULL, *dacl;
6934 DWORD size, revision;
6935 HANDLE token;
6936 char *str;
6937 SID *sid;
6939 ret = OpenProcessToken(GetCurrentProcess(), READ_CONTROL | WRITE_OWNER, &token);
6940 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
6942 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6943 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6944 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6946 sd = HeapAlloc(GetProcessHeap(), 0, size);
6947 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd, size, &size);
6948 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6950 ret = GetSecurityDescriptorControl(sd, &control, &revision);
6951 ok(ret, "GetSecurityDescriptorControl failed with error %u\n", GetLastError());
6952 todo_wine ok(control == (SE_SELF_RELATIVE | SE_SACL_AUTO_INHERITED | SE_SACL_PRESENT) ||
6953 broken(control == SE_SELF_RELATIVE) /* WinXP, Win2003 */,
6954 "Unexpected security descriptor control %#x\n", control);
6955 ok(revision == 1, "Unexpected security descriptor revision %u\n", revision);
6957 sid = (void *)0xdeadbeef;
6958 defaulted = TRUE;
6959 ret = GetSecurityDescriptorOwner(sd, (void **)&sid, &defaulted);
6960 ok(ret, "GetSecurityDescriptorOwner failed with error %u\n", GetLastError());
6961 ok(!sid, "Owner present\n");
6962 ok(!defaulted, "Owner defaulted\n");
6964 sid = (void *)0xdeadbeef;
6965 defaulted = TRUE;
6966 ret = GetSecurityDescriptorGroup(sd, (void **)&sid, &defaulted);
6967 ok(ret, "GetSecurityDescriptorGroup failed with error %u\n", GetLastError());
6968 ok(!sid, "Group present\n");
6969 ok(!defaulted, "Group defaulted\n");
6971 ret = GetSecurityDescriptorSacl(sd, &present, &sacl, &defaulted);
6972 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6973 ok(present || broken(!present) /* WinXP, Win2003 */, "No SACL in the security descriptor\n");
6974 ok(sacl || broken(!sacl) /* WinXP, Win2003 */, "NULL SACL in the security descriptor\n");
6976 if (present)
6978 ok(!defaulted, "SACL defaulted\n");
6979 ok(sacl->AceCount == 1, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
6981 ret = GetAce(sacl, 0, (void **)&ace);
6982 ok(ret, "GetAce failed with error %u\n", GetLastError());
6984 ok(ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE,
6985 "Unexpected ACE type %#x\n", ace->Header.AceType);
6986 ok(!ace->Header.AceFlags, "Unexpected ACE flags %#x\n", ace->Header.AceFlags);
6987 ok(ace->Header.AceSize, "Unexpected ACE size %u\n", ace->Header.AceSize);
6988 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, "Unexpected ACE mask %#x\n", ace->Mask);
6990 sid = (SID *)&ace->SidStart;
6991 ConvertSidToStringSidA(sid, &str);
6992 ok(EqualSid(sid, &medium_sid) || EqualSid(sid, &high_sid), "Got unexpected SID %s\n", str);
6993 LocalFree(str);
6996 ret = GetSecurityDescriptorDacl(sd, &present, &dacl, &defaulted);
6997 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
6998 todo_wine ok(!present, "DACL present\n");
7000 HeapFree(GetProcessHeap(), 0, sd);
7001 CloseHandle(token);
7004 static void test_token_security_descriptor(void)
7006 static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
7007 {SECURITY_MANDATORY_LOW_RID}};
7008 char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
7009 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&buffer_sd, *sd2;
7010 char buffer_acl[256], buffer[MAX_PATH];
7011 ACL *acl = (ACL *)&buffer_acl, *acl2, *acl_child;
7012 BOOL defaulted, present, ret, found;
7013 HANDLE token, token2, token3;
7014 EXPLICIT_ACCESSW exp_access;
7015 PROCESS_INFORMATION info;
7016 DWORD size, index, retd;
7017 ACCESS_ALLOWED_ACE *ace;
7018 SECURITY_ATTRIBUTES sa;
7019 STARTUPINFOA startup;
7020 PSID psid;
7022 if (!pDuplicateTokenEx || !pAddAccessAllowedAceEx || !pSetEntriesInAclW)
7024 win_skip("Some functions not available\n");
7025 return;
7028 /* Test whether we can create tokens with security descriptors */
7029 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
7030 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
7032 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7033 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
7035 memset(buffer_acl, 0, sizeof(buffer_acl));
7036 ret = InitializeAcl(acl, 256, ACL_REVISION);
7037 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
7039 ret = ConvertStringSidToSidA("S-1-5-6", &psid);
7040 ok(ret, "ConvertStringSidToSidA failed with error %u\n", GetLastError());
7042 ret = pAddAccessAllowedAceEx(acl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, GENERIC_ALL, psid);
7043 ok(ret, "AddAccessAllowedAceEx failed with error %u\n", GetLastError());
7045 ret = SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
7046 ok(ret, "SetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7048 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
7049 sa.lpSecurityDescriptor = sd;
7050 sa.bInheritHandle = FALSE;
7052 ret = pDuplicateTokenEx(token, MAXIMUM_ALLOWED, &sa, SecurityImpersonation, TokenImpersonation, &token2);
7053 ok(ret, "DuplicateTokenEx failed with error %u\n", GetLastError());
7055 ret = GetKernelObjectSecurity(token2, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7056 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7057 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7059 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
7060 ret = GetKernelObjectSecurity(token2, DACL_SECURITY_INFORMATION, sd2, size, &size);
7061 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7063 acl2 = (void *)0xdeadbeef;
7064 present = FALSE;
7065 defaulted = TRUE;
7066 ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
7067 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7068 ok(present, "acl2 not present\n");
7069 ok(acl2 != (void *)0xdeadbeef, "acl2 not set\n");
7070 ok(acl2->AceCount == 1, "Expected 1 ACE, got %d\n", acl2->AceCount);
7071 ok(!defaulted, "acl2 defaulted\n");
7073 ret = GetAce(acl2, 0, (void **)&ace);
7074 ok(ret, "GetAce failed with error %u\n", GetLastError());
7075 ok(ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE, "Unexpected ACE type %#x\n", ace->Header.AceType);
7076 ok(EqualSid(&ace->SidStart, psid), "Expected access allowed ACE\n");
7077 ok(ace->Header.AceFlags == NO_PROPAGATE_INHERIT_ACE,
7078 "Expected NO_PROPAGATE_INHERIT_ACE as flags, got %x\n", ace->Header.AceFlags);
7080 HeapFree(GetProcessHeap(), 0, sd2);
7082 /* Duplicate token without security attributes.
7083 * Tokens do not inherit the security descriptor in DuplicateToken. */
7084 ret = pDuplicateTokenEx(token2, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenImpersonation, &token3);
7085 ok(ret, "DuplicateTokenEx failed with error %u\n", GetLastError());
7087 ret = GetKernelObjectSecurity(token3, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7088 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7089 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7091 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
7092 ret = GetKernelObjectSecurity(token3, DACL_SECURITY_INFORMATION, sd2, size, &size);
7093 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7095 acl2 = (void *)0xdeadbeef;
7096 present = FALSE;
7097 defaulted = TRUE;
7098 ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
7099 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7100 todo_wine
7101 ok(present, "DACL not present\n");
7103 if (present)
7105 ok(acl2 != (void *)0xdeadbeef, "DACL not set\n");
7106 ok(!defaulted, "DACL defaulted\n");
7108 index = 0;
7109 found = FALSE;
7110 while (GetAce(acl2, index++, (void **)&ace))
7112 if (ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE && EqualSid(&ace->SidStart, psid))
7113 found = TRUE;
7115 ok(!found, "Access allowed ACE was inherited\n");
7118 HeapFree(GetProcessHeap(), 0, sd2);
7120 /* When creating a child process, the process does inherit the token of
7121 * the parent but not the DACL of the token */
7122 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7123 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7124 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7126 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
7127 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd2, size, &size);
7128 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7130 acl2 = (void *)0xdeadbeef;
7131 present = FALSE;
7132 defaulted = TRUE;
7133 ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
7134 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7135 ok(present, "DACL not present\n");
7136 ok(acl2 != (void *)0xdeadbeef, "DACL not set\n");
7137 ok(!defaulted, "DACL defaulted\n");
7139 exp_access.grfAccessPermissions = GENERIC_ALL;
7140 exp_access.grfAccessMode = GRANT_ACCESS;
7141 exp_access.grfInheritance = NO_PROPAGATE_INHERIT_ACE;
7142 exp_access.Trustee.pMultipleTrustee = NULL;
7143 exp_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
7144 exp_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
7145 exp_access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
7146 exp_access.Trustee.ptstrName = (void*)psid;
7148 retd = pSetEntriesInAclW(1, &exp_access, acl2, &acl_child);
7149 ok(retd == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", retd);
7151 memset(sd, 0, sizeof(buffer_sd));
7152 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7153 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
7155 ret = SetSecurityDescriptorDacl(sd, TRUE, acl_child, FALSE);
7156 ok(ret, "SetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7158 ret = SetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd);
7159 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
7161 /* The security label is also not inherited */
7162 if (pAddMandatoryAce)
7164 ret = InitializeAcl(acl, 256, ACL_REVISION);
7165 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
7167 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &low_level);
7168 ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
7170 memset(sd, 0, sizeof(buffer_sd));
7171 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7172 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
7174 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
7175 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
7177 ret = SetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd);
7178 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
7180 else
7181 win_skip("SYSTEM_MANDATORY_LABEL not supported\n");
7183 /* Start child process with our modified token */
7184 memset(&startup, 0, sizeof(startup));
7185 startup.cb = sizeof(startup);
7186 startup.dwFlags = STARTF_USESHOWWINDOW;
7187 startup.wShowWindow = SW_SHOWNORMAL;
7189 sprintf(buffer, "%s security test_token_sd", myARGV[0]);
7190 ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &info);
7191 ok(ret, "CreateProcess failed with error %u\n", GetLastError());
7192 wait_child_process(info.hProcess);
7193 CloseHandle(info.hProcess);
7194 CloseHandle(info.hThread);
7196 LocalFree(acl_child);
7197 HeapFree(GetProcessHeap(), 0, sd2);
7198 LocalFree(psid);
7200 CloseHandle(token3);
7201 CloseHandle(token2);
7202 CloseHandle(token);
7205 static void test_child_token_sd(void)
7207 static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
7208 {SECURITY_MANDATORY_LOW_RID}};
7209 SYSTEM_MANDATORY_LABEL_ACE *ace_label;
7210 BOOL ret, present, defaulted;
7211 ACCESS_ALLOWED_ACE *acc_ace;
7212 SECURITY_DESCRIPTOR *sd;
7213 DWORD size, i;
7214 HANDLE token;
7215 PSID psid;
7216 ACL *acl;
7218 ret = ConvertStringSidToSidA("S-1-5-6", &psid);
7219 ok(ret, "ConvertStringSidToSidA failed with error %u\n", GetLastError());
7221 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
7222 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
7224 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7225 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7226 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7228 sd = HeapAlloc(GetProcessHeap(), 0, size);
7229 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd, size, &size);
7230 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7232 acl = NULL;
7233 present = FALSE;
7234 defaulted = TRUE;
7235 ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
7236 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7237 ok(present, "DACL not present\n");
7238 ok(acl && acl != (void *)0xdeadbeef, "Got invalid DACL\n");
7239 ok(!defaulted, "DACL defaulted\n");
7241 ok(acl->AceCount, "Expected at least one ACE\n");
7242 for (i = 0; i < acl->AceCount; i++)
7244 ret = GetAce(acl, i, (void **)&acc_ace);
7245 ok(ret, "GetAce failed with error %u\n", GetLastError());
7246 ok(acc_ace->Header.AceType != ACCESS_ALLOWED_ACE_TYPE || !EqualSid(&acc_ace->SidStart, psid),
7247 "ACE inherited from the parent\n");
7250 LocalFree(psid);
7251 HeapFree(GetProcessHeap(), 0, sd);
7253 if (!pAddMandatoryAce)
7255 win_skip("SYSTEM_MANDATORY_LABEL not supported\n");
7256 return;
7259 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
7260 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7261 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7263 sd = HeapAlloc(GetProcessHeap(), 0, size);
7264 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd, size, &size);
7265 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7267 acl = NULL;
7268 present = FALSE;
7269 defaulted = TRUE;
7270 ret = GetSecurityDescriptorSacl(sd, &present, &acl, &defaulted);
7271 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
7272 ok(present, "SACL not present\n");
7273 ok(acl && acl != (void *)0xdeadbeef, "Got invalid SACL\n");
7274 ok(!defaulted, "SACL defaulted\n");
7275 ok(acl->AceCount == 1, "Expected exactly one ACE\n");
7276 ret = GetAce(acl, 0, (void **)&ace_label);
7277 ok(ret, "GetAce failed with error %u\n", GetLastError());
7278 ok(ace_label->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE,
7279 "Unexpected ACE type %#x\n", ace_label->Header.AceType);
7280 ok(!EqualSid(&ace_label->SidStart, &low_level),
7281 "Low integrity level should not have been inherited\n");
7283 HeapFree(GetProcessHeap(), 0, sd);
7286 static void test_GetExplicitEntriesFromAclW(void)
7288 static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
7289 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
7290 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
7291 PSID everyone_sid = NULL, users_sid = NULL;
7292 EXPLICIT_ACCESSW access;
7293 EXPLICIT_ACCESSW *access2;
7294 PACL new_acl, old_acl = NULL;
7295 ULONG count;
7296 DWORD res;
7298 if (!pGetExplicitEntriesFromAclW)
7300 win_skip("GetExplicitEntriesFromAclW is not available\n");
7301 return;
7304 if (!pSetEntriesInAclW)
7306 win_skip("SetEntriesInAclW is not available\n");
7307 return;
7310 old_acl = HeapAlloc(GetProcessHeap(), 0, 256);
7311 res = InitializeAcl(old_acl, 256, ACL_REVISION);
7312 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
7314 win_skip("ACLs not implemented - skipping tests\n");
7315 HeapFree(GetProcessHeap(), 0, old_acl);
7316 return;
7318 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
7320 res = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyone_sid);
7321 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
7323 res = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
7324 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &users_sid);
7325 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
7327 res = AddAccessAllowedAce(old_acl, ACL_REVISION, KEY_READ, users_sid);
7328 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
7330 access2 = NULL;
7331 res = pGetExplicitEntriesFromAclW(old_acl, &count, &access2);
7332 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7333 ok(count == 1, "Expected count == 1, got %d\n", count);
7334 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7335 ok(access2[0].grfAccessPermissions == KEY_READ, "Expected KEY_READ, got %d\n", access2[0].grfAccessPermissions);
7336 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7337 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7338 ok(EqualSid(access2[0].Trustee.ptstrName, users_sid), "Expected equal SIDs\n");
7339 LocalFree(access2);
7341 access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
7342 access.Trustee.pMultipleTrustee = NULL;
7344 access.grfAccessPermissions = KEY_WRITE;
7345 access.grfAccessMode = GRANT_ACCESS;
7346 access.grfInheritance = NO_INHERITANCE;
7347 access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
7348 access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
7349 access.Trustee.ptstrName = everyone_sid;
7350 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7351 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7352 ok(new_acl != NULL, "returned acl was NULL\n");
7354 access2 = NULL;
7355 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7356 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7357 ok(count == 2, "Expected count == 2, got %d\n", count);
7358 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7359 ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
7360 ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
7361 "Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
7362 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7363 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7364 ok(EqualSid(access2[0].Trustee.ptstrName, everyone_sid), "Expected equal SIDs\n");
7365 LocalFree(access2);
7366 LocalFree(new_acl);
7368 access.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
7369 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7370 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7371 ok(new_acl != NULL, "returned acl was NULL\n");
7373 access2 = NULL;
7374 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7375 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7376 ok(count == 2, "Expected count == 2, got %d\n", count);
7377 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7378 ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
7379 ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
7380 "Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
7381 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7382 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7383 ok(EqualSid(access2[0].Trustee.ptstrName, everyone_sid), "Expected equal SIDs\n");
7384 LocalFree(access2);
7385 LocalFree(new_acl);
7387 access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
7388 access.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
7389 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7390 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7391 ok(new_acl != NULL, "returned acl was NULL\n");
7393 access2 = NULL;
7394 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7395 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7396 ok(count == 2, "Expected count == 2, got %d\n", count);
7397 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7398 ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
7399 ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
7400 "Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
7401 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7402 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7403 LocalFree(access2);
7404 LocalFree(new_acl);
7406 access.grfAccessMode = REVOKE_ACCESS;
7407 access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
7408 access.Trustee.ptstrName = users_sid;
7409 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7410 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7411 ok(new_acl != NULL, "returned acl was NULL\n");
7413 access2 = (void *)0xdeadbeef;
7414 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7415 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7416 ok(count == 0, "Expected count == 0, got %d\n", count);
7417 ok(access2 == NULL, "access2 was not NULL\n");
7418 LocalFree(new_acl);
7420 FreeSid(users_sid);
7421 FreeSid(everyone_sid);
7422 HeapFree(GetProcessHeap(), 0, old_acl);
7425 static void test_BuildSecurityDescriptorW(void)
7427 SECURITY_DESCRIPTOR old_sd, *new_sd, *rel_sd;
7428 ULONG new_sd_size;
7429 DWORD buf_size;
7430 char buf[1024];
7431 BOOL success;
7432 DWORD ret;
7434 InitializeSecurityDescriptor(&old_sd, SECURITY_DESCRIPTOR_REVISION);
7436 buf_size = sizeof(buf);
7437 rel_sd = (SECURITY_DESCRIPTOR *)buf;
7438 success = MakeSelfRelativeSD(&old_sd, rel_sd, &buf_size);
7439 ok(success, "MakeSelfRelativeSD failed with %u\n", GetLastError());
7441 new_sd = NULL;
7442 new_sd_size = 0;
7443 ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, NULL, &new_sd_size, (void **)&new_sd);
7444 ok(ret == ERROR_SUCCESS, "BuildSecurityDescriptor failed with %u\n", ret);
7445 ok(new_sd != NULL, "expected new_sd != NULL\n");
7446 LocalFree(new_sd);
7448 new_sd = (void *)0xdeadbeef;
7449 ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, &old_sd, &new_sd_size, (void **)&new_sd);
7450 ok(ret == ERROR_INVALID_SECURITY_DESCR, "expected ERROR_INVALID_SECURITY_DESCR, got %u\n", ret);
7451 ok(new_sd == (void *)0xdeadbeef, "expected new_sd == 0xdeadbeef, got %p\n", new_sd);
7453 new_sd = NULL;
7454 new_sd_size = 0;
7455 ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, rel_sd, &new_sd_size, (void **)&new_sd);
7456 ok(ret == ERROR_SUCCESS, "BuildSecurityDescriptor failed with %u\n", ret);
7457 ok(new_sd != NULL, "expected new_sd != NULL\n");
7458 LocalFree(new_sd);
7461 static void test_EqualDomainSid(void)
7463 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
7464 char sid_buffer[SECURITY_MAX_SID_SIZE], sid_buffer2[SECURITY_MAX_SID_SIZE];
7465 PSID domainsid, sid = sid_buffer, sid2 = sid_buffer2;
7466 DWORD size;
7467 BOOL ret, equal;
7468 unsigned int i;
7470 if (!pEqualDomainSid)
7472 win_skip("EqualDomainSid not available\n");
7473 return;
7476 ret = AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
7477 ok(ret, "AllocateAndInitializeSid error %u\n", GetLastError());
7479 SetLastError(0xdeadbeef);
7480 ret = pEqualDomainSid(NULL, NULL, NULL);
7481 ok(!ret, "got %d\n", ret);
7482 ok(GetLastError() == ERROR_INVALID_SID, "got %u\n", GetLastError());
7484 SetLastError(0xdeadbeef);
7485 ret = pEqualDomainSid(domainsid, domainsid, NULL);
7486 ok(!ret, "got %d\n", ret);
7487 ok(GetLastError() == ERROR_INVALID_PARAMETER, "got %u\n", GetLastError());
7489 for (i = 0; i < ARRAY_SIZE(well_known_sid_values); i++)
7491 SID *pisid = sid;
7493 size = sizeof(sid_buffer);
7494 if (!CreateWellKnownSid(i, NULL, sid, &size))
7496 trace("Well known SID %u not supported\n", i);
7497 continue;
7500 equal = 0xdeadbeef;
7501 SetLastError(0xdeadbeef);
7502 ret = pEqualDomainSid(sid, domainsid, &equal);
7503 if (pisid->SubAuthority[0] != SECURITY_BUILTIN_DOMAIN_RID)
7505 ok(!ret, "%u: got %d\n", i, ret);
7506 ok(GetLastError() == ERROR_NON_DOMAIN_SID, "%u: got %u\n", i, GetLastError());
7507 ok(equal == 0xdeadbeef, "%u: got %d\n", i, equal);
7508 continue;
7511 ok(ret, "%u: got %d\n", i, ret);
7512 ok(GetLastError() == 0, "%u: got %u\n", i, GetLastError());
7513 ok(equal == 0, "%u: got %d\n", i, equal);
7515 size = sizeof(sid_buffer2);
7516 ret = CreateWellKnownSid(i, well_known_sid_values[i].without_domain ? NULL : domainsid, sid2, &size);
7517 ok(ret, "%u: CreateWellKnownSid error %u\n", i, GetLastError());
7519 equal = 0xdeadbeef;
7520 SetLastError(0xdeadbeef);
7521 ret = pEqualDomainSid(sid, sid2, &equal);
7522 ok(ret, "%u: got %d\n", i, ret);
7523 ok(GetLastError() == 0, "%u: got %u\n", i, GetLastError());
7524 ok(equal == 1, "%u: got %d\n", i, equal);
7527 FreeSid(domainsid);
7530 START_TEST(security)
7532 init();
7533 if (!hmod) return;
7535 if (myARGC >= 3)
7537 if (!strcmp(myARGV[2], "test_token_sd"))
7538 test_child_token_sd();
7539 else
7540 test_process_security_child();
7541 return;
7543 test_kernel_objects_security();
7544 test_sid();
7545 test_trustee();
7546 test_luid();
7547 test_CreateWellKnownSid();
7548 test_FileSecurity();
7549 test_AccessCheck();
7550 test_token_attr();
7551 test_GetTokenInformation();
7552 test_LookupAccountSid();
7553 test_LookupAccountName();
7554 test_security_descriptor();
7555 test_process_security();
7556 test_impersonation_level();
7557 test_SetEntriesInAclW();
7558 test_SetEntriesInAclA();
7559 test_CreateDirectoryA();
7560 test_GetNamedSecurityInfoA();
7561 test_ConvertStringSecurityDescriptor();
7562 test_ConvertSecurityDescriptorToString();
7563 test_PrivateObjectSecurity();
7564 test_acls();
7565 test_GetWindowsAccountDomainSid();
7566 test_EqualDomainSid();
7567 test_GetSecurityInfo();
7568 test_GetSidSubAuthority();
7569 test_CheckTokenMembership();
7570 test_EqualSid();
7571 test_GetUserNameA();
7572 test_GetUserNameW();
7573 test_CreateRestrictedToken();
7574 test_TokenIntegrityLevel();
7575 test_default_dacl_owner_sid();
7576 test_AdjustTokenPrivileges();
7577 test_AddAce();
7578 test_AddMandatoryAce();
7579 test_system_security_access();
7580 test_GetSidIdentifierAuthority();
7581 test_pseudo_tokens();
7582 test_maximum_allowed();
7583 test_token_label();
7584 test_GetExplicitEntriesFromAclW();
7585 test_BuildSecurityDescriptorW();
7587 /* Must be the last test, modifies process token */
7588 test_token_security_descriptor();