server: Create primary group using DOMAIN_GROUP_RID_USERS.
[wine.git] / dlls / advapi32 / tests / security.c
blobaee458742574dc8f4310b95a05a97d3ac34d624d
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 *pMakeSelfRelativeSD)( PSECURITY_DESCRIPTOR, PSECURITY_DESCRIPTOR, LPDWORD );
84 static BOOL (WINAPI *pConvertStringSidToSidA)( LPCSTR str, PSID pSid );
85 static BOOL (WINAPI *pCheckTokenMembership)(HANDLE, PSID, PBOOL);
86 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
87 PSECURITY_DESCRIPTOR*, PULONG );
88 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorW)(LPCWSTR, DWORD,
89 PSECURITY_DESCRIPTOR*, PULONG );
90 static BOOL (WINAPI *pConvertSecurityDescriptorToStringSecurityDescriptorA)(PSECURITY_DESCRIPTOR, DWORD,
91 SECURITY_INFORMATION, LPSTR *, PULONG );
92 static BOOL (WINAPI *pGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
93 PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
94 static BOOL (WINAPI *pSetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
95 PSECURITY_DESCRIPTOR);
96 static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
97 PSID*, PSID*, PACL*, PACL*,
98 PSECURITY_DESCRIPTOR*);
99 static DWORD (WINAPI *pSetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
100 PSID, PSID, PACL, PACL);
101 static PDWORD (WINAPI *pGetSidSubAuthority)(PSID, DWORD);
102 static PUCHAR (WINAPI *pGetSidSubAuthorityCount)(PSID);
103 static BOOL (WINAPI *pIsValidSid)(PSID);
104 static DWORD (WINAPI *pRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
105 static BOOL (WINAPI *pCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
106 static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
107 SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
109 static NTSTATUS (WINAPI *pLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
110 static NTSTATUS (WINAPI *pLsaClose)(LSA_HANDLE);
111 static NTSTATUS (WINAPI *pLsaFreeMemory)(PVOID);
112 static NTSTATUS (WINAPI *pLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
113 static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
114 static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
115 static DWORD (WINAPI *pSetEntriesInAclA)(ULONG, PEXPLICIT_ACCESSA, PACL, PACL*);
116 static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
117 SECURITY_DESCRIPTOR_CONTROL);
118 static DWORD (WINAPI *pGetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
119 PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
120 static DWORD (WINAPI *pSetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
121 PSID, PSID, PACL, PACL);
122 static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
123 PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
124 static BOOL (WINAPI *pCreateRestrictedToken)(HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD,
125 PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
126 static BOOL (WINAPI *pGetAclInformation)(PACL,LPVOID,DWORD,ACL_INFORMATION_CLASS);
127 static BOOL (WINAPI *pGetAce)(PACL,DWORD,LPVOID*);
128 static NTSTATUS (WINAPI *pNtSetSecurityObject)(HANDLE,SECURITY_INFORMATION,PSECURITY_DESCRIPTOR);
129 static NTSTATUS (WINAPI *pNtCreateFile)(PHANDLE,ACCESS_MASK,POBJECT_ATTRIBUTES,PIO_STATUS_BLOCK,PLARGE_INTEGER,ULONG,ULONG,ULONG,ULONG,PVOID,ULONG);
130 static BOOL (WINAPI *pRtlDosPathNameToNtPathName_U)(LPCWSTR,PUNICODE_STRING,PWSTR*,CURDIR*);
131 static NTSTATUS (WINAPI *pRtlAnsiStringToUnicodeString)(PUNICODE_STRING,PCANSI_STRING,BOOLEAN);
132 static BOOL (WINAPI *pGetWindowsAccountDomainSid)(PSID,PSID,DWORD*);
133 static void (WINAPI *pRtlInitAnsiString)(PANSI_STRING,PCSZ);
134 static NTSTATUS (WINAPI *pRtlFreeUnicodeString)(PUNICODE_STRING);
135 static PSID_IDENTIFIER_AUTHORITY (WINAPI *pGetSidIdentifierAuthority)(PSID);
136 static DWORD (WINAPI *pGetExplicitEntriesFromAclW)(PACL,PULONG,PEXPLICIT_ACCESSW*);
138 static HMODULE hmod;
139 static int myARGC;
140 static char** myARGV;
142 #define SID_SLOTS 4
143 static char debugsid_str[SID_SLOTS][256];
144 static int debugsid_index = 0;
145 static const char* debugstr_sid(PSID sid)
147 LPSTR sidstr;
148 DWORD le = GetLastError();
149 char* res = debugsid_str[debugsid_index];
150 debugsid_index = (debugsid_index + 1) % SID_SLOTS;
152 if (!ConvertSidToStringSidA(sid, &sidstr))
153 sprintf(res, "ConvertSidToStringSidA failed le=%u", GetLastError());
154 else if (strlen(sidstr) > sizeof(*debugsid_str) - 1)
156 memcpy(res, sidstr, sizeof(*debugsid_str) - 4);
157 strcpy(res + sizeof(*debugsid_str) - 4, "...");
158 LocalFree(sidstr);
160 else
162 strcpy(res, sidstr);
163 LocalFree(sidstr);
165 /* Restore the last error in case ConvertSidToStringSidA() modified it */
166 SetLastError(le);
167 return res;
170 struct sidRef
172 SID_IDENTIFIER_AUTHORITY auth;
173 const char *refStr;
176 static void init(void)
178 HMODULE hntdll;
180 hntdll = GetModuleHandleA("ntdll.dll");
181 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
182 pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
183 pNtSetSecurityObject = (void *)GetProcAddress(hntdll, "NtSetSecurityObject");
184 pNtCreateFile = (void *)GetProcAddress(hntdll, "NtCreateFile");
185 pRtlDosPathNameToNtPathName_U = (void *)GetProcAddress(hntdll, "RtlDosPathNameToNtPathName_U");
186 pRtlAnsiStringToUnicodeString = (void *)GetProcAddress(hntdll, "RtlAnsiStringToUnicodeString");
187 pRtlInitAnsiString = (void *)GetProcAddress(hntdll, "RtlInitAnsiString");
188 pRtlFreeUnicodeString = (void *)GetProcAddress(hntdll, "RtlFreeUnicodeString");
190 hmod = GetModuleHandleA("advapi32.dll");
191 pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
192 pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
193 pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
194 pAddMandatoryAce = (void *)GetProcAddress(hmod, "AddMandatoryAce");
195 pCheckTokenMembership = (void *)GetProcAddress(hmod, "CheckTokenMembership");
196 pConvertStringSecurityDescriptorToSecurityDescriptorA =
197 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
198 pConvertStringSecurityDescriptorToSecurityDescriptorW =
199 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
200 pConvertSecurityDescriptorToStringSecurityDescriptorA =
201 (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
202 pGetFileSecurityA = (void *)GetProcAddress(hmod, "GetFileSecurityA" );
203 pSetFileSecurityA = (void *)GetProcAddress(hmod, "SetFileSecurityA" );
204 pCreateWellKnownSid = (void *)GetProcAddress( hmod, "CreateWellKnownSid" );
205 pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
206 pSetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "SetNamedSecurityInfoA");
207 pGetSidSubAuthority = (void *)GetProcAddress(hmod, "GetSidSubAuthority");
208 pGetSidSubAuthorityCount = (void *)GetProcAddress(hmod, "GetSidSubAuthorityCount");
209 pIsValidSid = (void *)GetProcAddress(hmod, "IsValidSid");
210 pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
211 pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
212 pSetEntriesInAclA = (void *)GetProcAddress(hmod, "SetEntriesInAclA");
213 pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
214 pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
215 pSetSecurityInfo = (void *)GetProcAddress(hmod, "SetSecurityInfo");
216 pCreateRestrictedToken = (void *)GetProcAddress(hmod, "CreateRestrictedToken");
217 pConvertStringSidToSidA = (void *)GetProcAddress(hmod, "ConvertStringSidToSidA");
218 pGetAclInformation = (void *)GetProcAddress(hmod, "GetAclInformation");
219 pGetAce = (void *)GetProcAddress(hmod, "GetAce");
220 pGetWindowsAccountDomainSid = (void *)GetProcAddress(hmod, "GetWindowsAccountDomainSid");
221 pGetSidIdentifierAuthority = (void *)GetProcAddress(hmod, "GetSidIdentifierAuthority");
222 pDuplicateTokenEx = (void *)GetProcAddress(hmod, "DuplicateTokenEx");
223 pGetExplicitEntriesFromAclW = (void *)GetProcAddress(hmod, "GetExplicitEntriesFromAclW");
225 myARGC = winetest_get_mainargs( &myARGV );
228 static SECURITY_DESCRIPTOR* test_get_security_descriptor(HANDLE handle, int line)
230 /* use HeapFree(GetProcessHeap(), 0, sd); when done */
231 DWORD ret, length, needed;
232 SECURITY_DESCRIPTOR *sd;
234 needed = 0xdeadbeef;
235 SetLastError(0xdeadbeef);
236 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
237 NULL, 0, &needed);
238 ok_(__FILE__, line)(!ret, "GetKernelObjectSecurity should fail\n");
239 ok_(__FILE__, line)(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
240 ok_(__FILE__, line)(needed != 0xdeadbeef, "GetKernelObjectSecurity should return required buffer length\n");
242 length = needed;
243 sd = HeapAlloc(GetProcessHeap(), 0, length);
245 needed = 0xdeadbeef;
246 SetLastError(0xdeadbeef);
247 ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
248 sd, length, &needed);
249 ok_(__FILE__, line)(ret, "GetKernelObjectSecurity error %d\n", GetLastError());
250 ok_(__FILE__, line)(needed == length || needed == 0 /* file, pipe */, "GetKernelObjectSecurity should return %u instead of %u\n", length, needed);
251 return sd;
254 static void test_owner_equal(HANDLE Handle, PSID expected, int line)
256 BOOL res;
257 SECURITY_DESCRIPTOR *queriedSD = NULL;
258 PSID owner;
259 BOOL owner_defaulted;
261 queriedSD = test_get_security_descriptor( Handle, line );
263 res = GetSecurityDescriptorOwner(queriedSD, &owner, &owner_defaulted);
264 ok_(__FILE__, line)(res, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
266 ok_(__FILE__, line)(EqualSid(owner, expected), "Owner SIDs are not equal %s != %s\n",
267 debugstr_sid(owner), debugstr_sid(expected));
268 ok_(__FILE__, line)(!owner_defaulted, "Defaulted is true\n");
270 HeapFree(GetProcessHeap(), 0, queriedSD);
273 static void test_group_equal(HANDLE Handle, PSID expected, int line)
275 BOOL res;
276 SECURITY_DESCRIPTOR *queriedSD = NULL;
277 PSID group;
278 BOOL group_defaulted;
280 queriedSD = test_get_security_descriptor( Handle, line );
282 res = GetSecurityDescriptorGroup(queriedSD, &group, &group_defaulted);
283 ok_(__FILE__, line)(res, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
285 ok_(__FILE__, line)(EqualSid(group, expected), "Group SIDs are not equal %s != %s\n",
286 debugstr_sid(group), debugstr_sid(expected));
287 ok_(__FILE__, line)(!group_defaulted, "Defaulted is true\n");
289 HeapFree(GetProcessHeap(), 0, queriedSD);
292 static void test_sid(void)
294 struct sidRef refs[] = {
295 { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
296 { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
297 { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
298 { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
299 { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
300 { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
302 static const struct
304 const char *name;
305 const char *sid;
306 unsigned int optional;
308 str_to_sid_tests[] =
310 { "WD", "S-1-1-0" },
311 { "CO", "S-1-3-0" },
312 { "CG", "S-1-3-1" },
313 { "OW", "S-1-3-4", 1 }, /* Vista+ */
314 { "NU", "S-1-5-2" },
315 { "IU", "S-1-5-4" },
316 { "SU", "S-1-5-6" },
317 { "AN", "S-1-5-7" },
318 { "ED", "S-1-5-9" },
319 { "PS", "S-1-5-10" },
320 { "AU", "S-1-5-11" },
321 { "RC", "S-1-5-12" },
322 { "SY", "S-1-5-18" },
323 { "LS", "S-1-5-19" },
324 { "NS", "S-1-5-20" },
325 { "LA", "S-1-5-21-*-*-*-500" },
326 { "LG", "S-1-5-21-*-*-*-501" },
327 { "BO", "S-1-5-32-551" },
328 { "BA", "S-1-5-32-544" },
329 { "BU", "S-1-5-32-545" },
330 { "BG", "S-1-5-32-546" },
331 { "PU", "S-1-5-32-547" },
332 { "AO", "S-1-5-32-548" },
333 { "SO", "S-1-5-32-549" },
334 { "PO", "S-1-5-32-550" },
335 { "RE", "S-1-5-32-552" },
336 { "RU", "S-1-5-32-554" },
337 { "RD", "S-1-5-32-555" },
338 { "NO", "S-1-5-32-556" },
339 { "AC", "S-1-15-2-1", 1 }, /* Win8+ */
340 { "CA", "", 1 },
341 { "DA", "", 1 },
342 { "DC", "", 1 },
343 { "DD", "", 1 },
344 { "DG", "", 1 },
345 { "DU", "", 1 },
346 { "EA", "", 1 },
347 { "PA", "", 1 },
348 { "RS", "", 1 },
349 { "SA", "", 1 },
352 const char noSubAuthStr[] = "S-1-5";
353 unsigned int i;
354 PSID psid = NULL;
355 SID *pisid;
356 BOOL r, ret;
357 LPSTR str = NULL;
359 if( !pConvertStringSidToSidA )
361 win_skip("ConvertSidToStringSidA or ConvertStringSidToSidA not available\n");
362 return;
365 r = pConvertStringSidToSidA( NULL, NULL );
366 ok( !r, "expected failure with NULL parameters\n" );
367 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
368 return;
369 ok( GetLastError() == ERROR_INVALID_PARAMETER,
370 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
371 GetLastError() );
373 r = pConvertStringSidToSidA( refs[0].refStr, NULL );
374 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
375 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
376 GetLastError() );
378 r = pConvertStringSidToSidA( NULL, &str );
379 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
380 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
381 GetLastError() );
383 r = pConvertStringSidToSidA( noSubAuthStr, &psid );
384 ok( !r,
385 "expected failure with no sub authorities\n" );
386 ok( GetLastError() == ERROR_INVALID_SID,
387 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
388 GetLastError() );
390 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
391 pisid = psid;
392 ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
393 ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expected 21, got %d\n", pisid->SubAuthority[0]);
394 ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expected 4576, got %d\n", pisid->SubAuthority[3]);
395 LocalFree(str);
396 LocalFree(psid);
398 for( i = 0; i < ARRAY_SIZE(refs); i++ )
400 r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
401 &psid );
402 ok( r, "failed to allocate sid\n" );
403 r = ConvertSidToStringSidA( psid, &str );
404 ok( r, "failed to convert sid\n" );
405 if (r)
407 ok( !strcmp( str, refs[i].refStr ),
408 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
409 LocalFree( str );
411 if( psid )
412 FreeSid( psid );
414 r = pConvertStringSidToSidA( refs[i].refStr, &psid );
415 ok( r, "failed to parse sid string\n" );
416 pisid = psid;
417 ok( pisid &&
418 !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
419 sizeof(refs[i].auth) ),
420 "string sid %s didn't parse to expected value\n"
421 "(got 0x%04x%08x, expected 0x%04x%08x)\n",
422 refs[i].refStr,
423 MAKEWORD( pisid->IdentifierAuthority.Value[1],
424 pisid->IdentifierAuthority.Value[0] ),
425 MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
426 pisid->IdentifierAuthority.Value[4] ),
427 MAKEWORD( pisid->IdentifierAuthority.Value[3],
428 pisid->IdentifierAuthority.Value[2] ) ),
429 MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
430 MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
431 MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
432 if( psid )
433 LocalFree( psid );
436 for (i = 0; i < ARRAY_SIZE(str_to_sid_tests); i++)
438 char *str;
440 ret = ConvertStringSidToSidA(str_to_sid_tests[i].name, &psid);
441 if (!ret && str_to_sid_tests[i].optional)
443 skip("%u: failed to convert %s.\n", i, str_to_sid_tests[i].name);
444 continue;
446 ok(ret, "%u: failed to convert string to sid.\n", i);
448 if (str_to_sid_tests[i].optional || !strcmp(str_to_sid_tests[i].name, "LA") ||
449 !strcmp(str_to_sid_tests[i].name, "LG"))
451 LocalFree(psid);
452 continue;
455 ret = ConvertSidToStringSidA(psid, &str);
456 ok(ret, "%u: failed to convert SID to string.\n", i);
457 ok(!strcmp(str, str_to_sid_tests[i].sid), "%u: unexpected sid %s.\n", i, str);
458 LocalFree(psid);
459 LocalFree(str);
463 static void test_trustee(void)
465 GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
466 GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
467 GUID ZeroGuid;
468 OBJECTS_AND_NAME_A oan;
469 OBJECTS_AND_SID oas;
470 TRUSTEEA trustee;
471 PSID psid;
472 char szObjectTypeName[] = "ObjectTypeName";
473 char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
474 char szTrusteeName[] = "szTrusteeName";
475 SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
477 memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
479 pBuildTrusteeWithSidA = (void *)GetProcAddress( hmod, "BuildTrusteeWithSidA" );
480 pBuildTrusteeWithNameA = (void *)GetProcAddress( hmod, "BuildTrusteeWithNameA" );
481 pBuildTrusteeWithObjectsAndNameA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
482 pBuildTrusteeWithObjectsAndSidA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
483 pGetTrusteeNameA = (void *)GetProcAddress (hmod, "GetTrusteeNameA" );
484 if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
485 !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
486 !pGetTrusteeNameA )
487 return;
489 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
491 trace( "failed to init SID\n" );
492 return;
495 /* test BuildTrusteeWithSidA */
496 memset( &trustee, 0xff, sizeof trustee );
497 pBuildTrusteeWithSidA( &trustee, psid );
499 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
500 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
501 "MultipleTrusteeOperation wrong\n");
502 ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
503 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
504 ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
506 /* test BuildTrusteeWithObjectsAndSidA (test 1) */
507 memset( &trustee, 0xff, sizeof trustee );
508 memset( &oas, 0xff, sizeof(oas) );
509 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
510 &InheritedObjectType, psid);
512 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
513 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
514 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
515 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
516 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
518 ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
519 ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
520 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
521 ok(oas.pSid == psid, "pSid wrong\n");
523 /* test GetTrusteeNameA */
524 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
526 /* test BuildTrusteeWithObjectsAndSidA (test 2) */
527 memset( &trustee, 0xff, sizeof trustee );
528 memset( &oas, 0xff, sizeof(oas) );
529 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
530 &InheritedObjectType, psid);
532 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
533 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
534 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
535 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
536 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
538 ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
539 ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
540 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
541 ok(oas.pSid == psid, "pSid wrong\n");
543 FreeSid( psid );
545 /* test BuildTrusteeWithNameA */
546 memset( &trustee, 0xff, sizeof trustee );
547 pBuildTrusteeWithNameA( &trustee, szTrusteeName );
549 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
550 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
551 "MultipleTrusteeOperation wrong\n");
552 ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
553 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
554 ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
556 /* test BuildTrusteeWithObjectsAndNameA (test 1) */
557 memset( &trustee, 0xff, sizeof trustee );
558 memset( &oan, 0xff, sizeof(oan) );
559 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
560 szInheritedObjectTypeName, szTrusteeName);
562 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
563 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
564 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
565 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
566 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
568 ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
569 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
570 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
571 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
573 /* test GetTrusteeNameA */
574 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
576 /* test BuildTrusteeWithObjectsAndNameA (test 2) */
577 memset( &trustee, 0xff, sizeof trustee );
578 memset( &oan, 0xff, sizeof(oan) );
579 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
580 szInheritedObjectTypeName, szTrusteeName);
582 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
583 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
584 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
585 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
586 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
588 ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
589 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
590 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
591 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
593 /* test BuildTrusteeWithObjectsAndNameA (test 3) */
594 memset( &trustee, 0xff, sizeof trustee );
595 memset( &oan, 0xff, sizeof(oan) );
596 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
597 NULL, szTrusteeName);
599 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
600 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
601 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
602 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
603 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
605 ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
606 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
607 ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
608 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
611 /* If the first isn't defined, assume none is */
612 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
613 #define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
614 #define SE_CREATE_TOKEN_PRIVILEGE 2L
615 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
616 #define SE_LOCK_MEMORY_PRIVILEGE 4L
617 #define SE_INCREASE_QUOTA_PRIVILEGE 5L
618 #define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
619 #define SE_TCB_PRIVILEGE 7L
620 #define SE_SECURITY_PRIVILEGE 8L
621 #define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
622 #define SE_LOAD_DRIVER_PRIVILEGE 10L
623 #define SE_SYSTEM_PROFILE_PRIVILEGE 11L
624 #define SE_SYSTEMTIME_PRIVILEGE 12L
625 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
626 #define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
627 #define SE_CREATE_PAGEFILE_PRIVILEGE 15L
628 #define SE_CREATE_PERMANENT_PRIVILEGE 16L
629 #define SE_BACKUP_PRIVILEGE 17L
630 #define SE_RESTORE_PRIVILEGE 18L
631 #define SE_SHUTDOWN_PRIVILEGE 19L
632 #define SE_DEBUG_PRIVILEGE 20L
633 #define SE_AUDIT_PRIVILEGE 21L
634 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
635 #define SE_CHANGE_NOTIFY_PRIVILEGE 23L
636 #define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
637 #define SE_UNDOCK_PRIVILEGE 25L
638 #define SE_SYNC_AGENT_PRIVILEGE 26L
639 #define SE_ENABLE_DELEGATION_PRIVILEGE 27L
640 #define SE_MANAGE_VOLUME_PRIVILEGE 28L
641 #define SE_IMPERSONATE_PRIVILEGE 29L
642 #define SE_CREATE_GLOBAL_PRIVILEGE 30L
643 #define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
644 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
646 static void test_allocateLuid(void)
648 BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
649 LUID luid1, luid2;
650 BOOL ret;
652 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
653 if (!pAllocateLocallyUniqueId) return;
655 ret = pAllocateLocallyUniqueId(&luid1);
656 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
657 return;
659 ok(ret,
660 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
661 ret = pAllocateLocallyUniqueId(&luid2);
662 ok( ret,
663 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
664 ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
665 "AllocateLocallyUniqueId returned a well-known LUID\n");
666 ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
667 "AllocateLocallyUniqueId returned non-unique LUIDs\n");
668 ret = pAllocateLocallyUniqueId(NULL);
669 ok( !ret && GetLastError() == ERROR_NOACCESS,
670 "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
671 GetLastError());
674 static void test_lookupPrivilegeName(void)
676 BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
677 char buf[MAX_PATH]; /* arbitrary, seems long enough */
678 DWORD cchName = sizeof(buf);
679 LUID luid = { 0, 0 };
680 LONG i;
681 BOOL ret;
683 /* check whether it's available first */
684 pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
685 if (!pLookupPrivilegeNameA) return;
686 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
687 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
688 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
689 return;
691 /* check with a short buffer */
692 cchName = 0;
693 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
694 ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
695 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
696 "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
697 GetLastError());
698 ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
699 "LookupPrivilegeNameA returned an incorrect required length for\n"
700 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
701 lstrlenA("SeCreateTokenPrivilege") + 1);
702 /* check a known value and its returned length on success */
703 cchName = sizeof(buf);
704 ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
705 cchName == strlen("SeCreateTokenPrivilege"),
706 "LookupPrivilegeNameA returned an incorrect output length for\n"
707 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
708 (int)strlen("SeCreateTokenPrivilege"));
709 /* check known values */
710 for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
712 luid.LowPart = i;
713 cchName = sizeof(buf);
714 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
715 ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
716 "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
718 /* check a bogus LUID */
719 luid.LowPart = 0xdeadbeef;
720 cchName = sizeof(buf);
721 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
722 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
723 "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
724 GetLastError());
725 /* check on a bogus system */
726 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
727 cchName = sizeof(buf);
728 ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
729 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
730 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
731 "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
732 GetLastError());
735 struct NameToLUID
737 const char *name;
738 DWORD lowPart;
741 static void test_lookupPrivilegeValue(void)
743 static const struct NameToLUID privs[] = {
744 { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
745 { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
746 { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
747 { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
748 { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
749 { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
750 { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
751 { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
752 { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
753 { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
754 { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
755 { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
756 { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
757 { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
758 { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
759 { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
760 { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
761 { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
762 { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
763 { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
764 { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
765 { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
766 { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
767 { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
768 { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
769 { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
770 { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
771 { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
772 { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
774 BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
775 unsigned int i;
776 LUID luid;
777 BOOL ret;
779 /* check whether it's available first */
780 pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
781 if (!pLookupPrivilegeValueA) return;
782 ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
783 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
784 return;
786 /* check a bogus system name */
787 ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
788 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
789 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
790 "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
791 GetLastError());
792 /* check a NULL string */
793 ret = pLookupPrivilegeValueA(NULL, 0, &luid);
794 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
795 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
796 GetLastError());
797 /* check a bogus privilege name */
798 ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
799 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
800 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
801 GetLastError());
802 /* check case insensitive */
803 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
804 ok( ret,
805 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
806 GetLastError());
807 for (i = 0; i < ARRAY_SIZE(privs); i++)
809 /* Not all privileges are implemented on all Windows versions, so
810 * don't worry if the call fails
812 if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
814 ok(luid.LowPart == privs[i].lowPart,
815 "LookupPrivilegeValueA returned an invalid LUID for %s\n",
816 privs[i].name);
821 static void test_luid(void)
823 test_allocateLuid();
824 test_lookupPrivilegeName();
825 test_lookupPrivilegeValue();
828 static void test_FileSecurity(void)
830 char wintmpdir [MAX_PATH];
831 char path [MAX_PATH];
832 char file [MAX_PATH];
833 HANDLE fh, token;
834 DWORD sdSize, retSize, rc, granted, priv_set_len;
835 PRIVILEGE_SET priv_set;
836 BOOL status;
837 BYTE *sd;
838 GENERIC_MAPPING mapping = { FILE_READ_DATA, FILE_WRITE_DATA, FILE_EXECUTE, FILE_ALL_ACCESS };
839 const SECURITY_INFORMATION request = OWNER_SECURITY_INFORMATION
840 | GROUP_SECURITY_INFORMATION
841 | DACL_SECURITY_INFORMATION;
843 if (!pGetFileSecurityA) {
844 win_skip ("GetFileSecurity is not available\n");
845 return;
848 if (!pSetFileSecurityA) {
849 win_skip ("SetFileSecurity is not available\n");
850 return;
853 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
854 win_skip ("GetTempPathA failed\n");
855 return;
858 /* Create a temporary directory and in it a temporary file */
859 strcat (strcpy (path, wintmpdir), "rary");
860 SetLastError(0xdeadbeef);
861 rc = CreateDirectoryA (path, NULL);
862 ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
863 "failed for '%s' with %d\n", path, GetLastError());
865 strcat (strcpy (file, path), "\\ess");
866 SetLastError(0xdeadbeef);
867 fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
868 ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
869 "failed for '%s' with %d\n", file, GetLastError());
870 CloseHandle (fh);
872 /* For the temporary file ... */
874 /* Get size needed */
875 retSize = 0;
876 SetLastError(0xdeadbeef);
877 rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
878 if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
879 win_skip("GetFileSecurityA is not implemented\n");
880 goto cleanup;
882 ok (!rc, "GetFileSecurityA "
883 "was expected to fail for '%s'\n", file);
884 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
885 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
886 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
888 sdSize = retSize;
889 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
891 /* Get security descriptor for real */
892 retSize = -1;
893 SetLastError(0xdeadbeef);
894 rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
895 ok (rc, "GetFileSecurityA "
896 "was not expected to fail '%s': %d\n", file, GetLastError());
897 ok (retSize == sdSize ||
898 broken(retSize == 0), /* NT4 */
899 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
901 /* Use it to set security descriptor */
902 SetLastError(0xdeadbeef);
903 rc = pSetFileSecurityA (file, request, sd);
904 ok (rc, "SetFileSecurityA "
905 "was not expected to fail '%s': %d\n", file, GetLastError());
907 HeapFree (GetProcessHeap (), 0, sd);
909 /* Repeat for the temporary directory ... */
911 /* Get size needed */
912 retSize = 0;
913 SetLastError(0xdeadbeef);
914 rc = pGetFileSecurityA (path, request, NULL, 0, &retSize);
915 ok (!rc, "GetFileSecurityA "
916 "was expected to fail for '%s'\n", path);
917 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
918 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
919 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
921 sdSize = retSize;
922 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
924 /* Get security descriptor for real */
925 retSize = -1;
926 SetLastError(0xdeadbeef);
927 rc = pGetFileSecurityA (path, request, sd, sdSize, &retSize);
928 ok (rc, "GetFileSecurityA "
929 "was not expected to fail '%s': %d\n", path, GetLastError());
930 ok (retSize == sdSize ||
931 broken(retSize == 0), /* NT4 */
932 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
934 /* Use it to set security descriptor */
935 SetLastError(0xdeadbeef);
936 rc = pSetFileSecurityA (path, request, sd);
937 ok (rc, "SetFileSecurityA "
938 "was not expected to fail '%s': %d\n", path, GetLastError());
939 HeapFree (GetProcessHeap (), 0, sd);
941 /* Old test */
942 strcpy (wintmpdir, "\\Should not exist");
943 SetLastError(0xdeadbeef);
944 rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
945 ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
946 ok (GetLastError() == ERROR_FILE_NOT_FOUND,
947 "last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());
949 cleanup:
950 /* Remove temporary file and directory */
951 DeleteFileA(file);
952 RemoveDirectoryA(path);
954 /* Test file access permissions for a file with FILE_ATTRIBUTE_ARCHIVE */
955 SetLastError(0xdeadbeef);
956 rc = GetTempPathA(sizeof(wintmpdir), wintmpdir);
957 ok(rc, "GetTempPath error %d\n", GetLastError());
959 SetLastError(0xdeadbeef);
960 rc = GetTempFileNameA(wintmpdir, "tmp", 0, file);
961 ok(rc, "GetTempFileName error %d\n", GetLastError());
963 rc = GetFileAttributesA(file);
964 rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
965 ok(rc == FILE_ATTRIBUTE_ARCHIVE, "expected FILE_ATTRIBUTE_ARCHIVE got %#x\n", rc);
967 rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
968 NULL, 0, &sdSize);
969 ok(!rc, "GetFileSecurity should fail\n");
970 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
971 "expected ERROR_INSUFFICIENT_BUFFER got %d\n", GetLastError());
972 ok(sdSize > sizeof(SECURITY_DESCRIPTOR), "got sd size %d\n", sdSize);
974 sd = HeapAlloc(GetProcessHeap (), 0, sdSize);
975 retSize = 0xdeadbeef;
976 SetLastError(0xdeadbeef);
977 rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
978 sd, sdSize, &retSize);
979 ok(rc, "GetFileSecurity error %d\n", GetLastError());
980 ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
982 SetLastError(0xdeadbeef);
983 rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
984 ok(!rc, "OpenThreadToken should fail\n");
985 ok(GetLastError() == ERROR_NO_TOKEN, "expected ERROR_NO_TOKEN, got %d\n", GetLastError());
987 SetLastError(0xdeadbeef);
988 rc = ImpersonateSelf(SecurityIdentification);
989 ok(rc, "ImpersonateSelf error %d\n", GetLastError());
991 SetLastError(0xdeadbeef);
992 rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
993 ok(rc, "OpenThreadToken error %d\n", GetLastError());
995 SetLastError(0xdeadbeef);
996 rc = RevertToSelf();
997 ok(rc, "RevertToSelf error %d\n", GetLastError());
999 priv_set_len = sizeof(priv_set);
1000 granted = 0xdeadbeef;
1001 status = 0xdeadbeef;
1002 SetLastError(0xdeadbeef);
1003 rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1004 ok(rc, "AccessCheck error %d\n", GetLastError());
1005 ok(status == 1, "expected 1, got %d\n", status);
1006 ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
1008 granted = 0xdeadbeef;
1009 status = 0xdeadbeef;
1010 SetLastError(0xdeadbeef);
1011 rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1012 ok(rc, "AccessCheck error %d\n", GetLastError());
1013 ok(status == 1, "expected 1, got %d\n", status);
1014 ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
1016 granted = 0xdeadbeef;
1017 status = 0xdeadbeef;
1018 SetLastError(0xdeadbeef);
1019 rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1020 ok(rc, "AccessCheck error %d\n", GetLastError());
1021 ok(status == 1, "expected 1, got %d\n", status);
1022 ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
1024 granted = 0xdeadbeef;
1025 status = 0xdeadbeef;
1026 SetLastError(0xdeadbeef);
1027 rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1028 ok(rc, "AccessCheck error %d\n", GetLastError());
1029 ok(status == 1, "expected 1, got %d\n", status);
1030 ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
1032 granted = 0xdeadbeef;
1033 status = 0xdeadbeef;
1034 SetLastError(0xdeadbeef);
1035 rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
1036 ok(rc, "AccessCheck error %d\n", GetLastError());
1037 ok(status == 1, "expected 1, got %d\n", status);
1038 ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
1040 granted = 0xdeadbeef;
1041 status = 0xdeadbeef;
1042 SetLastError(0xdeadbeef);
1043 rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
1044 ok(rc, "AccessCheck error %d\n", GetLastError());
1045 ok(status == 1, "expected 1, got %d\n", status);
1046 ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
1048 granted = 0xdeadbeef;
1049 status = 0xdeadbeef;
1050 SetLastError(0xdeadbeef);
1051 rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
1052 ok(rc, "AccessCheck error %d\n", GetLastError());
1053 ok(status == 1, "expected 1, got %d\n", status);
1054 ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
1056 SetLastError(0xdeadbeef);
1057 rc = AccessCheck(sd, token, 0xffffffff, &mapping, &priv_set, &priv_set_len, &granted, &status);
1058 ok(!rc, "AccessCheck should fail\n");
1059 ok(GetLastError() == ERROR_GENERIC_NOT_MAPPED, "expected ERROR_GENERIC_NOT_MAPPED, got %d\n", GetLastError());
1061 /* Test file access permissions for a file with FILE_ATTRIBUTE_READONLY */
1062 SetLastError(0xdeadbeef);
1063 fh = CreateFileA(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
1064 ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
1065 retSize = 0xdeadbeef;
1066 SetLastError(0xdeadbeef);
1067 rc = WriteFile(fh, "1", 1, &retSize, NULL);
1068 ok(!rc, "WriteFile should fail\n");
1069 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1070 ok(retSize == 0, "expected 0, got %d\n", retSize);
1071 CloseHandle(fh);
1073 rc = GetFileAttributesA(file);
1074 rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
1075 todo_wine
1076 ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
1077 "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
1079 SetLastError(0xdeadbeef);
1080 rc = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
1081 ok(rc, "SetFileAttributes error %d\n", GetLastError());
1082 SetLastError(0xdeadbeef);
1083 rc = DeleteFileA(file);
1084 ok(rc, "DeleteFile error %d\n", GetLastError());
1086 SetLastError(0xdeadbeef);
1087 fh = CreateFileA(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
1088 ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
1089 retSize = 0xdeadbeef;
1090 SetLastError(0xdeadbeef);
1091 rc = WriteFile(fh, "1", 1, &retSize, NULL);
1092 ok(!rc, "WriteFile should fail\n");
1093 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1094 ok(retSize == 0, "expected 0, got %d\n", retSize);
1095 CloseHandle(fh);
1097 rc = GetFileAttributesA(file);
1098 rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
1099 ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
1100 "expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
1102 retSize = 0xdeadbeef;
1103 SetLastError(0xdeadbeef);
1104 rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
1105 sd, sdSize, &retSize);
1106 ok(rc, "GetFileSecurity error %d\n", GetLastError());
1107 ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
1109 priv_set_len = sizeof(priv_set);
1110 granted = 0xdeadbeef;
1111 status = 0xdeadbeef;
1112 SetLastError(0xdeadbeef);
1113 rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1114 ok(rc, "AccessCheck error %d\n", GetLastError());
1115 ok(status == 1, "expected 1, got %d\n", status);
1116 ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
1118 granted = 0xdeadbeef;
1119 status = 0xdeadbeef;
1120 SetLastError(0xdeadbeef);
1121 rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
1122 ok(rc, "AccessCheck error %d\n", GetLastError());
1123 todo_wine {
1124 ok(status == 1, "expected 1, got %d\n", status);
1125 ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
1127 granted = 0xdeadbeef;
1128 status = 0xdeadbeef;
1129 SetLastError(0xdeadbeef);
1130 rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1131 ok(rc, "AccessCheck error %d\n", GetLastError());
1132 ok(status == 1, "expected 1, got %d\n", status);
1133 ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
1135 granted = 0xdeadbeef;
1136 status = 0xdeadbeef;
1137 SetLastError(0xdeadbeef);
1138 rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
1139 ok(rc, "AccessCheck error %d\n", GetLastError());
1140 todo_wine {
1141 ok(status == 1, "expected 1, got %d\n", status);
1142 ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
1144 granted = 0xdeadbeef;
1145 status = 0xdeadbeef;
1146 SetLastError(0xdeadbeef);
1147 rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
1148 ok(rc, "AccessCheck error %d\n", GetLastError());
1149 todo_wine {
1150 ok(status == 1, "expected 1, got %d\n", status);
1151 ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
1153 granted = 0xdeadbeef;
1154 status = 0xdeadbeef;
1155 SetLastError(0xdeadbeef);
1156 rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
1157 ok(rc, "AccessCheck error %d\n", GetLastError());
1158 todo_wine {
1159 ok(status == 1, "expected 1, got %d\n", status);
1160 ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
1162 granted = 0xdeadbeef;
1163 status = 0xdeadbeef;
1164 SetLastError(0xdeadbeef);
1165 rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
1166 ok(rc, "AccessCheck error %d\n", GetLastError());
1167 todo_wine {
1168 ok(status == 1, "expected 1, got %d\n", status);
1169 ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
1171 SetLastError(0xdeadbeef);
1172 rc = DeleteFileA(file);
1173 ok(!rc, "DeleteFile should fail\n");
1174 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1175 SetLastError(0xdeadbeef);
1176 rc = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
1177 ok(rc, "SetFileAttributes error %d\n", GetLastError());
1178 SetLastError(0xdeadbeef);
1179 rc = DeleteFileA(file);
1180 ok(rc, "DeleteFile error %d\n", GetLastError());
1182 CloseHandle(token);
1183 HeapFree(GetProcessHeap(), 0, sd);
1186 static void test_AccessCheck(void)
1188 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
1189 PACL Acl = NULL;
1190 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
1191 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
1192 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1193 GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
1194 ACCESS_MASK Access;
1195 BOOL AccessStatus;
1196 HANDLE Token;
1197 HANDLE ProcessToken;
1198 BOOL ret;
1199 DWORD PrivSetLen;
1200 PRIVILEGE_SET *PrivSet;
1201 BOOL res;
1202 HMODULE NtDllModule;
1203 BOOLEAN Enabled;
1204 DWORD err;
1205 NTSTATUS ntret, ntAccessStatus;
1207 NtDllModule = GetModuleHandleA("ntdll.dll");
1208 if (!NtDllModule)
1210 skip("not running on NT, skipping test\n");
1211 return;
1213 pRtlAdjustPrivilege = (void *)GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
1214 if (!pRtlAdjustPrivilege)
1216 win_skip("missing RtlAdjustPrivilege, skipping test\n");
1217 return;
1220 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
1221 res = InitializeAcl(Acl, 256, ACL_REVISION);
1222 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1224 skip("ACLs not implemented - skipping tests\n");
1225 HeapFree(GetProcessHeap(), 0, Acl);
1226 return;
1228 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
1230 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
1231 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1233 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1234 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
1235 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1237 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1238 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
1239 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1241 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
1243 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1244 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
1246 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1247 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1249 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1250 PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
1251 PrivSet->PrivilegeCount = 16;
1253 res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
1254 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
1256 pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
1258 res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
1259 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1261 /* SD without owner/group */
1262 SetLastError(0xdeadbeef);
1263 Access = AccessStatus = 0x1abe11ed;
1264 ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
1265 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1266 err = GetLastError();
1267 ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
1268 "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
1269 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1270 "Access and/or AccessStatus were changed!\n");
1272 /* Set owner and group */
1273 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
1274 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
1275 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
1276 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
1278 /* Generic access mask */
1279 SetLastError(0xdeadbeef);
1280 Access = AccessStatus = 0x1abe11ed;
1281 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1282 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1283 err = GetLastError();
1284 ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
1285 "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
1286 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1287 "Access and/or AccessStatus were changed!\n");
1289 /* Generic access mask - no privilegeset buffer */
1290 SetLastError(0xdeadbeef);
1291 Access = AccessStatus = 0x1abe11ed;
1292 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1293 NULL, &PrivSetLen, &Access, &AccessStatus);
1294 err = GetLastError();
1295 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1296 "with ERROR_NOACCESS, instead of %d\n", err);
1297 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1298 "Access and/or AccessStatus were changed!\n");
1300 /* Generic access mask - no returnlength */
1301 SetLastError(0xdeadbeef);
1302 Access = AccessStatus = 0x1abe11ed;
1303 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1304 PrivSet, NULL, &Access, &AccessStatus);
1305 err = GetLastError();
1306 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1307 "with ERROR_NOACCESS, instead of %d\n", err);
1308 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1309 "Access and/or AccessStatus were changed!\n");
1311 /* Generic access mask - no privilegeset buffer, no returnlength */
1312 SetLastError(0xdeadbeef);
1313 Access = AccessStatus = 0x1abe11ed;
1314 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1315 NULL, NULL, &Access, &AccessStatus);
1316 err = GetLastError();
1317 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1318 "with ERROR_NOACCESS, instead of %d\n", err);
1319 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1320 "Access and/or AccessStatus were changed!\n");
1322 /* sd with no dacl present */
1323 Access = AccessStatus = 0x1abe11ed;
1324 ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
1325 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1326 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1327 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1328 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1329 ok(AccessStatus && (Access == KEY_READ),
1330 "AccessCheck failed to grant access with error %d\n",
1331 GetLastError());
1333 /* sd with no dacl present - no privilegeset buffer */
1334 SetLastError(0xdeadbeef);
1335 Access = AccessStatus = 0x1abe11ed;
1336 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1337 NULL, &PrivSetLen, &Access, &AccessStatus);
1338 err = GetLastError();
1339 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
1340 "with ERROR_NOACCESS, instead of %d\n", err);
1341 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1342 "Access and/or AccessStatus were changed!\n");
1344 if(pNtAccessCheck)
1346 DWORD ntPrivSetLen = sizeof(PRIVILEGE_SET);
1348 /* Generic access mask - no privilegeset buffer */
1349 SetLastError(0xdeadbeef);
1350 Access = ntAccessStatus = 0x1abe11ed;
1351 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1352 NULL, &ntPrivSetLen, &Access, &ntAccessStatus);
1353 err = GetLastError();
1354 ok(ntret == STATUS_ACCESS_VIOLATION,
1355 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1356 ok(err == 0xdeadbeef,
1357 "NtAccessCheck shouldn't set last error, got %d\n", err);
1358 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1359 "Access and/or AccessStatus were changed!\n");
1360 ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
1362 /* Generic access mask - no returnlength */
1363 SetLastError(0xdeadbeef);
1364 Access = ntAccessStatus = 0x1abe11ed;
1365 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1366 PrivSet, NULL, &Access, &ntAccessStatus);
1367 err = GetLastError();
1368 ok(ntret == STATUS_ACCESS_VIOLATION,
1369 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1370 ok(err == 0xdeadbeef,
1371 "NtAccessCheck shouldn't set last error, got %d\n", err);
1372 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1373 "Access and/or AccessStatus were changed!\n");
1375 /* Generic access mask - no privilegeset buffer, no returnlength */
1376 SetLastError(0xdeadbeef);
1377 Access = ntAccessStatus = 0x1abe11ed;
1378 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1379 NULL, NULL, &Access, &ntAccessStatus);
1380 err = GetLastError();
1381 ok(ntret == STATUS_ACCESS_VIOLATION,
1382 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1383 ok(err == 0xdeadbeef,
1384 "NtAccessCheck shouldn't set last error, got %d\n", err);
1385 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1386 "Access and/or AccessStatus were changed!\n");
1388 /* Generic access mask - zero returnlength */
1389 SetLastError(0xdeadbeef);
1390 Access = ntAccessStatus = 0x1abe11ed;
1391 ntPrivSetLen = 0;
1392 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1393 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1394 err = GetLastError();
1395 ok(ntret == STATUS_GENERIC_NOT_MAPPED,
1396 "NtAccessCheck should have failed with STATUS_GENERIC_NOT_MAPPED, got %x\n", ntret);
1397 ok(err == 0xdeadbeef,
1398 "NtAccessCheck shouldn't set last error, got %d\n", err);
1399 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1400 "Access and/or AccessStatus were changed!\n");
1401 todo_wine ok(ntPrivSetLen == 0, "PrivSetLen returns %d\n", ntPrivSetLen);
1403 /* Generic access mask - insufficient returnlength */
1404 SetLastError(0xdeadbeef);
1405 Access = ntAccessStatus = 0x1abe11ed;
1406 ntPrivSetLen = sizeof(PRIVILEGE_SET)-1;
1407 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1408 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1409 err = GetLastError();
1410 ok(ntret == STATUS_GENERIC_NOT_MAPPED,
1411 "NtAccessCheck should have failed with STATUS_GENERIC_NOT_MAPPED, got %x\n", ntret);
1412 ok(err == 0xdeadbeef,
1413 "NtAccessCheck shouldn't set last error, got %d\n", err);
1414 ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1415 "Access and/or AccessStatus were changed!\n");
1416 todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET)-1, "PrivSetLen returns %d\n", ntPrivSetLen);
1418 /* Key access mask - zero returnlength */
1419 SetLastError(0xdeadbeef);
1420 Access = ntAccessStatus = 0x1abe11ed;
1421 ntPrivSetLen = 0;
1422 ntret = pNtAccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1423 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1424 err = GetLastError();
1425 todo_wine ok(ntret == STATUS_BUFFER_TOO_SMALL,
1426 "NtAccessCheck should have failed with STATUS_BUFFER_TOO_SMALL, got %x\n", ntret);
1427 ok(err == 0xdeadbeef,
1428 "NtAccessCheck shouldn't set last error, got %d\n", err);
1429 todo_wine ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1430 "Access and/or AccessStatus were changed!\n");
1431 todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
1433 /* Key access mask - insufficient returnlength */
1434 SetLastError(0xdeadbeef);
1435 Access = ntAccessStatus = 0x1abe11ed;
1436 ntPrivSetLen = sizeof(PRIVILEGE_SET)-1;
1437 ntret = pNtAccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1438 PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
1439 err = GetLastError();
1440 todo_wine ok(ntret == STATUS_BUFFER_TOO_SMALL,
1441 "NtAccessCheck should have failed with STATUS_BUFFER_TOO_SMALL, got %x\n", ntret);
1442 ok(err == 0xdeadbeef,
1443 "NtAccessCheck shouldn't set last error, got %d\n", err);
1444 todo_wine ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
1445 "Access and/or AccessStatus were changed!\n");
1446 todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
1448 else
1449 win_skip("NtAccessCheck unavailable. Skipping.\n");
1451 /* sd with NULL dacl */
1452 Access = AccessStatus = 0x1abe11ed;
1453 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
1454 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1455 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1456 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1457 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1458 ok(AccessStatus && (Access == KEY_READ),
1459 "AccessCheck failed to grant access with error %d\n",
1460 GetLastError());
1461 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1462 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1463 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1464 ok(AccessStatus && (Access == KEY_ALL_ACCESS),
1465 "AccessCheck failed to grant access with error %d\n",
1466 GetLastError());
1468 /* sd with blank dacl */
1469 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1470 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1471 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1472 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1473 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1474 err = GetLastError();
1475 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1476 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1477 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1479 res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
1480 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1482 res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
1483 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1485 /* sd with dacl */
1486 Access = AccessStatus = 0x1abe11ed;
1487 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1488 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1489 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1490 ok(AccessStatus && (Access == KEY_READ),
1491 "AccessCheck failed to grant access with error %d\n",
1492 GetLastError());
1494 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1495 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1496 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1497 ok(AccessStatus,
1498 "AccessCheck failed to grant any access with error %d\n",
1499 GetLastError());
1500 trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
1502 /* Null PrivSet with null PrivSetLen pointer */
1503 SetLastError(0xdeadbeef);
1504 Access = AccessStatus = 0x1abe11ed;
1505 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1506 NULL, NULL, &Access, &AccessStatus);
1507 err = GetLastError();
1508 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1509 "failed with ERROR_NOACCESS, instead of %d\n", err);
1510 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1511 "Access and/or AccessStatus were changed!\n");
1513 /* Null PrivSet with zero PrivSetLen */
1514 SetLastError(0xdeadbeef);
1515 Access = AccessStatus = 0x1abe11ed;
1516 PrivSetLen = 0;
1517 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1518 0, &PrivSetLen, &Access, &AccessStatus);
1519 err = GetLastError();
1520 todo_wine
1521 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1522 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1523 todo_wine
1524 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1525 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1526 "Access and/or AccessStatus were changed!\n");
1528 /* Null PrivSet with insufficient PrivSetLen */
1529 SetLastError(0xdeadbeef);
1530 Access = AccessStatus = 0x1abe11ed;
1531 PrivSetLen = 1;
1532 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1533 0, &PrivSetLen, &Access, &AccessStatus);
1534 err = GetLastError();
1535 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1536 "failed with ERROR_NOACCESS, instead of %d\n", err);
1537 ok(PrivSetLen == 1, "PrivSetLen returns %d\n", PrivSetLen);
1538 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1539 "Access and/or AccessStatus were changed!\n");
1541 /* Null PrivSet with insufficient PrivSetLen */
1542 SetLastError(0xdeadbeef);
1543 Access = AccessStatus = 0x1abe11ed;
1544 PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
1545 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1546 0, &PrivSetLen, &Access, &AccessStatus);
1547 err = GetLastError();
1548 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1549 "failed with ERROR_NOACCESS, instead of %d\n", err);
1550 ok(PrivSetLen == sizeof(PRIVILEGE_SET) - 1, "PrivSetLen returns %d\n", PrivSetLen);
1551 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1552 "Access and/or AccessStatus were changed!\n");
1554 /* Null PrivSet with minimal sufficient PrivSetLen */
1555 SetLastError(0xdeadbeef);
1556 Access = AccessStatus = 0x1abe11ed;
1557 PrivSetLen = sizeof(PRIVILEGE_SET);
1558 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1559 0, &PrivSetLen, &Access, &AccessStatus);
1560 err = GetLastError();
1561 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1562 "failed with ERROR_NOACCESS, instead of %d\n", err);
1563 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1564 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1565 "Access and/or AccessStatus were changed!\n");
1567 /* Valid PrivSet with zero PrivSetLen */
1568 SetLastError(0xdeadbeef);
1569 Access = AccessStatus = 0x1abe11ed;
1570 PrivSetLen = 0;
1571 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1572 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1573 err = GetLastError();
1574 todo_wine
1575 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1576 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1577 todo_wine
1578 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1579 todo_wine
1580 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1581 "Access and/or AccessStatus were changed!\n");
1583 /* Valid PrivSet with insufficient PrivSetLen */
1584 SetLastError(0xdeadbeef);
1585 Access = AccessStatus = 0x1abe11ed;
1586 PrivSetLen = 1;
1587 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1588 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1589 err = GetLastError();
1590 todo_wine
1591 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1592 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1593 todo_wine
1594 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1595 todo_wine
1596 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1597 "Access and/or AccessStatus were changed!\n");
1599 /* Valid PrivSet with insufficient PrivSetLen */
1600 SetLastError(0xdeadbeef);
1601 Access = AccessStatus = 0x1abe11ed;
1602 PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
1603 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1604 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1605 err = GetLastError();
1606 todo_wine
1607 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1608 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1609 todo_wine
1610 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1611 todo_wine
1612 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1613 "Access and/or AccessStatus were changed!\n");
1615 /* Valid PrivSet with minimal sufficient PrivSetLen */
1616 SetLastError(0xdeadbeef);
1617 Access = AccessStatus = 0x1abe11ed;
1618 PrivSetLen = sizeof(PRIVILEGE_SET);
1619 memset(PrivSet, 0xcc, PrivSetLen);
1620 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1621 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1622 err = GetLastError();
1623 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1624 todo_wine
1625 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1626 ok(AccessStatus && (Access == KEY_READ),
1627 "AccessCheck failed to grant access with error %d\n", GetLastError());
1628 ok(PrivSet->PrivilegeCount == 0, "PrivilegeCount returns %d, expects 0\n",
1629 PrivSet->PrivilegeCount);
1631 /* Valid PrivSet with sufficient PrivSetLen */
1632 SetLastError(0xdeadbeef);
1633 Access = AccessStatus = 0x1abe11ed;
1634 PrivSetLen = sizeof(PRIVILEGE_SET) + 1;
1635 memset(PrivSet, 0xcc, PrivSetLen);
1636 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1637 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1638 err = GetLastError();
1639 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1640 todo_wine
1641 ok(PrivSetLen == sizeof(PRIVILEGE_SET) + 1, "PrivSetLen returns %d\n", PrivSetLen);
1642 ok(AccessStatus && (Access == KEY_READ),
1643 "AccessCheck failed to grant access with error %d\n", GetLastError());
1644 ok(PrivSet->PrivilegeCount == 0, "PrivilegeCount returns %d, expects 0\n",
1645 PrivSet->PrivilegeCount);
1647 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1649 /* Null PrivSet with valid PrivSetLen */
1650 SetLastError(0xdeadbeef);
1651 Access = AccessStatus = 0x1abe11ed;
1652 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1653 0, &PrivSetLen, &Access, &AccessStatus);
1654 err = GetLastError();
1655 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
1656 "failed with ERROR_NOACCESS, instead of %d\n", err);
1657 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1658 "Access and/or AccessStatus were changed!\n");
1660 /* Access denied by SD */
1661 SetLastError(0xdeadbeef);
1662 Access = AccessStatus = 0x1abe11ed;
1663 ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
1664 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1665 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1666 err = GetLastError();
1667 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1668 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1669 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1671 SetLastError(0xdeadbeef);
1672 PrivSet->PrivilegeCount = 16;
1673 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1674 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1675 ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
1676 "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
1677 GetLastError());
1679 ret = ImpersonateLoggedOnUser(Token);
1680 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1681 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
1682 if (!ret)
1684 /* Valid PrivSet with zero PrivSetLen */
1685 SetLastError(0xdeadbeef);
1686 Access = AccessStatus = 0x1abe11ed;
1687 PrivSetLen = 0;
1688 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1689 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1690 err = GetLastError();
1691 todo_wine
1692 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1693 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1694 todo_wine
1695 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1696 todo_wine
1697 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1698 "Access and/or AccessStatus were changed!\n");
1700 /* Valid PrivSet with insufficient PrivSetLen */
1701 SetLastError(0xdeadbeef);
1702 Access = AccessStatus = 0x1abe11ed;
1703 PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
1704 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1705 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1706 err = GetLastError();
1707 todo_wine
1708 ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
1709 "failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
1710 todo_wine
1711 ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
1712 todo_wine
1713 ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
1714 "Access and/or AccessStatus were changed!\n");
1716 /* Valid PrivSet with minimal sufficient PrivSetLen */
1717 SetLastError(0xdeadbeef);
1718 Access = AccessStatus = 0x1abe11ed;
1719 PrivSetLen = sizeof(PRIVILEGE_SET);
1720 memset(PrivSet, 0xcc, PrivSetLen);
1721 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1722 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1723 ok(ret && AccessStatus && GetLastError() == 0xdeadbeef,
1724 "AccessCheck should have succeeded, error %d\n",
1725 GetLastError());
1726 ok(Access == ACCESS_SYSTEM_SECURITY,
1727 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1728 Access);
1729 ok(PrivSet->PrivilegeCount == 1, "PrivilegeCount returns %d, expects 1\n",
1730 PrivSet->PrivilegeCount);
1732 /* Valid PrivSet with large PrivSetLen */
1733 SetLastError(0xdeadbeef);
1734 Access = AccessStatus = 0x1abe11ed;
1735 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
1736 memset(PrivSet, 0xcc, PrivSetLen);
1737 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1738 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1739 ok(ret && AccessStatus && GetLastError() == 0xdeadbeef,
1740 "AccessCheck should have succeeded, error %d\n",
1741 GetLastError());
1742 ok(Access == ACCESS_SYSTEM_SECURITY,
1743 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1744 Access);
1745 ok(PrivSet->PrivilegeCount == 1, "PrivilegeCount returns %d, expects 1\n",
1746 PrivSet->PrivilegeCount);
1748 else
1749 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1750 ret);
1751 ret = RevertToSelf();
1752 ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1754 /* test INHERIT_ONLY_ACE */
1755 ret = InitializeAcl(Acl, 256, ACL_REVISION);
1756 ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
1758 /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
1759 * the next ones.
1761 if (pAddAccessAllowedAceEx)
1763 ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
1764 ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1766 else
1767 win_skip("AddAccessAllowedAceEx is not available\n");
1769 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1770 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1771 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1772 err = GetLastError();
1773 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1774 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1775 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1777 CloseHandle(Token);
1779 res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
1780 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1782 SetLastError(0xdeadbeef);
1783 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1784 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1785 err = GetLastError();
1786 ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
1787 "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
1789 CloseHandle(Token);
1791 SetLastError(0xdeadbeef);
1792 ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
1793 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1794 err = GetLastError();
1795 ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
1796 "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
1798 CloseHandle(ProcessToken);
1800 if (EveryoneSid)
1801 FreeSid(EveryoneSid);
1802 if (AdminSid)
1803 FreeSid(AdminSid);
1804 if (UsersSid)
1805 FreeSid(UsersSid);
1806 HeapFree(GetProcessHeap(), 0, Acl);
1807 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1808 HeapFree(GetProcessHeap(), 0, PrivSet);
1811 /* test GetTokenInformation for the various attributes */
1812 static void test_token_attr(void)
1814 HANDLE Token, ImpersonationToken;
1815 DWORD Size, Size2;
1816 TOKEN_PRIVILEGES *Privileges;
1817 TOKEN_GROUPS *Groups;
1818 TOKEN_USER *User;
1819 TOKEN_DEFAULT_DACL *Dacl;
1820 BOOL ret;
1821 DWORD i, GLE;
1822 LPSTR SidString;
1823 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1824 ACL *acl;
1826 /* cygwin-like use case */
1827 SetLastError(0xdeadbeef);
1828 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1829 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1831 win_skip("OpenProcessToken is not implemented\n");
1832 return;
1834 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1835 if (ret)
1837 DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1838 Size = sizeof(buf);
1839 ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1840 ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1841 Size = sizeof(ImpersonationLevel);
1842 ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1843 GLE = GetLastError();
1844 ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1845 CloseHandle(Token);
1848 SetLastError(0xdeadbeef);
1849 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1850 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1852 /* groups */
1853 /* insufficient buffer length */
1854 SetLastError(0xdeadbeef);
1855 Size2 = 0;
1856 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size2);
1857 ok(Size2 > 1, "got %d\n", Size2);
1858 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1859 "%d with error %d\n", ret, GetLastError());
1860 Size2 -= 1;
1861 Groups = HeapAlloc(GetProcessHeap(), 0, Size2);
1862 memset(Groups, 0xcc, Size2);
1863 Size = 0;
1864 ret = GetTokenInformation(Token, TokenGroups, Groups, Size2, &Size);
1865 ok(Size > 1, "got %d\n", Size);
1866 ok((!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER) || broken(ret) /* wow64 */,
1867 "%d with error %d\n", ret, GetLastError());
1868 if(!ret)
1869 ok(*((BYTE*)Groups) == 0xcc, "buffer altered\n");
1871 HeapFree(GetProcessHeap(), 0, Groups);
1873 SetLastError(0xdeadbeef);
1874 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1875 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1876 "GetTokenInformation(TokenGroups) %s with error %d\n",
1877 ret ? "succeeded" : "failed", GetLastError());
1878 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1879 SetLastError(0xdeadbeef);
1880 ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1881 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1882 ok(GetLastError() == 0xdeadbeef,
1883 "GetTokenInformation shouldn't have set last error to %d\n",
1884 GetLastError());
1885 trace("TokenGroups:\n");
1886 for (i = 0; i < Groups->GroupCount; i++)
1888 DWORD NameLength = 255;
1889 CHAR Name[255];
1890 DWORD DomainLength = 255;
1891 CHAR Domain[255];
1892 SID_NAME_USE SidNameUse;
1893 Name[0] = '\0';
1894 Domain[0] = '\0';
1895 ret = LookupAccountSidA(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1896 if (ret)
1898 ConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1899 trace("%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
1900 LocalFree(SidString);
1902 else trace("attr: 0x%08x LookupAccountSid failed with error %d\n", Groups->Groups[i].Attributes, GetLastError());
1904 HeapFree(GetProcessHeap(), 0, Groups);
1906 /* user */
1907 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1908 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1909 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1910 User = HeapAlloc(GetProcessHeap(), 0, Size);
1911 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1912 ok(ret,
1913 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1915 ConvertSidToStringSidA(User->User.Sid, &SidString);
1916 trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1917 LocalFree(SidString);
1918 HeapFree(GetProcessHeap(), 0, User);
1920 /* logon */
1921 ret = GetTokenInformation(Token, TokenLogonSid, NULL, 0, &Size);
1922 if (!ret && (GetLastError() == ERROR_INVALID_PARAMETER))
1923 todo_wine win_skip("TokenLogonSid not supported. Skipping tests\n");
1924 else
1926 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1927 "GetTokenInformation(TokenLogonSid) failed with error %d\n", GetLastError());
1928 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1929 ret = GetTokenInformation(Token, TokenLogonSid, Groups, Size, &Size);
1930 ok(ret,
1931 "GetTokenInformation(TokenLogonSid) failed with error %d\n", GetLastError());
1932 if (ret)
1934 ok(Groups->GroupCount == 1, "got %d\n", Groups->GroupCount);
1935 if(Groups->GroupCount == 1)
1937 ConvertSidToStringSidA(Groups->Groups[0].Sid, &SidString);
1938 trace("TokenLogon: %s\n", SidString);
1939 LocalFree(SidString);
1941 /* S-1-5-5-0-XXXXXX */
1942 ret = IsWellKnownSid(Groups->Groups[0].Sid, WinLogonIdsSid);
1943 ok(ret, "Unknown SID\n");
1947 HeapFree(GetProcessHeap(), 0, Groups);
1950 /* privileges */
1951 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1952 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1953 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1954 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1955 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1956 ok(ret,
1957 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1958 trace("TokenPrivileges:\n");
1959 for (i = 0; i < Privileges->PrivilegeCount; i++)
1961 CHAR Name[256];
1962 DWORD NameLen = ARRAY_SIZE(Name);
1963 LookupPrivilegeNameA(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1964 trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1966 HeapFree(GetProcessHeap(), 0, Privileges);
1968 ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
1969 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1971 Size = sizeof(ImpersonationLevel);
1972 ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1973 ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1974 ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
1976 CloseHandle(ImpersonationToken);
1978 /* default dacl */
1979 ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
1980 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1981 "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1983 Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
1984 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
1985 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1987 SetLastError(0xdeadbeef);
1988 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
1989 GLE = GetLastError();
1990 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1991 ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);
1993 SetLastError(0xdeadbeef);
1994 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
1995 GLE = GetLastError();
1996 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1997 ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);
1999 acl = Dacl->DefaultDacl;
2000 Dacl->DefaultDacl = NULL;
2002 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
2003 ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
2005 Size2 = 0;
2006 Dacl->DefaultDacl = (ACL *)0xdeadbeef;
2007 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
2008 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
2009 ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
2010 ok(Size2 == sizeof(TOKEN_DEFAULT_DACL) || broken(Size2 == 2*sizeof(TOKEN_DEFAULT_DACL)), /* WoW64 */
2011 "got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
2013 Dacl->DefaultDacl = acl;
2014 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
2015 ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
2017 if (Size2 == sizeof(TOKEN_DEFAULT_DACL)) {
2018 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
2019 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
2020 } else
2021 win_skip("TOKEN_DEFAULT_DACL size too small on WoW64\n");
2023 HeapFree(GetProcessHeap(), 0, Dacl);
2024 CloseHandle(Token);
2027 static void test_GetTokenInformation(void)
2029 DWORD is_app_container, size;
2030 HANDLE token;
2031 BOOL ret;
2033 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
2034 ok(ret, "OpenProcessToken failed: %u\n", GetLastError());
2036 size = 0;
2037 is_app_container = 0xdeadbeef;
2038 ret = GetTokenInformation(token, TokenIsAppContainer, &is_app_container,
2039 sizeof(is_app_container), &size);
2040 ok(ret || broken(GetLastError() == ERROR_INVALID_PARAMETER ||
2041 GetLastError() == ERROR_INVALID_FUNCTION), /* pre-win8 */
2042 "GetTokenInformation failed: %u\n", GetLastError());
2043 if(ret) {
2044 ok(size == sizeof(is_app_container), "size = %u\n", size);
2045 ok(!is_app_container, "is_app_container = %x\n", is_app_container);
2048 CloseHandle(token);
2051 typedef union _MAX_SID
2053 SID sid;
2054 char max[SECURITY_MAX_SID_SIZE];
2055 } MAX_SID;
2057 static void test_sid_str(PSID * sid)
2059 char *str_sid;
2060 BOOL ret = ConvertSidToStringSidA(sid, &str_sid);
2061 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
2062 if (ret)
2064 char account[MAX_PATH], domain[MAX_PATH];
2065 SID_NAME_USE use;
2066 DWORD acc_size = MAX_PATH;
2067 DWORD dom_size = MAX_PATH;
2068 ret = LookupAccountSidA (NULL, sid, account, &acc_size, domain, &dom_size, &use);
2069 ok(ret || GetLastError() == ERROR_NONE_MAPPED,
2070 "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
2071 if (ret)
2072 trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
2073 else if (GetLastError() == ERROR_NONE_MAPPED)
2074 trace(" %s couldn't be mapped\n", str_sid);
2075 LocalFree(str_sid);
2079 static const struct well_known_sid_value
2081 BOOL without_domain;
2082 const char *sid_string;
2083 } well_known_sid_values[] = {
2084 /* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
2085 /* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
2086 /* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
2087 /* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
2088 /* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
2089 /* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
2090 /* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
2091 /* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
2092 /* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
2093 /* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
2094 /* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
2095 /* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
2096 /* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
2097 /* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
2098 /* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
2099 /* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
2100 /* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
2101 /* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
2102 /* Added in Windows Server 2003 */
2103 /* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
2104 /* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
2105 /* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
2106 /* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
2107 /* Added in Windows Vista: */
2108 /* 62 */ {TRUE, "S-1-5-32-568"},
2109 /* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
2110 /* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
2111 /* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
2112 /* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
2113 /* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"},
2114 /* 77 */ {FALSE, "S-1-5-21-12-23-34-45-56-498"}, {TRUE, "S-1-5-32-574"}, {TRUE, "S-1-16-8448"},
2115 /* 80 */ {FALSE, NULL}, {TRUE, "S-1-2-1"}, {TRUE, "S-1-5-65-1"}, {FALSE, NULL},
2116 /* 84 */ {TRUE, "S-1-15-2-1"},
2119 static void test_CreateWellKnownSid(void)
2121 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
2122 PSID domainsid, sid;
2123 DWORD size, error;
2124 BOOL ret;
2125 unsigned int i;
2127 if (!pCreateWellKnownSid)
2129 win_skip("CreateWellKnownSid not available\n");
2130 return;
2133 size = 0;
2134 SetLastError(0xdeadbeef);
2135 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
2136 error = GetLastError();
2137 ok(!ret, "CreateWellKnownSid succeeded\n");
2138 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
2139 ok(size, "expected size > 0\n");
2141 SetLastError(0xdeadbeef);
2142 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
2143 error = GetLastError();
2144 ok(!ret, "CreateWellKnownSid succeeded\n");
2145 ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);
2147 sid = HeapAlloc(GetProcessHeap(), 0, size);
2148 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
2149 ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
2150 HeapFree(GetProcessHeap(), 0, sid);
2152 /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
2153 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
2155 for (i = 0; i < ARRAY_SIZE(well_known_sid_values); i++)
2157 const struct well_known_sid_value *value = &well_known_sid_values[i];
2158 char sid_buffer[SECURITY_MAX_SID_SIZE];
2159 LPSTR str;
2160 DWORD cb;
2162 if (value->sid_string == NULL)
2163 continue;
2165 /* some SIDs aren't implemented by all Windows versions - detect it */
2166 cb = sizeof(sid_buffer);
2167 if (!pCreateWellKnownSid(i, NULL, sid_buffer, &cb))
2169 skip("Well known SID %u not implemented\n", i);
2170 continue;
2173 cb = sizeof(sid_buffer);
2174 ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %u\n", i);
2175 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
2176 ok(IsValidSid(sid_buffer), "The sid is not valid\n");
2177 ok(ConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
2178 ok(strcmp(str, value->sid_string) == 0, "%d: SID mismatch - expected %s, got %s\n", i,
2179 value->sid_string, str);
2180 LocalFree(str);
2182 if (value->without_domain)
2184 char buf2[SECURITY_MAX_SID_SIZE];
2185 cb = sizeof(buf2);
2186 ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %u with optional domain\n", i);
2187 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
2188 ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%u)\n", i);
2192 FreeSid(domainsid);
2195 static void test_LookupAccountSid(void)
2197 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2198 CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
2199 DWORD acc_sizeA, dom_sizeA, user_sizeA;
2200 DWORD real_acc_sizeA, real_dom_sizeA;
2201 WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
2202 DWORD acc_sizeW, dom_sizeW;
2203 DWORD real_acc_sizeW, real_dom_sizeW;
2204 PSID pUsersSid = NULL;
2205 SID_NAME_USE use;
2206 BOOL ret;
2207 DWORD error, size, cbti = 0;
2208 MAX_SID max_sid;
2209 CHAR *str_sidA;
2210 int i;
2211 HANDLE hToken;
2212 PTOKEN_USER ptiUser = NULL;
2214 /* native windows crashes if account size, domain size, or name use is NULL */
2216 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2217 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
2218 ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
2219 "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2221 /* not running on NT so give up */
2222 if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2223 return;
2225 real_acc_sizeA = MAX_PATH;
2226 real_dom_sizeA = MAX_PATH;
2227 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
2228 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2230 /* try NULL account */
2231 acc_sizeA = MAX_PATH;
2232 dom_sizeA = MAX_PATH;
2233 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
2234 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2236 /* try NULL domain */
2237 acc_sizeA = MAX_PATH;
2238 dom_sizeA = MAX_PATH;
2239 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
2240 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2242 /* try a small account buffer */
2243 acc_sizeA = 1;
2244 dom_sizeA = MAX_PATH;
2245 accountA[0] = 0;
2246 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2247 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
2248 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2249 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2251 /* try a 0 sized account buffer */
2252 acc_sizeA = 0;
2253 dom_sizeA = MAX_PATH;
2254 accountA[0] = 0;
2255 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2256 /* this can fail or succeed depending on OS version but the size will always be returned */
2257 ok(acc_sizeA == real_acc_sizeA + 1,
2258 "LookupAccountSidA() Expected acc_size = %u, got %u\n",
2259 real_acc_sizeA + 1, acc_sizeA);
2261 /* try a 0 sized account buffer */
2262 acc_sizeA = 0;
2263 dom_sizeA = MAX_PATH;
2264 LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
2265 /* this can fail or succeed depending on OS version but the size will always be returned */
2266 ok(acc_sizeA == real_acc_sizeA + 1,
2267 "LookupAccountSid() Expected acc_size = %u, got %u\n",
2268 real_acc_sizeA + 1, acc_sizeA);
2270 /* try a small domain buffer */
2271 dom_sizeA = 1;
2272 acc_sizeA = MAX_PATH;
2273 accountA[0] = 0;
2274 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2275 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
2276 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2277 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2279 /* try a 0 sized domain buffer */
2280 dom_sizeA = 0;
2281 acc_sizeA = MAX_PATH;
2282 accountA[0] = 0;
2283 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2284 /* this can fail or succeed depending on OS version but the size will always be returned */
2285 ok(dom_sizeA == real_dom_sizeA + 1,
2286 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
2287 real_dom_sizeA + 1, dom_sizeA);
2289 /* try a 0 sized domain buffer */
2290 dom_sizeA = 0;
2291 acc_sizeA = MAX_PATH;
2292 LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
2293 /* this can fail or succeed depending on OS version but the size will always be returned */
2294 ok(dom_sizeA == real_dom_sizeA + 1,
2295 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
2296 real_dom_sizeA + 1, dom_sizeA);
2298 real_acc_sizeW = MAX_PATH;
2299 real_dom_sizeW = MAX_PATH;
2300 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
2301 ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
2303 /* try an invalid system name */
2304 real_acc_sizeA = MAX_PATH;
2305 real_dom_sizeA = MAX_PATH;
2306 ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
2307 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
2308 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2309 "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
2311 /* native windows crashes if domainW or accountW is NULL */
2313 /* try a small account buffer */
2314 acc_sizeW = 1;
2315 dom_sizeW = MAX_PATH;
2316 accountW[0] = 0;
2317 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2318 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
2319 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2320 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2322 /* try a 0 sized account buffer */
2323 acc_sizeW = 0;
2324 dom_sizeW = MAX_PATH;
2325 accountW[0] = 0;
2326 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2327 /* this can fail or succeed depending on OS version but the size will always be returned */
2328 ok(acc_sizeW == real_acc_sizeW + 1,
2329 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
2330 real_acc_sizeW + 1, acc_sizeW);
2332 /* try a 0 sized account buffer */
2333 acc_sizeW = 0;
2334 dom_sizeW = MAX_PATH;
2335 LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
2336 /* this can fail or succeed depending on OS version but the size will always be returned */
2337 ok(acc_sizeW == real_acc_sizeW + 1,
2338 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
2339 real_acc_sizeW + 1, acc_sizeW);
2341 /* try a small domain buffer */
2342 dom_sizeW = 1;
2343 acc_sizeW = MAX_PATH;
2344 accountW[0] = 0;
2345 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2346 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
2347 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2348 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
2350 /* try a 0 sized domain buffer */
2351 dom_sizeW = 0;
2352 acc_sizeW = MAX_PATH;
2353 accountW[0] = 0;
2354 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
2355 /* this can fail or succeed depending on OS version but the size will always be returned */
2356 ok(dom_sizeW == real_dom_sizeW + 1,
2357 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
2358 real_dom_sizeW + 1, dom_sizeW);
2360 /* try a 0 sized domain buffer */
2361 dom_sizeW = 0;
2362 acc_sizeW = MAX_PATH;
2363 LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
2364 /* this can fail or succeed depending on OS version but the size will always be returned */
2365 ok(dom_sizeW == real_dom_sizeW + 1,
2366 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
2367 real_dom_sizeW + 1, dom_sizeW);
2369 acc_sizeW = dom_sizeW = use = 0;
2370 SetLastError(0xdeadbeef);
2371 ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, NULL, &dom_sizeW, &use);
2372 error = GetLastError();
2373 ok(!ret, "LookupAccountSidW failed %u\n", GetLastError());
2374 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
2375 ok(acc_sizeW, "expected non-zero account size\n");
2376 ok(dom_sizeW, "expected non-zero domain size\n");
2377 ok(!use, "expected zero use %u\n", use);
2379 FreeSid(pUsersSid);
2381 /* Test LookupAccountSid with Sid retrieved from token information.
2382 This assumes this process is running under the account of the current user.*/
2383 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
2384 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
2385 ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
2386 ok(!ret, "GetTokenInformation failed with error %d\n", GetLastError());
2387 ptiUser = HeapAlloc(GetProcessHeap(), 0, cbti);
2388 if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
2390 acc_sizeA = dom_sizeA = MAX_PATH;
2391 ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
2392 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
2393 user_sizeA = MAX_PATH;
2394 ret = GetUserNameA(usernameA , &user_sizeA);
2395 ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
2396 ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
2398 HeapFree(GetProcessHeap(), 0, ptiUser);
2400 if (pCreateWellKnownSid)
2402 trace("Well Known SIDs:\n");
2403 for (i = 0; i <= 60; i++)
2405 size = SECURITY_MAX_SID_SIZE;
2406 if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
2408 if (ConvertSidToStringSidA(&max_sid.sid, &str_sidA))
2410 acc_sizeA = MAX_PATH;
2411 dom_sizeA = MAX_PATH;
2412 if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
2413 trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
2414 LocalFree(str_sidA);
2417 else
2419 if (GetLastError() != ERROR_INVALID_PARAMETER)
2420 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
2421 else
2422 trace(" %d: not supported\n", i);
2426 pLsaQueryInformationPolicy = (void *)GetProcAddress( hmod, "LsaQueryInformationPolicy");
2427 pLsaOpenPolicy = (void *)GetProcAddress( hmod, "LsaOpenPolicy");
2428 pLsaFreeMemory = (void *)GetProcAddress( hmod, "LsaFreeMemory");
2429 pLsaClose = (void *)GetProcAddress( hmod, "LsaClose");
2431 if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
2433 NTSTATUS status;
2434 LSA_HANDLE handle;
2435 LSA_OBJECT_ATTRIBUTES object_attributes;
2437 ZeroMemory(&object_attributes, sizeof(object_attributes));
2438 object_attributes.Length = sizeof(object_attributes);
2440 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
2441 ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
2442 "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
2444 /* try a more restricted access mask if necessary */
2445 if (status == STATUS_ACCESS_DENIED) {
2446 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
2447 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
2448 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
2451 if (status == STATUS_SUCCESS)
2453 PPOLICY_ACCOUNT_DOMAIN_INFO info;
2454 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
2455 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
2456 if (status == STATUS_SUCCESS)
2458 ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
2459 if (info->DomainSid)
2461 int count = *GetSidSubAuthorityCount(info->DomainSid);
2462 CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
2463 test_sid_str((PSID)&max_sid.sid);
2464 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
2465 max_sid.sid.SubAuthorityCount = count + 1;
2466 test_sid_str((PSID)&max_sid.sid);
2467 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
2468 test_sid_str((PSID)&max_sid.sid);
2469 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
2470 test_sid_str((PSID)&max_sid.sid);
2471 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
2472 test_sid_str((PSID)&max_sid.sid);
2473 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
2474 test_sid_str((PSID)&max_sid.sid);
2475 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
2476 test_sid_str((PSID)&max_sid.sid);
2477 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
2478 test_sid_str((PSID)&max_sid.sid);
2479 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
2480 test_sid_str((PSID)&max_sid.sid);
2481 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
2482 test_sid_str((PSID)&max_sid.sid);
2483 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
2484 test_sid_str((PSID)&max_sid.sid);
2485 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
2486 test_sid_str((PSID)&max_sid.sid);
2487 max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
2488 test_sid_str((PSID)&max_sid.sid);
2489 max_sid.sid.SubAuthority[count] = 1000; /* first user account */
2490 test_sid_str((PSID)&max_sid.sid);
2493 pLsaFreeMemory((LPVOID)info);
2496 status = pLsaClose(handle);
2497 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
2503 static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
2505 static CHAR account[UNLEN + 1];
2506 static CHAR domain[UNLEN + 1];
2507 DWORD size, dom_size;
2508 SID_NAME_USE use;
2510 *user = account;
2511 *dom = domain;
2513 size = dom_size = UNLEN + 1;
2514 account[0] = '\0';
2515 domain[0] = '\0';
2516 SetLastError(0xdeadbeef);
2517 return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
2520 static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
2522 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
2523 PSID domainsid = NULL;
2524 char wk_sid[SECURITY_MAX_SID_SIZE];
2525 DWORD cb;
2527 DWORD sid_size, domain_size;
2528 SID_NAME_USE sid_use;
2529 LPSTR domain, account, sid_domain, wk_domain, wk_account;
2530 PSID psid;
2531 BOOL ret ,ret2;
2533 sid_size = 0;
2534 domain_size = 0;
2535 ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2536 ok(!ret, " %s Should have failed to lookup account name\n", name);
2537 psid = HeapAlloc(GetProcessHeap(),0,sid_size);
2538 domain = HeapAlloc(GetProcessHeap(),0,domain_size);
2539 ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);
2541 if (!result)
2543 ok(!ret, " %s Should have failed to lookup account name\n",name);
2544 goto cleanup;
2547 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
2548 cb = sizeof(wk_sid);
2549 if (!pCreateWellKnownSid(result, domainsid, wk_sid, &cb))
2551 win_skip("SID %i is not available on the system\n",result);
2552 goto cleanup;
2555 ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
2556 if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
2558 win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
2559 goto cleanup;
2562 get_sid_info(psid, &account, &sid_domain);
2564 ok(ret, "Failed to lookup account name %s\n",name);
2565 ok(sid_size != 0, "sid_size was zero\n");
2567 ok(EqualSid(psid,wk_sid),"%s Sid %s fails to match well known sid %s!\n",
2568 name, debugstr_sid(psid), debugstr_sid(wk_sid));
2570 ok(!lstrcmpA(account, wk_account), "Expected %s , got %s\n", account, wk_account);
2571 ok(!lstrcmpA(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
2572 ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
2574 cleanup:
2575 FreeSid(domainsid);
2576 HeapFree(GetProcessHeap(),0,psid);
2577 HeapFree(GetProcessHeap(),0,domain);
2580 static void test_LookupAccountName(void)
2582 DWORD sid_size, domain_size, user_size;
2583 DWORD sid_save, domain_save;
2584 CHAR user_name[UNLEN + 1];
2585 CHAR computer_name[UNLEN + 1];
2586 SID_NAME_USE sid_use;
2587 LPSTR domain, account, sid_dom;
2588 PSID psid;
2589 BOOL ret;
2591 /* native crashes if (assuming all other parameters correct):
2592 * - peUse is NULL
2593 * - Sid is NULL and cbSid is > 0
2594 * - cbSid or cchReferencedDomainName are NULL
2595 * - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
2598 user_size = UNLEN + 1;
2599 SetLastError(0xdeadbeef);
2600 ret = GetUserNameA(user_name, &user_size);
2601 ok(ret, "Failed to get user name : %d\n", GetLastError());
2603 /* get sizes */
2604 sid_size = 0;
2605 domain_size = 0;
2606 sid_use = 0xcafebabe;
2607 SetLastError(0xdeadbeef);
2608 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2609 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2611 win_skip("LookupAccountNameA is not implemented\n");
2612 return;
2614 ok(!ret, "Expected 0, got %d\n", ret);
2615 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2616 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2617 ok(sid_size != 0, "Expected non-zero sid size\n");
2618 ok(domain_size != 0, "Expected non-zero domain size\n");
2619 ok(sid_use == (SID_NAME_USE)0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2621 sid_save = sid_size;
2622 domain_save = domain_size;
2624 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2625 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2627 /* try valid account name */
2628 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
2629 get_sid_info(psid, &account, &sid_dom);
2630 ok(ret, "Failed to lookup account name\n");
2631 ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
2632 ok(!lstrcmpA(account, user_name), "Expected %s, got %s\n", user_name, account);
2633 ok(!lstrcmpiA(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2634 ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
2635 ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlenA(domain), domain_size);
2636 ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
2637 domain_size = domain_save;
2638 sid_size = sid_save;
2640 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2642 skip("Non-English locale (test with hardcoded 'Everyone')\n");
2644 else
2646 ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
2647 get_sid_info(psid, &account, &sid_dom);
2648 ok(ret, "Failed to lookup account name\n");
2649 ok(sid_size != 0, "sid_size was zero\n");
2650 ok(!lstrcmpA(account, "Everyone"), "Expected Everyone, got %s\n", account);
2651 ok(!lstrcmpiA(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
2652 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2653 ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlenA(domain), domain_size);
2654 ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
2655 domain_size = domain_save;
2658 /* NULL Sid with zero sid size */
2659 SetLastError(0xdeadbeef);
2660 sid_size = 0;
2661 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
2662 ok(!ret, "Expected 0, got %d\n", ret);
2663 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2664 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2665 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2666 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2668 /* try cchReferencedDomainName - 1 */
2669 SetLastError(0xdeadbeef);
2670 domain_size--;
2671 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
2672 ok(!ret, "Expected 0, got %d\n", ret);
2673 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2674 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2675 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2676 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2678 /* NULL ReferencedDomainName with zero domain name size */
2679 SetLastError(0xdeadbeef);
2680 domain_size = 0;
2681 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
2682 ok(!ret, "Expected 0, got %d\n", ret);
2683 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2684 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2685 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
2686 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
2688 HeapFree(GetProcessHeap(), 0, psid);
2689 HeapFree(GetProcessHeap(), 0, domain);
2691 /* get sizes for NULL account name */
2692 sid_size = 0;
2693 domain_size = 0;
2694 sid_use = 0xcafebabe;
2695 SetLastError(0xdeadbeef);
2696 ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2697 if (!ret && GetLastError() == ERROR_NONE_MAPPED)
2698 win_skip("NULL account name doesn't work on NT4\n");
2699 else
2701 ok(!ret, "Expected 0, got %d\n", ret);
2702 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2703 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2704 ok(sid_size != 0, "Expected non-zero sid size\n");
2705 ok(domain_size != 0, "Expected non-zero domain size\n");
2706 ok(sid_use == (SID_NAME_USE)0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2708 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2709 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2711 /* try NULL account name */
2712 ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
2713 get_sid_info(psid, &account, &sid_dom);
2714 ok(ret, "Failed to lookup account name\n");
2715 /* Using a fixed string will not work on different locales */
2716 ok(!lstrcmpiA(account, domain),
2717 "Got %s for account and %s for domain, these should be the same\n", account, domain);
2718 ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
2720 HeapFree(GetProcessHeap(), 0, psid);
2721 HeapFree(GetProcessHeap(), 0, domain);
2724 /* try an invalid account name */
2725 SetLastError(0xdeadbeef);
2726 sid_size = 0;
2727 domain_size = 0;
2728 ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
2729 ok(!ret, "Expected 0, got %d\n", ret);
2730 ok(GetLastError() == ERROR_NONE_MAPPED ||
2731 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
2732 "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
2733 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2734 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2736 /* try an invalid system name */
2737 SetLastError(0xdeadbeef);
2738 sid_size = 0;
2739 domain_size = 0;
2740 ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2741 ok(!ret, "Expected 0, got %d\n", ret);
2742 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2743 "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
2744 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2745 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2747 /* try with the computer name as the account name */
2748 domain_size = sizeof(computer_name);
2749 GetComputerNameA(computer_name, &domain_size);
2750 sid_size = 0;
2751 domain_size = 0;
2752 ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2753 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
2754 GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
2755 broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
2756 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
2757 "LookupAccountNameA failed: %d\n", GetLastError());
2758 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2760 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2761 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2762 ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
2763 ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
2764 ok(sid_use == SidTypeDomain ||
2765 (sid_use == SidTypeUser && ! strcmp(computer_name, user_name)), "expected SidTypeDomain for %s, got %d\n", computer_name, sid_use);
2766 HeapFree(GetProcessHeap(), 0, domain);
2767 HeapFree(GetProcessHeap(), 0, psid);
2770 /* Well Known names */
2771 if (!pCreateWellKnownSid)
2773 win_skip("CreateWellKnownSid not available\n");
2774 return;
2777 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
2779 skip("Non-English locale (skipping well known name creation tests)\n");
2780 return;
2783 check_wellknown_name("LocalService", WinLocalServiceSid);
2784 check_wellknown_name("Local Service", WinLocalServiceSid);
2785 /* 2 spaces */
2786 check_wellknown_name("Local Service", 0);
2787 check_wellknown_name("NetworkService", WinNetworkServiceSid);
2788 check_wellknown_name("Network Service", WinNetworkServiceSid);
2790 /* example of some names where the spaces are not optional */
2791 check_wellknown_name("Terminal Server User", WinTerminalServerSid);
2792 check_wellknown_name("TerminalServer User", 0);
2793 check_wellknown_name("TerminalServerUser", 0);
2794 check_wellknown_name("Terminal ServerUser", 0);
2796 check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
2797 check_wellknown_name("enterprisedomain controllers", 0);
2798 check_wellknown_name("enterprise domaincontrollers", 0);
2799 check_wellknown_name("enterprisedomaincontrollers", 0);
2801 /* case insensitivity */
2802 check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
2804 /* fully qualified account names */
2805 check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
2806 check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
2807 check_wellknown_name("nt authority test\\Network Service", 0);
2808 check_wellknown_name("Dummy\\Network Service", 0);
2809 check_wellknown_name("ntauthority\\Network Service", 0);
2812 static void test_security_descriptor(void)
2814 SECURITY_DESCRIPTOR sd, *sd_rel, *sd_rel2, *sd_abs;
2815 char buf[8192];
2816 DWORD size, size_dacl, size_sacl, size_owner, size_group;
2817 BOOL isDefault, isPresent, ret;
2818 PACL pacl, dacl, sacl;
2819 PSID psid, owner, group;
2821 SetLastError(0xdeadbeef);
2822 ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
2823 if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2825 win_skip("InitializeSecurityDescriptor is not implemented\n");
2826 return;
2829 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2830 expect_eq(psid, NULL, PSID, "%p");
2831 expect_eq(isDefault, FALSE, BOOL, "%d");
2832 sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
2834 SetLastError(0xdeadbeef);
2835 size = 5;
2836 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
2837 expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
2838 ok(size > 5, "Size not increased\n");
2839 if (size <= 8192)
2841 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
2842 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2843 expect_eq(psid, NULL, PSID, "%p");
2844 expect_eq(isDefault, FALSE, BOOL, "%d");
2845 ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
2846 expect_eq(psid, NULL, PSID, "%p");
2847 expect_eq(isDefault, FALSE, BOOL, "%d");
2848 ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
2849 expect_eq(isPresent, TRUE, BOOL, "%d");
2850 expect_eq(psid, NULL, PSID, "%p");
2851 expect_eq(isDefault, FALSE, BOOL, "%d");
2852 ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
2853 expect_eq(isPresent, TRUE, BOOL, "%d");
2854 expect_eq(psid, NULL, PSID, "%p");
2855 expect_eq(isDefault, FALSE, BOOL, "%d");
2858 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2859 "O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
2860 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)"
2861 "(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, (void **)&sd_rel, NULL);
2862 ok(ret, "got %u\n", GetLastError());
2864 size = 0;
2865 ret = MakeSelfRelativeSD(sd_rel, NULL, &size);
2866 todo_wine ok(!ret && GetLastError() == ERROR_BAD_DESCRIPTOR_FORMAT, "got %u\n", GetLastError());
2868 /* convert to absolute form */
2869 size = size_dacl = size_sacl = size_owner = size_group = 0;
2870 ret = MakeAbsoluteSD(sd_rel, NULL, &size, NULL, &size_dacl, NULL, &size_sacl, NULL, &size_owner, NULL,
2871 &size_group);
2872 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %u\n", GetLastError());
2874 sd_abs = HeapAlloc(GetProcessHeap(), 0, size + size_dacl + size_sacl + size_owner + size_group);
2875 dacl = (PACL)(sd_abs + 1);
2876 sacl = (PACL)((char *)dacl + size_dacl);
2877 owner = (PSID)((char *)sacl + size_sacl);
2878 group = (PSID)((char *)owner + size_owner);
2879 ret = MakeAbsoluteSD(sd_rel, sd_abs, &size, dacl, &size_dacl, sacl, &size_sacl, owner, &size_owner,
2880 group, &size_group);
2881 ok(ret, "got %u\n", GetLastError());
2883 size = 0;
2884 ret = MakeSelfRelativeSD(sd_abs, NULL, &size);
2885 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %u\n", GetLastError());
2886 ok(size == 184, "got %u\n", size);
2888 size += 4;
2889 sd_rel2 = HeapAlloc(GetProcessHeap(), 0, size);
2890 ret = MakeSelfRelativeSD(sd_abs, sd_rel2, &size);
2891 ok(ret, "got %u\n", GetLastError());
2892 ok(size == 188, "got %u\n", size);
2894 HeapFree(GetProcessHeap(), 0, sd_abs);
2895 HeapFree(GetProcessHeap(), 0, sd_rel2);
2896 LocalFree(sd_rel);
2899 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
2900 #define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
2901 static void test_granted_access(HANDLE handle, ACCESS_MASK access,
2902 ACCESS_MASK alt, int line)
2904 OBJECT_BASIC_INFORMATION obj_info;
2905 NTSTATUS status;
2907 if (!pNtQueryObject)
2909 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
2910 return;
2913 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
2914 sizeof(obj_info), NULL );
2915 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2916 if (alt)
2917 ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
2918 obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
2919 "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
2920 else
2921 ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
2922 "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
2925 #define CHECK_SET_SECURITY(o,i,e) \
2926 do{ \
2927 BOOL res_; \
2928 DWORD err; \
2929 SetLastError( 0xdeadbeef ); \
2930 res_ = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
2931 err = GetLastError(); \
2932 if (e == ERROR_SUCCESS) \
2933 ok(res_, "SetKernelObjectSecurity failed with %d\n", err); \
2934 else \
2935 ok(!res_ && err == e, "SetKernelObjectSecurity should have failed " \
2936 "with %s, instead of %d\n", #e, err); \
2937 }while(0)
2939 static void test_process_security(void)
2941 BOOL res;
2942 PTOKEN_USER user;
2943 PTOKEN_OWNER owner;
2944 PTOKEN_PRIMARY_GROUP group;
2945 PSID AdminSid = NULL, UsersSid = NULL, UserSid = NULL;
2946 PACL Acl = NULL, ThreadAcl = NULL;
2947 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL, *ThreadSecurityDescriptor = NULL;
2948 char buffer[MAX_PATH], account[MAX_PATH], domain[MAX_PATH];
2949 PROCESS_INFORMATION info;
2950 STARTUPINFOA startup;
2951 SECURITY_ATTRIBUTES psa, tsa;
2952 HANDLE token, event;
2953 DWORD size, acc_size, dom_size, ret;
2954 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2955 PSID EveryoneSid = NULL;
2956 SID_NAME_USE use;
2958 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
2959 res = InitializeAcl(Acl, 256, ACL_REVISION);
2960 if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2962 win_skip("ACLs not implemented - skipping tests\n");
2963 HeapFree(GetProcessHeap(), 0, Acl);
2964 return;
2966 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2968 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2969 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2971 /* get owner from the token we might be running as a user not admin */
2972 res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
2973 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
2974 if (!res)
2976 HeapFree(GetProcessHeap(), 0, Acl);
2977 return;
2980 res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
2981 ok(!res, "Expected failure, got %d\n", res);
2982 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2983 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2985 owner = HeapAlloc(GetProcessHeap(), 0, size);
2986 res = GetTokenInformation( token, TokenOwner, owner, size, &size );
2987 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2988 AdminSid = owner->Owner;
2989 test_sid_str(AdminSid);
2991 res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
2992 ok(!res, "Expected failure, got %d\n", res);
2993 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2994 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2996 group = HeapAlloc(GetProcessHeap(), 0, size);
2997 res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
2998 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2999 UsersSid = group->PrimaryGroup;
3000 test_sid_str(UsersSid);
3002 acc_size = sizeof(account);
3003 dom_size = sizeof(domain);
3004 ret = LookupAccountSidA( NULL, UsersSid, account, &acc_size, domain, &dom_size, &use );
3005 ok(ret, "LookupAccountSid failed with %d\n", ret);
3006 todo_wine ok(use == SidTypeGroup, "expect SidTypeGroup, got %d\n", use);
3007 todo_wine ok(!strcmp(account, "None"), "expect None, got %s\n", account);
3009 res = GetTokenInformation( token, TokenUser, NULL, 0, &size );
3010 ok(!res, "Expected failure, got %d\n", res);
3011 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
3012 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
3014 user = HeapAlloc(GetProcessHeap(), 0, size);
3015 res = GetTokenInformation( token, TokenUser, user, size, &size );
3016 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
3017 UserSid = user->User.Sid;
3018 test_sid_str(UserSid);
3019 ok(EqualPrefixSid(UsersSid, UserSid), "TokenPrimaryGroup Sid and TokenUser Sid don't match.\n");
3021 CloseHandle( token );
3022 if (!res)
3024 HeapFree(GetProcessHeap(), 0, group);
3025 HeapFree(GetProcessHeap(), 0, owner);
3026 HeapFree(GetProcessHeap(), 0, user);
3027 HeapFree(GetProcessHeap(), 0, Acl);
3028 return;
3031 res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
3032 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
3033 res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
3034 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3036 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
3037 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
3038 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
3040 event = CreateEventA( NULL, TRUE, TRUE, "test_event" );
3041 ok(event != NULL, "CreateEvent %d\n", GetLastError());
3043 SecurityDescriptor->Revision = 0;
3044 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
3045 SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
3047 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
3048 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
3049 CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
3050 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
3051 /* NULL DACL is valid and means that everyone has access */
3052 SecurityDescriptor->Control |= SE_DACL_PRESENT;
3053 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
3055 /* Set owner and group and dacl */
3056 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
3057 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3058 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
3059 test_owner_equal( event, AdminSid, __LINE__ );
3061 res = SetSecurityDescriptorGroup(SecurityDescriptor, EveryoneSid, FALSE);
3062 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3063 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
3064 test_group_equal( event, EveryoneSid, __LINE__ );
3066 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
3067 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
3068 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
3069 /* setting a dacl should not change the owner or group */
3070 test_owner_equal( event, AdminSid, __LINE__ );
3071 test_group_equal( event, EveryoneSid, __LINE__ );
3073 /* Test again with a different SID in case the previous SID also happens to
3074 * be the one that is incorrectly replacing the group. */
3075 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
3076 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3077 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
3078 test_group_equal( event, UsersSid, __LINE__ );
3080 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
3081 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
3082 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
3083 test_group_equal( event, UsersSid, __LINE__ );
3085 sprintf(buffer, "%s tests/security.c test", myARGV[0]);
3086 memset(&startup, 0, sizeof(startup));
3087 startup.cb = sizeof(startup);
3088 startup.dwFlags = STARTF_USESHOWWINDOW;
3089 startup.wShowWindow = SW_SHOWNORMAL;
3091 psa.nLength = sizeof(psa);
3092 psa.lpSecurityDescriptor = SecurityDescriptor;
3093 psa.bInheritHandle = TRUE;
3095 ThreadSecurityDescriptor = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
3096 res = InitializeSecurityDescriptor( ThreadSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION );
3097 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
3099 ThreadAcl = HeapAlloc( GetProcessHeap(), 0, 256 );
3100 res = InitializeAcl( ThreadAcl, 256, ACL_REVISION );
3101 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
3102 res = AddAccessDeniedAce( ThreadAcl, ACL_REVISION, THREAD_SET_THREAD_TOKEN, AdminSid );
3103 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError() );
3104 res = AddAccessAllowedAce( ThreadAcl, ACL_REVISION, THREAD_ALL_ACCESS, AdminSid );
3105 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3107 res = SetSecurityDescriptorOwner( ThreadSecurityDescriptor, AdminSid, FALSE );
3108 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3109 res = SetSecurityDescriptorGroup( ThreadSecurityDescriptor, UsersSid, FALSE );
3110 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3111 res = SetSecurityDescriptorDacl( ThreadSecurityDescriptor, TRUE, ThreadAcl, FALSE );
3112 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
3114 tsa.nLength = sizeof(tsa);
3115 tsa.lpSecurityDescriptor = ThreadSecurityDescriptor;
3116 tsa.bInheritHandle = TRUE;
3118 /* Doesn't matter what ACL say we should get full access for ourselves */
3119 res = CreateProcessA( NULL, buffer, &psa, &tsa, FALSE, 0, NULL, NULL, &startup, &info );
3120 ok(res, "CreateProcess with err:%d\n", GetLastError());
3121 TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS_NT4,
3122 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
3123 TEST_GRANTED_ACCESS2( info.hThread, THREAD_ALL_ACCESS_NT4,
3124 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
3125 winetest_wait_child_process( info.hProcess );
3127 FreeSid(EveryoneSid);
3128 CloseHandle( info.hProcess );
3129 CloseHandle( info.hThread );
3130 CloseHandle( event );
3131 HeapFree(GetProcessHeap(), 0, group);
3132 HeapFree(GetProcessHeap(), 0, owner);
3133 HeapFree(GetProcessHeap(), 0, user);
3134 HeapFree(GetProcessHeap(), 0, Acl);
3135 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
3136 HeapFree(GetProcessHeap(), 0, ThreadAcl);
3137 HeapFree(GetProcessHeap(), 0, ThreadSecurityDescriptor);
3140 static void test_process_security_child(void)
3142 HANDLE handle, handle1;
3143 BOOL ret;
3144 DWORD err;
3146 handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
3147 ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
3148 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
3150 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
3151 &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS );
3152 ok(ret, "duplicating handle err:%d\n", GetLastError());
3153 TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
3155 CloseHandle( handle1 );
3157 SetLastError( 0xdeadbeef );
3158 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
3159 &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
3160 err = GetLastError();
3161 ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
3162 "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
3164 CloseHandle( handle );
3166 /* These two should fail - they are denied by ACL */
3167 handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
3168 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
3169 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
3170 ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
3172 /* Documented privilege elevation */
3173 ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
3174 &handle, 0, TRUE, DUPLICATE_SAME_ACCESS );
3175 ok(ret, "duplicating handle err:%d\n", GetLastError());
3176 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
3177 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
3179 CloseHandle( handle );
3181 /* Same only explicitly asking for all access rights */
3182 ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
3183 &handle, PROCESS_ALL_ACCESS, TRUE, 0 );
3184 ok(ret, "duplicating handle err:%d\n", GetLastError());
3185 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
3186 PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
3187 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
3188 &handle1, PROCESS_VM_READ, TRUE, 0 );
3189 ok(ret, "duplicating handle err:%d\n", GetLastError());
3190 TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
3191 CloseHandle( handle1 );
3192 CloseHandle( handle );
3194 /* Test thread security */
3195 handle = OpenThread( THREAD_TERMINATE, FALSE, GetCurrentThreadId() );
3196 ok(handle != NULL, "OpenThread(THREAD_TERMINATE) with err:%d\n", GetLastError());
3197 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
3198 CloseHandle( handle );
3200 handle = OpenThread( THREAD_SET_THREAD_TOKEN, FALSE, GetCurrentThreadId() );
3201 ok(handle == NULL, "OpenThread(THREAD_SET_THREAD_TOKEN) should have failed\n");
3204 static void test_impersonation_level(void)
3206 HANDLE Token, ProcessToken;
3207 HANDLE Token2;
3208 DWORD Size;
3209 TOKEN_PRIVILEGES *Privileges;
3210 TOKEN_USER *User;
3211 PRIVILEGE_SET *PrivilegeSet;
3212 BOOL AccessGranted;
3213 BOOL ret;
3214 HKEY hkey;
3215 DWORD error;
3217 if( !pDuplicateTokenEx ) {
3218 win_skip("DuplicateTokenEx is not available\n");
3219 return;
3221 SetLastError(0xdeadbeef);
3222 ret = ImpersonateSelf(SecurityAnonymous);
3223 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3225 win_skip("ImpersonateSelf is not implemented\n");
3226 return;
3228 ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
3229 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
3230 ok(!ret, "OpenThreadToken should have failed\n");
3231 error = GetLastError();
3232 ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
3233 /* can't perform access check when opening object against an anonymous impersonation token */
3234 todo_wine {
3235 error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
3236 ok(error == ERROR_INVALID_HANDLE || error == ERROR_CANT_OPEN_ANONYMOUS || error == ERROR_BAD_IMPERSONATION_LEVEL,
3237 "RegOpenKeyEx failed with %d\n", error);
3239 RevertToSelf();
3241 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
3242 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
3244 ret = pDuplicateTokenEx(ProcessToken,
3245 TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
3246 SecurityAnonymous, TokenImpersonation, &Token);
3247 ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
3248 /* can't increase the impersonation level */
3249 ret = DuplicateToken(Token, SecurityIdentification, &Token2);
3250 error = GetLastError();
3251 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
3252 "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
3253 /* we can query anything from an anonymous token, including the user */
3254 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
3255 error = GetLastError();
3256 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
3257 User = HeapAlloc(GetProcessHeap(), 0, Size);
3258 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
3259 ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3260 HeapFree(GetProcessHeap(), 0, User);
3262 /* PrivilegeCheck fails with SecurityAnonymous level */
3263 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
3264 error = GetLastError();
3265 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
3266 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
3267 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
3268 ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
3270 PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
3271 PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
3272 memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
3273 PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
3274 HeapFree(GetProcessHeap(), 0, Privileges);
3276 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
3277 error = GetLastError();
3278 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
3280 CloseHandle(Token);
3282 ret = ImpersonateSelf(SecurityIdentification);
3283 ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
3284 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
3285 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
3287 /* can't perform access check when opening object against an identification impersonation token */
3288 error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
3289 todo_wine {
3290 ok(error == ERROR_INVALID_HANDLE || error == ERROR_BAD_IMPERSONATION_LEVEL || error == ERROR_ACCESS_DENIED,
3291 "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE, ERROR_BAD_IMPERSONATION_LEVEL or ERROR_ACCESS_DENIED instead of %d\n", error);
3293 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
3294 ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
3295 CloseHandle(Token);
3296 RevertToSelf();
3298 ret = ImpersonateSelf(SecurityImpersonation);
3299 ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
3300 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
3301 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
3302 error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
3303 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
3304 RegCloseKey(hkey);
3305 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
3306 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
3307 RevertToSelf();
3309 CloseHandle(Token);
3310 CloseHandle(ProcessToken);
3312 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
3315 static void test_SetEntriesInAclW(void)
3317 DWORD res;
3318 PSID EveryoneSid = NULL, UsersSid = NULL;
3319 PACL OldAcl = NULL, NewAcl;
3320 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
3321 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3322 EXPLICIT_ACCESSW ExplicitAccess;
3323 static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
3324 static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
3326 if (!pSetEntriesInAclW)
3328 win_skip("SetEntriesInAclW is not available\n");
3329 return;
3332 NewAcl = (PACL)0xdeadbeef;
3333 res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
3334 if(res == ERROR_CALL_NOT_IMPLEMENTED)
3336 win_skip("SetEntriesInAclW is not implemented\n");
3337 return;
3339 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3340 ok(NewAcl == NULL ||
3341 broken(NewAcl != NULL), /* NT4 */
3342 "NewAcl=%p, expected NULL\n", NewAcl);
3343 LocalFree(NewAcl);
3345 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
3346 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
3347 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3349 win_skip("ACLs not implemented - skipping tests\n");
3350 HeapFree(GetProcessHeap(), 0, OldAcl);
3351 return;
3353 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
3355 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
3356 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3358 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
3359 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
3360 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3362 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
3363 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3365 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
3366 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
3367 ExplicitAccess.grfInheritance = NO_INHERITANCE;
3368 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
3369 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3370 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
3371 ExplicitAccess.Trustee.MultipleTrusteeOperation = 0xDEADBEEF;
3372 ExplicitAccess.Trustee.pMultipleTrustee = (PVOID)0xDEADBEEF;
3373 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3374 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3375 ok(NewAcl != NULL, "returned acl was NULL\n");
3376 LocalFree(NewAcl);
3378 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
3379 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
3380 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3381 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3382 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3383 ok(NewAcl != NULL, "returned acl was NULL\n");
3384 LocalFree(NewAcl);
3386 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
3388 skip("Non-English locale (test with hardcoded 'Everyone')\n");
3390 else
3392 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3393 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
3394 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3395 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3396 ok(NewAcl != NULL, "returned acl was NULL\n");
3397 LocalFree(NewAcl);
3399 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
3400 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3401 ok(res == ERROR_INVALID_PARAMETER ||
3402 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3403 "SetEntriesInAclW failed: %u\n", res);
3404 ok(NewAcl == NULL ||
3405 broken(NewAcl != NULL), /* NT4 */
3406 "returned acl wasn't NULL: %p\n", NewAcl);
3408 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3409 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
3410 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3411 ok(res == ERROR_INVALID_PARAMETER ||
3412 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3413 "SetEntriesInAclW failed: %u\n", res);
3414 ok(NewAcl == NULL ||
3415 broken(NewAcl != NULL), /* NT4 */
3416 "returned acl wasn't NULL: %p\n", NewAcl);
3418 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3419 ExplicitAccess.grfAccessMode = SET_ACCESS;
3420 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3421 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3422 ok(NewAcl != NULL, "returned acl was NULL\n");
3423 LocalFree(NewAcl);
3426 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3427 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
3428 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3429 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3430 ok(NewAcl != NULL, "returned acl was NULL\n");
3431 LocalFree(NewAcl);
3433 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
3434 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3435 ExplicitAccess.Trustee.ptstrName = UsersSid;
3436 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
3437 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
3438 ok(NewAcl != NULL, "returned acl was NULL\n");
3439 LocalFree(NewAcl);
3441 FreeSid(UsersSid);
3442 FreeSid(EveryoneSid);
3443 HeapFree(GetProcessHeap(), 0, OldAcl);
3446 static void test_SetEntriesInAclA(void)
3448 DWORD res;
3449 PSID EveryoneSid = NULL, UsersSid = NULL;
3450 PACL OldAcl = NULL, NewAcl;
3451 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
3452 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3453 EXPLICIT_ACCESSA ExplicitAccess;
3454 static const CHAR szEveryone[] = {'E','v','e','r','y','o','n','e',0};
3455 static const CHAR szCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
3457 if (!pSetEntriesInAclA)
3459 win_skip("SetEntriesInAclA is not available\n");
3460 return;
3463 NewAcl = (PACL)0xdeadbeef;
3464 res = pSetEntriesInAclA(0, NULL, NULL, &NewAcl);
3465 if(res == ERROR_CALL_NOT_IMPLEMENTED)
3467 win_skip("SetEntriesInAclA is not implemented\n");
3468 return;
3470 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3471 ok(NewAcl == NULL ||
3472 broken(NewAcl != NULL), /* NT4 */
3473 "NewAcl=%p, expected NULL\n", NewAcl);
3474 LocalFree(NewAcl);
3476 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
3477 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
3478 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3480 win_skip("ACLs not implemented - skipping tests\n");
3481 HeapFree(GetProcessHeap(), 0, OldAcl);
3482 return;
3484 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
3486 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
3487 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3489 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
3490 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
3491 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
3493 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
3494 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
3496 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
3497 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
3498 ExplicitAccess.grfInheritance = NO_INHERITANCE;
3499 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
3500 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3501 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
3502 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3503 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
3504 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3505 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3506 ok(NewAcl != NULL, "returned acl was NULL\n");
3507 LocalFree(NewAcl);
3509 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
3510 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
3511 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3512 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3513 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3514 ok(NewAcl != NULL, "returned acl was NULL\n");
3515 LocalFree(NewAcl);
3517 if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
3519 skip("Non-English locale (test with hardcoded 'Everyone')\n");
3521 else
3523 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3524 ExplicitAccess.Trustee.ptstrName = (LPSTR)szEveryone;
3525 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3526 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3527 ok(NewAcl != NULL, "returned acl was NULL\n");
3528 LocalFree(NewAcl);
3530 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
3531 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3532 ok(res == ERROR_INVALID_PARAMETER ||
3533 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3534 "SetEntriesInAclA failed: %u\n", res);
3535 ok(NewAcl == NULL ||
3536 broken(NewAcl != NULL), /* NT4 */
3537 "returned acl wasn't NULL: %p\n", NewAcl);
3539 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3540 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
3541 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3542 ok(res == ERROR_INVALID_PARAMETER ||
3543 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
3544 "SetEntriesInAclA failed: %u\n", res);
3545 ok(NewAcl == NULL ||
3546 broken(NewAcl != NULL), /* NT4 */
3547 "returned acl wasn't NULL: %p\n", NewAcl);
3549 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3550 ExplicitAccess.grfAccessMode = SET_ACCESS;
3551 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3552 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3553 ok(NewAcl != NULL, "returned acl was NULL\n");
3554 LocalFree(NewAcl);
3557 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
3558 ExplicitAccess.Trustee.ptstrName = (LPSTR)szCurrentUser;
3559 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3560 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3561 ok(NewAcl != NULL, "returned acl was NULL\n");
3562 LocalFree(NewAcl);
3564 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
3565 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
3566 ExplicitAccess.Trustee.ptstrName = UsersSid;
3567 res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
3568 ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
3569 ok(NewAcl != NULL, "returned acl was NULL\n");
3570 LocalFree(NewAcl);
3572 FreeSid(UsersSid);
3573 FreeSid(EveryoneSid);
3574 HeapFree(GetProcessHeap(), 0, OldAcl);
3577 /* helper function for test_CreateDirectoryA */
3578 static void get_nt_pathW(const char *name, UNICODE_STRING *nameW)
3580 UNICODE_STRING strW;
3581 ANSI_STRING str;
3582 NTSTATUS status;
3583 BOOLEAN ret;
3585 pRtlInitAnsiString(&str, name);
3587 status = pRtlAnsiStringToUnicodeString(&strW, &str, TRUE);
3588 ok(!status, "RtlAnsiStringToUnicodeString failed with %08x\n", status);
3590 ret = pRtlDosPathNameToNtPathName_U(strW.Buffer, nameW, NULL, NULL);
3591 ok(ret, "RtlDosPathNameToNtPathName_U failed\n");
3593 pRtlFreeUnicodeString(&strW);
3596 static void test_inherited_dacl(PACL dacl, PSID admin_sid, PSID user_sid, DWORD flags, DWORD mask,
3597 BOOL todo_count, BOOL todo_sid, BOOL todo_flags, int line)
3599 ACL_SIZE_INFORMATION acl_size;
3600 ACCESS_ALLOWED_ACE *ace;
3601 BOOL bret;
3603 bret = pGetAclInformation(dacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3604 ok_(__FILE__, line)(bret, "GetAclInformation failed\n");
3606 todo_wine_if (todo_count)
3607 ok_(__FILE__, line)(acl_size.AceCount == 2,
3608 "GetAclInformation returned unexpected entry count (%d != 2)\n",
3609 acl_size.AceCount);
3611 if (acl_size.AceCount > 0)
3613 bret = pGetAce(dacl, 0, (VOID **)&ace);
3614 ok_(__FILE__, line)(bret, "Failed to get Current User ACE\n");
3616 bret = EqualSid(&ace->SidStart, user_sid);
3617 todo_wine_if (todo_sid)
3618 ok_(__FILE__, line)(bret, "Current User ACE (%s) != Current User SID (%s)\n", debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
3620 todo_wine_if (todo_flags)
3621 ok_(__FILE__, line)(((ACE_HEADER *)ace)->AceFlags == flags,
3622 "Current User ACE has unexpected flags (0x%x != 0x%x)\n",
3623 ((ACE_HEADER *)ace)->AceFlags, flags);
3625 ok_(__FILE__, line)(ace->Mask == mask,
3626 "Current User ACE has unexpected mask (0x%x != 0x%x)\n",
3627 ace->Mask, mask);
3629 if (acl_size.AceCount > 1)
3631 bret = pGetAce(dacl, 1, (VOID **)&ace);
3632 ok_(__FILE__, line)(bret, "Failed to get Administators Group ACE\n");
3634 bret = EqualSid(&ace->SidStart, admin_sid);
3635 todo_wine_if (todo_sid)
3636 ok_(__FILE__, line)(bret, "Administators Group ACE (%s) != Administators Group SID (%s)\n", debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
3638 todo_wine_if (todo_flags)
3639 ok_(__FILE__, line)(((ACE_HEADER *)ace)->AceFlags == flags,
3640 "Administators Group ACE has unexpected flags (0x%x != 0x%x)\n",
3641 ((ACE_HEADER *)ace)->AceFlags, flags);
3643 ok_(__FILE__, line)(ace->Mask == mask,
3644 "Administators Group ACE has unexpected mask (0x%x != 0x%x)\n",
3645 ace->Mask, mask);
3649 static void test_CreateDirectoryA(void)
3651 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
3652 DWORD sid_size = sizeof(admin_ptr), user_size;
3653 PSID admin_sid = (PSID) admin_ptr, user_sid;
3654 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
3655 PSECURITY_DESCRIPTOR pSD = &sd;
3656 ACL_SIZE_INFORMATION acl_size;
3657 UNICODE_STRING tmpfileW;
3658 SECURITY_ATTRIBUTES sa;
3659 OBJECT_ATTRIBUTES attr;
3660 char tmpfile[MAX_PATH];
3661 char tmpdir[MAX_PATH];
3662 HANDLE token, hTemp;
3663 IO_STATUS_BLOCK io;
3664 struct _SID *owner;
3665 BOOL bret = TRUE;
3666 NTSTATUS status;
3667 DWORD error;
3668 PACL pDacl;
3670 if (!pGetSecurityInfo || !pGetNamedSecurityInfoA || !pCreateWellKnownSid)
3672 win_skip("Required functions are not available\n");
3673 return;
3676 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3678 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3679 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3681 if (!bret)
3683 win_skip("Failed to get current user token\n");
3684 return;
3686 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3687 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3688 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3689 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3690 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3691 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3692 CloseHandle( token );
3693 user_sid = ((TOKEN_USER *)user)->User.Sid;
3695 sa.nLength = sizeof(sa);
3696 sa.lpSecurityDescriptor = pSD;
3697 sa.bInheritHandle = TRUE;
3698 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3699 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
3700 pDacl = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 100);
3701 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
3702 ok(bret, "Failed to initialize ACL.\n");
3703 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3704 GENERIC_ALL, user_sid);
3705 ok(bret, "Failed to add Current User to ACL.\n");
3706 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3707 GENERIC_ALL, admin_sid);
3708 ok(bret, "Failed to add Administrator Group to ACL.\n");
3709 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3710 ok(bret, "Failed to add ACL to security descriptor.\n");
3712 GetTempPathA(MAX_PATH, tmpdir);
3713 lstrcatA(tmpdir, "Please Remove Me");
3714 bret = CreateDirectoryA(tmpdir, &sa);
3715 ok(bret == TRUE, "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
3716 HeapFree(GetProcessHeap(), 0, pDacl);
3718 SetLastError(0xdeadbeef);
3719 error = pGetNamedSecurityInfoA(tmpdir, SE_FILE_OBJECT,
3720 OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, (PSID*)&owner,
3721 NULL, &pDacl, NULL, &pSD);
3722 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3724 win_skip("GetNamedSecurityInfoA is not implemented\n");
3725 goto done;
3727 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3728 test_inherited_dacl(pDacl, admin_sid, user_sid, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
3729 0x1f01ff, FALSE, TRUE, FALSE, __LINE__);
3730 LocalFree(pSD);
3732 /* Test inheritance of ACLs in CreateFile without security descriptor */
3733 strcpy(tmpfile, tmpdir);
3734 lstrcatA(tmpfile, "/tmpfile");
3736 hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3737 CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
3738 ok(hTemp != INVALID_HANDLE_VALUE, "CreateFile error %u\n", GetLastError());
3740 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3741 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3742 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3743 ok(error == ERROR_SUCCESS, "Failed to get permissions on file\n");
3744 test_inherited_dacl(pDacl, admin_sid, user_sid, INHERITED_ACE,
3745 0x1f01ff, TRUE, TRUE, TRUE, __LINE__);
3746 LocalFree(pSD);
3747 CloseHandle(hTemp);
3749 /* Test inheritance of ACLs in CreateFile with security descriptor -
3750 * When a security descriptor is set, then inheritance doesn't take effect */
3751 pSD = &sd;
3752 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3753 pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
3754 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
3755 ok(bret, "Failed to initialize ACL\n");
3756 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3757 ok(bret, "Failed to add ACL to security descriptor\n");
3759 strcpy(tmpfile, tmpdir);
3760 lstrcatA(tmpfile, "/tmpfile");
3762 sa.nLength = sizeof(sa);
3763 sa.lpSecurityDescriptor = pSD;
3764 sa.bInheritHandle = TRUE;
3765 hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, &sa,
3766 CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
3767 ok(hTemp != INVALID_HANDLE_VALUE, "CreateFile error %u\n", GetLastError());
3768 HeapFree(GetProcessHeap(), 0, pDacl);
3770 error = pGetSecurityInfo(hTemp, SE_FILE_OBJECT,
3771 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 = pGetAclInformation(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 = pGetAclInformation(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 /* Test inheritance of ACLs in NtCreateFile without security descriptor */
3798 strcpy(tmpfile, tmpdir);
3799 lstrcatA(tmpfile, "/tmpfile");
3800 get_nt_pathW(tmpfile, &tmpfileW);
3802 attr.Length = sizeof(attr);
3803 attr.RootDirectory = 0;
3804 attr.ObjectName = &tmpfileW;
3805 attr.Attributes = OBJ_CASE_INSENSITIVE;
3806 attr.SecurityDescriptor = NULL;
3807 attr.SecurityQualityOfService = NULL;
3809 status = pNtCreateFile(&hTemp, GENERIC_WRITE | DELETE, &attr, &io, NULL, 0,
3810 FILE_SHARE_READ, FILE_CREATE, FILE_DELETE_ON_CLOSE, NULL, 0);
3811 ok(!status, "NtCreateFile failed with %08x\n", status);
3812 pRtlFreeUnicodeString(&tmpfileW);
3814 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3815 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3816 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3817 ok(error == ERROR_SUCCESS, "Failed to get permissions on file\n");
3818 test_inherited_dacl(pDacl, admin_sid, user_sid, INHERITED_ACE,
3819 0x1f01ff, TRUE, TRUE, TRUE, __LINE__);
3820 LocalFree(pSD);
3821 CloseHandle(hTemp);
3823 /* Test inheritance of ACLs in NtCreateFile with security descriptor -
3824 * When a security descriptor is set, then inheritance doesn't take effect */
3825 pSD = &sd;
3826 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
3827 pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
3828 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
3829 ok(bret, "Failed to initialize ACL\n");
3830 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
3831 ok(bret, "Failed to add ACL to security descriptor\n");
3833 strcpy(tmpfile, tmpdir);
3834 lstrcatA(tmpfile, "/tmpfile");
3835 get_nt_pathW(tmpfile, &tmpfileW);
3837 attr.Length = sizeof(attr);
3838 attr.RootDirectory = 0;
3839 attr.ObjectName = &tmpfileW;
3840 attr.Attributes = OBJ_CASE_INSENSITIVE;
3841 attr.SecurityDescriptor = pSD;
3842 attr.SecurityQualityOfService = NULL;
3844 status = pNtCreateFile(&hTemp, GENERIC_WRITE | DELETE, &attr, &io, NULL, 0,
3845 FILE_SHARE_READ, FILE_CREATE, FILE_DELETE_ON_CLOSE, NULL, 0);
3846 ok(!status, "NtCreateFile failed with %08x\n", status);
3847 pRtlFreeUnicodeString(&tmpfileW);
3848 HeapFree(GetProcessHeap(), 0, pDacl);
3850 error = pGetSecurityInfo(hTemp, SE_FILE_OBJECT,
3851 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3852 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3853 ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
3854 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3855 ok(bret, "GetAclInformation failed\n");
3856 todo_wine
3857 ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
3858 acl_size.AceCount);
3859 LocalFree(pSD);
3861 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
3862 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
3863 (PSID *)&owner, NULL, &pDacl, NULL, &pSD);
3864 todo_wine
3865 ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
3866 if (error == ERROR_SUCCESS)
3868 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
3869 ok(bret, "GetAclInformation failed\n");
3870 todo_wine
3871 ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
3872 acl_size.AceCount);
3873 LocalFree(pSD);
3875 CloseHandle(hTemp);
3877 done:
3878 HeapFree(GetProcessHeap(), 0, user);
3879 bret = RemoveDirectoryA(tmpdir);
3880 ok(bret == TRUE, "RemoveDirectoryA should always succeed\n");
3883 static void test_GetNamedSecurityInfoA(void)
3885 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
3886 char system_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
3887 char users_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
3888 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
3889 PSID admin_sid = (PSID) admin_ptr, users_sid = (PSID) users_ptr;
3890 PSID system_sid = (PSID) system_ptr, user_sid, localsys_sid;
3891 DWORD sid_size = sizeof(admin_ptr), user_size;
3892 char invalid_path[] = "/an invalid file path";
3893 int users_ace_id = -1, admins_ace_id = -1, i;
3894 char software_key[] = "MACHINE\\Software";
3895 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH+sizeof(void*)];
3896 SECURITY_DESCRIPTOR_CONTROL control;
3897 ACL_SIZE_INFORMATION acl_size;
3898 CHAR windows_dir[MAX_PATH];
3899 PSECURITY_DESCRIPTOR pSD;
3900 ACCESS_ALLOWED_ACE *ace;
3901 BOOL bret = TRUE, isNT4;
3902 char tmpfile[MAX_PATH];
3903 DWORD error, revision;
3904 BOOL owner_defaulted;
3905 BOOL group_defaulted;
3906 BOOL dacl_defaulted;
3907 HANDLE token, hTemp, h;
3908 PSID owner, group;
3909 BOOL dacl_present;
3910 PACL pDacl;
3911 BYTE flags;
3912 NTSTATUS status;
3914 if (!pSetNamedSecurityInfoA || !pGetNamedSecurityInfoA || !pCreateWellKnownSid)
3916 win_skip("Required functions are not available\n");
3917 return;
3920 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
3922 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
3923 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
3925 if (!bret)
3927 win_skip("Failed to get current user token\n");
3928 return;
3930 bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
3931 ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
3932 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3933 user = HeapAlloc(GetProcessHeap(), 0, user_size);
3934 bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
3935 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
3936 CloseHandle( token );
3937 user_sid = ((TOKEN_USER *)user)->User.Sid;
3939 bret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
3940 ok(bret, "GetWindowsDirectory failed with error %d\n", GetLastError());
3942 SetLastError(0xdeadbeef);
3943 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
3944 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
3945 NULL, NULL, NULL, NULL, &pSD);
3946 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
3948 win_skip("GetNamedSecurityInfoA is not implemented\n");
3949 HeapFree(GetProcessHeap(), 0, user);
3950 return;
3952 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3954 bret = GetSecurityDescriptorControl(pSD, &control, &revision);
3955 ok(bret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
3956 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
3957 broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
3958 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
3959 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
3961 isNT4 = (control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT;
3963 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
3964 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
3965 ok(owner != NULL, "owner should not be NULL\n");
3967 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
3968 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
3969 ok(group != NULL, "group should not be NULL\n");
3970 LocalFree(pSD);
3973 /* NULL descriptor tests */
3974 if(isNT4)
3976 win_skip("NT4 does not support GetNamedSecutityInfo with a NULL descriptor\n");
3977 HeapFree(GetProcessHeap(), 0, user);
3978 return;
3981 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3982 NULL, NULL, NULL, NULL, NULL);
3983 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3985 pDacl = NULL;
3986 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
3987 NULL, NULL, &pDacl, NULL, &pSD);
3988 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
3989 ok(pDacl != NULL, "DACL should not be NULL\n");
3990 LocalFree(pSD);
3992 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,
3993 NULL, NULL, &pDacl, NULL, NULL);
3994 ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
3996 /* Test behavior of SetNamedSecurityInfo with an invalid path */
3997 SetLastError(0xdeadbeef);
3998 error = pSetNamedSecurityInfoA(invalid_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
3999 NULL, NULL, NULL);
4000 ok(error == ERROR_FILE_NOT_FOUND, "Unexpected error returned: 0x%x\n", error);
4001 ok(GetLastError() == 0xdeadbeef, "Expected last error to remain unchanged.\n");
4003 /* Create security descriptor information and test that it comes back the same */
4004 pSD = &sd;
4005 pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
4006 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
4007 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
4008 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
4009 ok(bret, "Failed to initialize ACL.\n");
4010 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4011 ok(bret, "Failed to add Current User to ACL.\n");
4012 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
4013 ok(bret, "Failed to add Administrator Group to ACL.\n");
4014 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4015 ok(bret, "Failed to add ACL to security descriptor.\n");
4016 GetTempFileNameA(".", "foo", 0, tmpfile);
4017 hTemp = CreateFileA(tmpfile, WRITE_DAC|GENERIC_WRITE, FILE_SHARE_DELETE|FILE_SHARE_READ,
4018 NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);
4019 SetLastError(0xdeadbeef);
4020 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
4021 NULL, pDacl, NULL);
4022 HeapFree(GetProcessHeap(), 0, pDacl);
4023 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
4025 win_skip("SetNamedSecurityInfoA is not implemented\n");
4026 HeapFree(GetProcessHeap(), 0, user);
4027 CloseHandle(hTemp);
4028 return;
4030 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
4031 SetLastError(0xdeadbeef);
4032 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4033 NULL, NULL, &pDacl, NULL, &pSD);
4034 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
4036 win_skip("GetNamedSecurityInfoA is not implemented\n");
4037 HeapFree(GetProcessHeap(), 0, user);
4038 CloseHandle(hTemp);
4039 return;
4041 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4043 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4044 ok(bret, "GetAclInformation failed\n");
4045 if (acl_size.AceCount > 0)
4047 bret = pGetAce(pDacl, 0, (VOID **)&ace);
4048 ok(bret, "Failed to get Current User ACE.\n");
4049 bret = EqualSid(&ace->SidStart, user_sid);
4050 todo_wine ok(bret, "Current User ACE (%s) != Current User SID (%s).\n",
4051 debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
4052 ok(((ACE_HEADER *)ace)->AceFlags == 0,
4053 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
4054 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
4055 ace->Mask);
4057 if (acl_size.AceCount > 1)
4059 bret = pGetAce(pDacl, 1, (VOID **)&ace);
4060 ok(bret, "Failed to get Administators Group ACE.\n");
4061 bret = EqualSid(&ace->SidStart, admin_sid);
4062 todo_wine ok(bret || broken(!bret) /* win2k */,
4063 "Administators Group ACE (%s) != Administators Group SID (%s).\n",
4064 debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
4065 ok(((ACE_HEADER *)ace)->AceFlags == 0,
4066 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
4067 ok(ace->Mask == 0x1f01ff || broken(ace->Mask == GENERIC_ALL) /* win2k */,
4068 "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n", ace->Mask);
4070 LocalFree(pSD);
4072 /* show that setting empty DACL is not removing all file permissions */
4073 pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
4074 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
4075 ok(bret, "Failed to initialize ACL.\n");
4076 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4077 NULL, NULL, pDacl, NULL);
4078 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
4079 HeapFree(GetProcessHeap(), 0, pDacl);
4081 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4082 NULL, NULL, &pDacl, NULL, &pSD);
4083 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4085 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4086 ok(bret, "GetAclInformation failed\n");
4087 if (acl_size.AceCount > 0)
4089 bret = pGetAce(pDacl, 0, (VOID **)&ace);
4090 ok(bret, "Failed to get ACE.\n");
4091 todo_wine ok(((ACE_HEADER *)ace)->AceFlags & INHERITED_ACE,
4092 "ACE has unexpected flags: 0x%x\n", ((ACE_HEADER *)ace)->AceFlags);
4094 LocalFree(pSD);
4096 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4097 NULL, OPEN_EXISTING, 0, NULL);
4098 ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4099 CloseHandle(h);
4101 /* test setting NULL DACL */
4102 error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
4103 DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);
4104 ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
4106 error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4107 NULL, NULL, &pDacl, NULL, &pSD);
4108 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4109 todo_wine ok(!pDacl, "pDacl != NULL\n");
4110 LocalFree(pSD);
4112 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4113 NULL, OPEN_EXISTING, 0, NULL);
4114 ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4115 CloseHandle(h);
4117 /* NtSetSecurityObject doesn't inherit DACL entries */
4118 pSD = sd+sizeof(void*)-((ULONG_PTR)sd)%sizeof(void*);
4119 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
4120 pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
4121 bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
4122 ok(bret, "Failed to initialize ACL.\n");
4123 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4124 ok(bret, "Failed to add ACL to security descriptor.\n");
4125 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4126 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4128 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4129 NULL, OPEN_EXISTING, 0, NULL);
4130 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4131 CloseHandle(h);
4133 pSetSecurityDescriptorControl(pSD, SE_DACL_AUTO_INHERIT_REQ, SE_DACL_AUTO_INHERIT_REQ);
4134 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4135 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4137 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4138 NULL, OPEN_EXISTING, 0, NULL);
4139 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4140 CloseHandle(h);
4142 pSetSecurityDescriptorControl(pSD, SE_DACL_AUTO_INHERIT_REQ|SE_DACL_AUTO_INHERITED,
4143 SE_DACL_AUTO_INHERIT_REQ|SE_DACL_AUTO_INHERITED);
4144 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4145 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4147 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4148 NULL, OPEN_EXISTING, 0, NULL);
4149 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4150 CloseHandle(h);
4152 /* test if DACL is properly mapped to permission */
4153 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
4154 ok(bret, "Failed to initialize ACL.\n");
4155 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4156 ok(bret, "Failed to add Current User to ACL.\n");
4157 bret = pAddAccessDeniedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4158 ok(bret, "Failed to add Current User to ACL.\n");
4159 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4160 ok(bret, "Failed to add ACL to security descriptor.\n");
4161 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4162 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4164 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4165 NULL, OPEN_EXISTING, 0, NULL);
4166 ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4167 CloseHandle(h);
4169 bret = InitializeAcl(pDacl, 100, ACL_REVISION);
4170 ok(bret, "Failed to initialize ACL.\n");
4171 bret = pAddAccessDeniedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4172 ok(bret, "Failed to add Current User to ACL.\n");
4173 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4174 ok(bret, "Failed to add Current User to ACL.\n");
4175 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4176 ok(bret, "Failed to add ACL to security descriptor.\n");
4177 status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
4178 ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
4180 h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
4181 NULL, OPEN_EXISTING, 0, NULL);
4182 ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
4183 HeapFree(GetProcessHeap(), 0, pDacl);
4184 HeapFree(GetProcessHeap(), 0, user);
4185 CloseHandle(hTemp);
4187 /* Test querying the ownership of a built-in registry key */
4188 sid_size = sizeof(system_ptr);
4189 pCreateWellKnownSid(WinLocalSystemSid, NULL, system_sid, &sid_size);
4190 error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY,
4191 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
4192 NULL, NULL, NULL, NULL, &pSD);
4193 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4195 bret = AllocateAndInitializeSid(&SIDAuthNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &localsys_sid);
4196 ok(bret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
4198 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
4199 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
4200 ok(owner != NULL, "owner should not be NULL\n");
4201 ok(EqualSid(owner, admin_sid) || EqualSid(owner, localsys_sid),
4202 "MACHINE\\Software owner SID (%s) != Administrators SID (%s) or Local System Sid (%s).\n",
4203 debugstr_sid(owner), debugstr_sid(admin_sid), debugstr_sid(localsys_sid));
4205 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
4206 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
4207 ok(group != NULL, "group should not be NULL\n");
4208 ok(EqualSid(group, admin_sid) || broken(EqualSid(group, system_sid)) /* before Win7 */
4209 || broken(((SID*)group)->SubAuthority[0] == SECURITY_NT_NON_UNIQUE) /* Vista */,
4210 "MACHINE\\Software group SID (%s) != Local System SID (%s or %s)\n",
4211 debugstr_sid(group), debugstr_sid(admin_sid), debugstr_sid(system_sid));
4212 LocalFree(pSD);
4214 /* Test querying the DACL of a built-in registry key */
4215 sid_size = sizeof(users_ptr);
4216 pCreateWellKnownSid(WinBuiltinUsersSid, NULL, users_sid, &sid_size);
4217 error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
4218 NULL, NULL, NULL, NULL, &pSD);
4219 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
4221 bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
4222 ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
4223 ok(dacl_present, "DACL should be present\n");
4224 ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
4225 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4226 ok(bret, "GetAclInformation failed\n");
4227 ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
4228 for (i=0; i<acl_size.AceCount; i++)
4230 bret = pGetAce(pDacl, i, (VOID **)&ace);
4231 ok(bret, "Failed to get ACE %d.\n", i);
4232 bret = EqualSid(&ace->SidStart, users_sid);
4233 if (bret) users_ace_id = i;
4234 bret = EqualSid(&ace->SidStart, admin_sid);
4235 if (bret) admins_ace_id = i;
4237 ok(users_ace_id != -1 || broken(users_ace_id == -1) /* win2k */,
4238 "Builtin Users ACE not found.\n");
4239 if (users_ace_id != -1)
4241 bret = pGetAce(pDacl, users_ace_id, (VOID **)&ace);
4242 ok(bret, "Failed to get Builtin Users ACE.\n");
4243 flags = ((ACE_HEADER *)ace)->AceFlags;
4244 ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)
4245 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */
4246 || broken(flags == (CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* win 10 wow64 */
4247 || broken(flags == CONTAINER_INHERIT_ACE), /* win 10 */
4248 "Builtin Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
4249 INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
4250 ok(ace->Mask == GENERIC_READ
4251 || broken(ace->Mask == KEY_READ), /* win 10 */
4252 "Builtin Users ACE has unexpected mask (0x%x != 0x%x)\n",
4253 ace->Mask, GENERIC_READ);
4255 ok(admins_ace_id != -1, "Builtin Admins ACE not found.\n");
4256 if (admins_ace_id != -1)
4258 bret = pGetAce(pDacl, admins_ace_id, (VOID **)&ace);
4259 ok(bret, "Failed to get Builtin Admins ACE.\n");
4260 flags = ((ACE_HEADER *)ace)->AceFlags;
4261 ok(flags == 0x0
4262 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */
4263 || broken(flags == (OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE)) /* win7 */
4264 || broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)) /* win8+ */
4265 || broken(flags == (CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* win 10 wow64 */
4266 || broken(flags == CONTAINER_INHERIT_ACE), /* win 10 */
4267 "Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
4268 ok(ace->Mask == KEY_ALL_ACCESS || broken(ace->Mask == GENERIC_ALL) /* w2k8 */,
4269 "Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, KEY_ALL_ACCESS);
4272 FreeSid(localsys_sid);
4273 LocalFree(pSD);
4276 static void test_ConvertStringSecurityDescriptor(void)
4278 BOOL ret;
4279 PSECURITY_DESCRIPTOR pSD;
4280 static const WCHAR Blank[] = { 0 };
4281 unsigned int i;
4282 ULONG size;
4283 ACL *acl;
4284 static const struct
4286 const char *sidstring;
4287 DWORD revision;
4288 BOOL ret;
4289 DWORD GLE;
4290 DWORD altGLE;
4291 } cssd[] =
4293 { "D:(A;;GA;;;WD)", 0xdeadbeef, FALSE, ERROR_UNKNOWN_REVISION },
4294 /* test ACE string type */
4295 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4296 { "D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4297 { "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
4298 /* test ACE string with spaces */
4299 { " D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4300 { "D: (D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4301 { "D:( D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4302 { "D:(D ;;GA;;;WD)", SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
4303 { "D:(D; ;GA;;;WD)", SDDL_REVISION_1, TRUE },
4304 { "D:(D;; GA;;;WD)", SDDL_REVISION_1, TRUE },
4305 { "D:(D;;GA ;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
4306 { "D:(D;;GA; ;;WD)", SDDL_REVISION_1, TRUE },
4307 { "D:(D;;GA;; ;WD)", SDDL_REVISION_1, TRUE },
4308 { "D:(D;;GA;;; WD)", SDDL_REVISION_1, TRUE },
4309 { "D:(D;;GA;;;WD )", SDDL_REVISION_1, TRUE },
4310 /* test ACE string access rights */
4311 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
4312 { "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, TRUE },
4313 { "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, TRUE },
4314 { "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, TRUE },
4315 { "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, TRUE },
4316 { "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, TRUE },
4317 { "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
4318 { "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
4319 /* test ACE string access right error case */
4320 { "D:(A;;ROB;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
4321 /* test behaviour with empty strings */
4322 { "", SDDL_REVISION_1, TRUE },
4323 /* test ACE string SID */
4324 { "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, TRUE },
4325 { "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
4328 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
4330 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
4331 return;
4334 for (i = 0; i < ARRAY_SIZE(cssd); i++)
4336 DWORD GLE;
4338 SetLastError(0xdeadbeef);
4339 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
4340 cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
4341 GLE = GetLastError();
4342 ok(ret == cssd[i].ret, "(%02u) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
4343 if (!cssd[i].ret)
4344 ok(GLE == cssd[i].GLE ||
4345 (cssd[i].altGLE && GLE == cssd[i].altGLE),
4346 "(%02u) Unexpected last error %d\n", i, GLE);
4347 if (ret)
4348 LocalFree(pSD);
4351 /* test behaviour with NULL parameters */
4352 SetLastError(0xdeadbeef);
4353 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
4354 NULL, 0xdeadbeef, &pSD, NULL);
4355 todo_wine
4356 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4357 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4358 GetLastError());
4360 SetLastError(0xdeadbeef);
4361 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
4362 NULL, 0xdeadbeef, &pSD, NULL);
4363 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4364 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4365 GetLastError());
4367 SetLastError(0xdeadbeef);
4368 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
4369 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
4370 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4371 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4372 GetLastError());
4374 SetLastError(0xdeadbeef);
4375 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
4376 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
4377 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
4378 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
4379 GetLastError());
4381 /* test behaviour with empty strings */
4382 SetLastError(0xdeadbeef);
4383 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
4384 Blank, SDDL_REVISION_1, &pSD, NULL);
4385 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
4386 LocalFree(pSD);
4388 SetLastError(0xdeadbeef);
4389 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
4390 "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);
4391 ok(ret || broken(!ret && GetLastError() == ERROR_INVALID_DATATYPE) /* win2k */,
4392 "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %u\n", GetLastError());
4393 if (ret) LocalFree(pSD);
4395 /* empty DACL */
4396 size = 0;
4397 SetLastError(0xdeadbeef);
4398 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA("D:", SDDL_REVISION_1, &pSD, &size);
4399 ok(ret, "unexpected error %u\n", GetLastError());
4400 ok(size == sizeof(SECURITY_DESCRIPTOR_RELATIVE) + sizeof(ACL), "got %u\n", size);
4401 acl = (ACL *)((char *)pSD + sizeof(SECURITY_DESCRIPTOR_RELATIVE));
4402 ok(acl->AclRevision == ACL_REVISION, "got %u\n", acl->AclRevision);
4403 ok(!acl->Sbz1, "got %u\n", acl->Sbz1);
4404 ok(acl->AclSize == sizeof(*acl), "got %u\n", acl->AclSize);
4405 ok(!acl->AceCount, "got %u\n", acl->AceCount);
4406 ok(!acl->Sbz2, "got %u\n", acl->Sbz2);
4407 LocalFree(pSD);
4409 /* empty SACL */
4410 size = 0;
4411 SetLastError(0xdeadbeef);
4412 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA("S:", SDDL_REVISION_1, &pSD, &size);
4413 ok(ret, "unexpected error %u\n", GetLastError());
4414 ok(size == sizeof(SECURITY_DESCRIPTOR_RELATIVE) + sizeof(ACL), "got %u\n", size);
4415 acl = (ACL *)((char *)pSD + sizeof(SECURITY_DESCRIPTOR_RELATIVE));
4416 ok(!acl->Sbz1, "got %u\n", acl->Sbz1);
4417 ok(acl->AclSize == sizeof(*acl), "got %u\n", acl->AclSize);
4418 ok(!acl->AceCount, "got %u\n", acl->AceCount);
4419 ok(!acl->Sbz2, "got %u\n", acl->Sbz2);
4420 LocalFree(pSD);
4423 static void test_ConvertSecurityDescriptorToString(void)
4425 SECURITY_DESCRIPTOR desc;
4426 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
4427 LPSTR string;
4428 DWORD size;
4429 PSID psid, psid2;
4430 PACL pacl;
4431 char sid_buf[256];
4432 char acl_buf[8192];
4433 ULONG len;
4435 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
4437 win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
4438 return;
4440 if (!pCreateWellKnownSid)
4442 win_skip("CreateWellKnownSid is not available\n");
4443 return;
4446 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
4447 * don't replicate this feature so we only test len >= strlen+1. */
4448 #define CHECK_RESULT_AND_FREE(exp_str) \
4449 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
4450 ok(len >= (strlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlenA(exp_str) + 1, len); \
4451 LocalFree(string);
4453 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
4454 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); \
4455 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); \
4456 LocalFree(string);
4458 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
4459 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4460 CHECK_RESULT_AND_FREE("");
4462 size = 4096;
4463 pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
4464 SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
4465 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4466 CHECK_RESULT_AND_FREE("O:S-1-2-0");
4468 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
4469 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4470 CHECK_RESULT_AND_FREE("O:S-1-2-0");
4472 size = sizeof(sid_buf);
4473 pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
4474 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
4475 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4476 CHECK_RESULT_AND_FREE("O:SY");
4478 pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
4479 SetSecurityDescriptorGroup(&desc, psid, TRUE);
4480 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4481 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
4483 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
4484 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
4486 pacl = (PACL)acl_buf;
4487 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
4488 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
4489 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4490 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
4492 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
4493 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4494 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
4496 pConvertStringSidToSidA("S-1-5-6", &psid2);
4497 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
4498 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4499 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
4501 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
4502 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4503 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
4505 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
4506 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4507 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)");
4510 pacl = (PACL)acl_buf;
4511 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
4512 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
4513 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4514 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
4516 /* fails in win2k */
4517 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
4518 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
4519 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
4521 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
4522 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
4525 /* fails in win2k */
4526 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
4527 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
4529 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
4530 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
4533 LocalFree(psid2);
4534 LocalFree(psid);
4537 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
4539 SECURITY_DESCRIPTOR_CONTROL ref;
4540 SECURITY_DESCRIPTOR_CONTROL test;
4542 SECURITY_DESCRIPTOR_CONTROL const mutable
4543 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
4544 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
4545 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
4546 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
4548 SECURITY_DESCRIPTOR_CONTROL const immutable
4549 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
4550 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
4551 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
4552 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
4555 int bit;
4556 DWORD dwRevision;
4557 LPCSTR fmt = "Expected error %s, got %u\n";
4559 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
4561 /* The mutable bits are mutable regardless of the truth of
4562 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
4564 /* Check call barfs if any bit-of-interest is immutable */
4565 for (bit = 0; bit < 16; ++bit)
4567 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
4568 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
4570 SECURITY_DESCRIPTOR_CONTROL ctrl;
4572 DWORD dwExpect = (bitOfInterest & immutable)
4573 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
4574 LPCSTR strExpect = (bitOfInterest & immutable)
4575 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
4577 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
4578 setOrClear ^= bitOfInterest;
4579 SetLastError (0xbebecaca);
4580 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
4581 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4582 GetSecurityDescriptorControl(sec, &test, &dwRevision);
4583 expect_eq(test, ctrl, int, "%x");
4585 setOrClear ^= bitOfInterest;
4586 SetLastError (0xbebecaca);
4587 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
4588 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4589 GetSecurityDescriptorControl (sec, &test, &dwRevision);
4590 expect_eq(test, ref, int, "%x");
4593 /* Check call barfs if any bit-to-set is immutable
4594 even when not a bit-of-interest */
4595 for (bit = 0; bit < 16; ++bit)
4597 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
4598 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
4600 SECURITY_DESCRIPTOR_CONTROL ctrl;
4602 DWORD dwExpect = ((1 << bit) & immutable)
4603 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
4604 LPCSTR strExpect = ((1 << bit) & immutable)
4605 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
4607 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
4608 setOrClear ^= bitsOfInterest;
4609 SetLastError (0xbebecaca);
4610 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
4611 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4612 GetSecurityDescriptorControl(sec, &test, &dwRevision);
4613 expect_eq(test, ctrl, int, "%x");
4615 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
4616 setOrClear ^= bitsOfInterest;
4617 SetLastError (0xbebecaca);
4618 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
4619 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
4620 GetSecurityDescriptorControl(sec, &test, &dwRevision);
4621 expect_eq(test, ctrl, int, "%x");
4625 static void test_PrivateObjectSecurity(void)
4627 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
4628 SECURITY_DESCRIPTOR_CONTROL ctrl;
4629 PSECURITY_DESCRIPTOR sec;
4630 DWORD dwDescSize;
4631 DWORD dwRevision;
4632 DWORD retSize;
4633 LPSTR string;
4634 ULONG len;
4635 PSECURITY_DESCRIPTOR buf;
4636 BOOL ret;
4638 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
4640 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
4641 return;
4644 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
4645 "O:SY"
4646 "G:S-1-5-21-93476-23408-4576"
4647 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
4648 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4649 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
4650 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
4652 test_SetSecurityDescriptorControl(sec);
4654 LocalFree(sec);
4656 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
4657 "O:SY"
4658 "G:S-1-5-21-93476-23408-4576",
4659 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
4661 test_SetSecurityDescriptorControl(sec);
4663 LocalFree(sec);
4665 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
4666 "O:SY"
4667 "G:S-1-5-21-93476-23408-4576"
4668 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4669 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
4670 buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
4671 pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
4672 GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
4673 expect_eq(ctrl, 0x9014, int, "%x");
4675 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
4676 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
4677 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
4678 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4679 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
4680 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
4681 expect_eq(ctrl, 0x8000, int, "%x");
4683 ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
4684 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
4685 ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
4686 ret = pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len);
4687 ok(ret, "Conversion failed err=%u\n", GetLastError());
4688 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)",
4689 "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 */
4690 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
4691 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8004, int, "%x");
4693 ret = GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize);
4694 ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
4695 ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
4696 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
4697 CHECK_ONE_OF_AND_FREE("O:SY"
4698 "G:S-1-5-21-93476-23408-4576"
4699 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4700 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
4701 "O:SY"
4702 "G:S-1-5-21-93476-23408-4576"
4703 "D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
4704 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)"); /* Win7 */
4705 GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
4706 expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8014, int, "%x");
4708 SetLastError(0xdeadbeef);
4709 ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
4710 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
4712 LocalFree(sec);
4713 HeapFree(GetProcessHeap(), 0, buf);
4715 #undef CHECK_RESULT_AND_FREE
4716 #undef CHECK_ONE_OF_AND_FREE
4718 static void test_acls(void)
4720 char buffer[256];
4721 PACL pAcl = (PACL)buffer;
4722 BOOL ret;
4724 SetLastError(0xdeadbeef);
4725 ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
4726 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4728 win_skip("InitializeAcl is not implemented\n");
4729 return;
4732 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
4734 SetLastError(0xdeadbeef);
4735 ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
4736 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
4738 SetLastError(0xdeadbeef);
4739 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
4740 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
4742 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
4743 ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
4745 ret = IsValidAcl(pAcl);
4746 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
4748 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
4749 ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
4751 ret = IsValidAcl(pAcl);
4752 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
4754 SetLastError(0xdeadbeef);
4755 ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
4756 if (GetLastError() != ERROR_INVALID_PARAMETER)
4758 ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
4760 ret = IsValidAcl(pAcl);
4761 ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
4763 else
4764 win_skip("ACL_REVISION4 is not implemented on NT4\n");
4766 SetLastError(0xdeadbeef);
4767 ret = InitializeAcl(pAcl, sizeof(buffer), -1);
4768 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
4771 static void test_GetSecurityInfo(void)
4773 char domain_users_ptr[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
4774 char b[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
4775 char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], dacl[100];
4776 PSID domain_users_sid = (PSID) domain_users_ptr, domain_sid;
4777 SID_IDENTIFIER_AUTHORITY sia = { SECURITY_NT_AUTHORITY };
4778 int domain_users_ace_id = -1, admins_ace_id = -1, i;
4779 DWORD sid_size = sizeof(admin_ptr), l = sizeof(b);
4780 PSID admin_sid = (PSID) admin_ptr, user_sid;
4781 char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
4782 BOOL owner_defaulted, group_defaulted;
4783 BOOL dacl_defaulted, dacl_present;
4784 ACL_SIZE_INFORMATION acl_size;
4785 PSECURITY_DESCRIPTOR pSD;
4786 ACCESS_ALLOWED_ACE *ace;
4787 HANDLE token, obj;
4788 PSID owner, group;
4789 BOOL bret = TRUE;
4790 PACL pDacl;
4791 BYTE flags;
4792 DWORD ret;
4794 if (!pGetSecurityInfo || !pSetSecurityInfo)
4796 win_skip("[Get|Set]SecurityInfo is not available\n");
4797 return;
4800 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
4802 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
4803 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
4805 if (!bret)
4807 win_skip("Failed to get current user token\n");
4808 return;
4810 bret = GetTokenInformation(token, TokenUser, b, l, &l);
4811 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
4812 CloseHandle( token );
4813 user_sid = ((TOKEN_USER *)b)->User.Sid;
4815 /* Create something. Files have lots of associated security info. */
4816 obj = CreateFileA(myARGV[0], GENERIC_READ|WRITE_DAC, FILE_SHARE_READ, NULL,
4817 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
4818 if (obj == INVALID_HANDLE_VALUE)
4820 skip("Couldn't create an object for GetSecurityInfo test\n");
4821 return;
4824 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
4825 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4826 &owner, &group, &pDacl, NULL, &pSD);
4827 if (ret == ERROR_CALL_NOT_IMPLEMENTED)
4829 win_skip("GetSecurityInfo is not implemented\n");
4830 CloseHandle(obj);
4831 return;
4833 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
4834 ok(pSD != NULL, "GetSecurityInfo\n");
4835 ok(owner != NULL, "GetSecurityInfo\n");
4836 ok(group != NULL, "GetSecurityInfo\n");
4837 if (pDacl != NULL)
4838 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
4839 else
4840 win_skip("No ACL information returned\n");
4842 LocalFree(pSD);
4844 if (!pCreateWellKnownSid)
4846 win_skip("NULL parameter test would crash on NT4\n");
4847 CloseHandle(obj);
4848 return;
4851 /* If we don't ask for the security descriptor, Windows will still give us
4852 the other stuff, leaving us no way to free it. */
4853 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
4854 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
4855 &owner, &group, &pDacl, NULL, NULL);
4856 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
4857 ok(owner != NULL, "GetSecurityInfo\n");
4858 ok(group != NULL, "GetSecurityInfo\n");
4859 if (pDacl != NULL)
4860 ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
4861 else
4862 win_skip("No ACL information returned\n");
4864 /* Create security descriptor information and test that it comes back the same */
4865 pSD = &sd;
4866 pDacl = (PACL)&dacl;
4867 InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
4868 pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
4869 bret = InitializeAcl(pDacl, sizeof(dacl), ACL_REVISION);
4870 ok(bret, "Failed to initialize ACL.\n");
4871 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
4872 ok(bret, "Failed to add Current User to ACL.\n");
4873 bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
4874 ok(bret, "Failed to add Administrator Group to ACL.\n");
4875 bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
4876 ok(bret, "Failed to add ACL to security descriptor.\n");
4877 ret = pSetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4878 NULL, NULL, pDacl, NULL);
4879 ok(ret == ERROR_SUCCESS, "SetSecurityInfo returned %d\n", ret);
4880 ret = pGetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
4881 NULL, NULL, &pDacl, NULL, &pSD);
4882 ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
4883 ok(pDacl && IsValidAcl(pDacl), "GetSecurityInfo returned invalid DACL.\n");
4884 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4885 ok(bret, "GetAclInformation failed\n");
4886 if (acl_size.AceCount > 0)
4888 bret = pGetAce(pDacl, 0, (VOID **)&ace);
4889 ok(bret, "Failed to get Current User ACE.\n");
4890 bret = EqualSid(&ace->SidStart, user_sid);
4891 todo_wine ok(bret, "Current User ACE (%s) != Current User SID (%s).\n",
4892 debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
4893 ok(((ACE_HEADER *)ace)->AceFlags == 0,
4894 "Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
4895 ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
4896 ace->Mask);
4898 if (acl_size.AceCount > 1)
4900 bret = pGetAce(pDacl, 1, (VOID **)&ace);
4901 ok(bret, "Failed to get Administators Group ACE.\n");
4902 bret = EqualSid(&ace->SidStart, admin_sid);
4903 todo_wine ok(bret, "Administators Group ACE (%s) != Administators Group SID (%s).\n", debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
4904 ok(((ACE_HEADER *)ace)->AceFlags == 0,
4905 "Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
4906 ok(ace->Mask == 0x1f01ff, "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n",
4907 ace->Mask);
4909 LocalFree(pSD);
4910 CloseHandle(obj);
4912 /* Obtain the "domain users" SID from the user SID */
4913 if (!AllocateAndInitializeSid(&sia, 4, *GetSidSubAuthority(user_sid, 0),
4914 *GetSidSubAuthority(user_sid, 1),
4915 *GetSidSubAuthority(user_sid, 2),
4916 *GetSidSubAuthority(user_sid, 3), 0, 0, 0, 0, &domain_sid))
4918 win_skip("Failed to get current domain SID\n");
4919 return;
4921 sid_size = sizeof(domain_users_ptr);
4922 pCreateWellKnownSid(WinAccountDomainUsersSid, domain_sid, domain_users_sid, &sid_size);
4923 FreeSid(domain_sid);
4925 /* Test querying the ownership of a process */
4926 ret = pGetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT,
4927 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
4928 NULL, NULL, NULL, NULL, &pSD);
4929 ok(!ret, "GetNamedSecurityInfo failed with error %d\n", ret);
4931 bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
4932 ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
4933 ok(owner != NULL, "owner should not be NULL\n");
4934 ok(EqualSid(owner, admin_sid) || EqualSid(owner, user_sid),
4935 "Process owner SID != Administrators SID.\n");
4937 bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
4938 ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
4939 ok(group != NULL, "group should not be NULL\n");
4940 ok(EqualSid(group, domain_users_sid), "Process group SID != Domain Users SID.\n");
4941 LocalFree(pSD);
4943 /* Test querying the DACL of a process */
4944 ret = pGetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
4945 NULL, NULL, NULL, NULL, &pSD);
4946 ok(!ret, "GetSecurityInfo failed with error %d\n", ret);
4948 bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
4949 ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
4950 ok(dacl_present, "DACL should be present\n");
4951 ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
4952 bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
4953 ok(bret, "GetAclInformation failed\n");
4954 ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
4955 for (i=0; i<acl_size.AceCount; i++)
4957 bret = pGetAce(pDacl, i, (VOID **)&ace);
4958 ok(bret, "Failed to get ACE %d.\n", i);
4959 bret = EqualSid(&ace->SidStart, domain_users_sid);
4960 if (bret) domain_users_ace_id = i;
4961 bret = EqualSid(&ace->SidStart, admin_sid);
4962 if (bret) admins_ace_id = i;
4964 ok(domain_users_ace_id != -1 || broken(domain_users_ace_id == -1) /* win2k */,
4965 "Domain Users ACE not found.\n");
4966 if (domain_users_ace_id != -1)
4968 bret = pGetAce(pDacl, domain_users_ace_id, (VOID **)&ace);
4969 ok(bret, "Failed to get Domain Users ACE.\n");
4970 flags = ((ACE_HEADER *)ace)->AceFlags;
4971 ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE),
4972 "Domain Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
4973 INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
4974 ok(ace->Mask == GENERIC_READ, "Domain Users ACE has unexpected mask (0x%x != 0x%x)\n",
4975 ace->Mask, GENERIC_READ);
4977 ok(admins_ace_id != -1 || broken(admins_ace_id == -1) /* xp */,
4978 "Builtin Admins ACE not found.\n");
4979 if (admins_ace_id != -1)
4981 bret = pGetAce(pDacl, admins_ace_id, (VOID **)&ace);
4982 ok(bret, "Failed to get Builtin Admins ACE.\n");
4983 flags = ((ACE_HEADER *)ace)->AceFlags;
4984 ok(flags == 0x0, "Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
4985 ok(ace->Mask == PROCESS_ALL_ACCESS || broken(ace->Mask == 0x1f0fff) /* win2k */,
4986 "Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, PROCESS_ALL_ACCESS);
4988 LocalFree(pSD);
4991 static void test_GetSidSubAuthority(void)
4993 PSID psid = NULL;
4995 if (!pGetSidSubAuthority || !pConvertStringSidToSidA || !pIsValidSid || !pGetSidSubAuthorityCount)
4997 win_skip("Some functions not available\n");
4998 return;
5000 /* Note: on windows passing in an invalid index like -1, lets GetSidSubAuthority return 0x05000000 but
5001 still GetLastError returns ERROR_SUCCESS then. We don't test these unlikely cornercases here for now */
5002 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576",&psid),"ConvertStringSidToSidA failed\n");
5003 ok(pIsValidSid(psid),"Sid is not valid\n");
5004 SetLastError(0xbebecaca);
5005 ok(*pGetSidSubAuthorityCount(psid) == 4,"GetSidSubAuthorityCount gave %d expected 4\n",*pGetSidSubAuthorityCount(psid));
5006 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
5007 SetLastError(0xbebecaca);
5008 ok(*pGetSidSubAuthority(psid,0) == 21,"GetSidSubAuthority gave %d expected 21\n",*pGetSidSubAuthority(psid,0));
5009 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
5010 SetLastError(0xbebecaca);
5011 ok(*pGetSidSubAuthority(psid,1) == 93476,"GetSidSubAuthority gave %d expected 93476\n",*pGetSidSubAuthority(psid,1));
5012 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
5013 SetLastError(0xbebecaca);
5014 ok(pGetSidSubAuthority(psid,4) != NULL,"Expected out of bounds GetSidSubAuthority to return a non-NULL pointer\n");
5015 ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
5016 LocalFree(psid);
5019 static void test_CheckTokenMembership(void)
5021 PTOKEN_GROUPS token_groups;
5022 DWORD size;
5023 HANDLE process_token, token;
5024 BOOL is_member;
5025 BOOL ret;
5026 DWORD i;
5028 if (!pCheckTokenMembership)
5030 win_skip("CheckTokenMembership is not available\n");
5031 return;
5033 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
5034 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
5036 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
5037 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
5039 /* groups */
5040 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
5041 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
5042 "GetTokenInformation(TokenGroups) %s with error %d\n",
5043 ret ? "succeeded" : "failed", GetLastError());
5044 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
5045 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
5046 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
5048 for (i = 0; i < token_groups->GroupCount; i++)
5050 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
5051 break;
5054 if (i == token_groups->GroupCount)
5056 HeapFree(GetProcessHeap(), 0, token_groups);
5057 CloseHandle(token);
5058 skip("user not a member of any group\n");
5059 return;
5062 is_member = FALSE;
5063 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
5064 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
5065 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
5067 is_member = FALSE;
5068 ret = pCheckTokenMembership(NULL, token_groups->Groups[i].Sid, &is_member);
5069 ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
5070 ok(is_member, "CheckTokenMembership should have detected sid as member\n");
5072 is_member = TRUE;
5073 SetLastError(0xdeadbeef);
5074 ret = pCheckTokenMembership(process_token, token_groups->Groups[i].Sid, &is_member);
5075 ok(!ret && GetLastError() == ERROR_NO_IMPERSONATION_TOKEN,
5076 "CheckTokenMembership with process token %s with error %d\n",
5077 ret ? "succeeded" : "failed", GetLastError());
5078 ok(!is_member, "CheckTokenMembership should have cleared is_member\n");
5080 HeapFree(GetProcessHeap(), 0, token_groups);
5081 CloseHandle(token);
5082 CloseHandle(process_token);
5085 static void test_EqualSid(void)
5087 PSID sid1, sid2;
5088 BOOL ret;
5089 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
5090 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
5092 SetLastError(0xdeadbeef);
5093 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
5094 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid1);
5095 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5097 win_skip("AllocateAndInitializeSid is not implemented\n");
5098 return;
5100 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
5101 ok(GetLastError() == 0xdeadbeef,
5102 "AllocateAndInitializeSid shouldn't have set last error to %d\n",
5103 GetLastError());
5105 ret = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
5106 0, 0, 0, 0, 0, 0, 0, &sid2);
5107 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
5109 SetLastError(0xdeadbeef);
5110 ret = EqualSid(sid1, sid2);
5111 ok(!ret, "World and domain admins sids shouldn't have been equal\n");
5112 ok(GetLastError() == ERROR_SUCCESS ||
5113 broken(GetLastError() == 0xdeadbeef), /* NT4 */
5114 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
5115 GetLastError());
5117 SetLastError(0xdeadbeef);
5118 sid2 = FreeSid(sid2);
5119 ok(!sid2, "FreeSid should have returned NULL instead of %p\n", sid2);
5120 ok(GetLastError() == 0xdeadbeef,
5121 "FreeSid shouldn't have set last error to %d\n",
5122 GetLastError());
5124 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
5125 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid2);
5126 ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
5128 SetLastError(0xdeadbeef);
5129 ret = EqualSid(sid1, sid2);
5130 ok(ret, "Same sids should have been equal %s != %s\n",
5131 debugstr_sid(sid1), debugstr_sid(sid2));
5132 ok(GetLastError() == ERROR_SUCCESS ||
5133 broken(GetLastError() == 0xdeadbeef), /* NT4 */
5134 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
5135 GetLastError());
5137 ((SID *)sid2)->Revision = 2;
5138 SetLastError(0xdeadbeef);
5139 ret = EqualSid(sid1, sid2);
5140 ok(!ret, "EqualSid with invalid sid should have returned FALSE\n");
5141 ok(GetLastError() == ERROR_SUCCESS ||
5142 broken(GetLastError() == 0xdeadbeef), /* NT4 */
5143 "EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
5144 GetLastError());
5145 ((SID *)sid2)->Revision = SID_REVISION;
5147 FreeSid(sid1);
5148 FreeSid(sid2);
5151 static void test_GetUserNameA(void)
5153 char buffer[UNLEN + 1], filler[UNLEN + 1];
5154 DWORD required_len, buffer_len;
5155 BOOL ret;
5157 /* Test crashes on Windows. */
5158 if (0)
5160 SetLastError(0xdeadbeef);
5161 GetUserNameA(NULL, NULL);
5164 SetLastError(0xdeadbeef);
5165 required_len = 0;
5166 ret = GetUserNameA(NULL, &required_len);
5167 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5168 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5169 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5171 SetLastError(0xdeadbeef);
5172 required_len = 1;
5173 ret = GetUserNameA(NULL, &required_len);
5174 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5175 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
5176 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5178 /* Tests crashes on Windows. */
5179 if (0)
5181 SetLastError(0xdeadbeef);
5182 required_len = UNLEN + 1;
5183 GetUserNameA(NULL, &required_len);
5185 SetLastError(0xdeadbeef);
5186 GetUserNameA(buffer, NULL);
5189 memset(filler, 'x', sizeof(filler));
5191 /* Note that GetUserNameA on XP and newer outputs the number of bytes
5192 * required for a Unicode string, which affects a test in the next block. */
5193 SetLastError(0xdeadbeef);
5194 memcpy(buffer, filler, sizeof(filler));
5195 required_len = 0;
5196 ret = GetUserNameA(buffer, &required_len);
5197 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5198 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
5199 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5200 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5202 SetLastError(0xdeadbeef);
5203 memcpy(buffer, filler, sizeof(filler));
5204 buffer_len = required_len;
5205 ret = GetUserNameA(buffer, &buffer_len);
5206 ok(ret == TRUE, "GetUserNameA returned %d, last error %u\n", ret, GetLastError());
5207 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
5208 ok(buffer_len == required_len ||
5209 broken(buffer_len == required_len / sizeof(WCHAR)), /* XP+ */
5210 "Outputted buffer length was %u\n", buffer_len);
5212 /* Use the reported buffer size from the last GetUserNameA call and pass
5213 * a length that is one less than the required value. */
5214 SetLastError(0xdeadbeef);
5215 memcpy(buffer, filler, sizeof(filler));
5216 buffer_len--;
5217 ret = GetUserNameA(buffer, &buffer_len);
5218 ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
5219 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was untouched\n");
5220 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
5221 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5224 static void test_GetUserNameW(void)
5226 WCHAR buffer[UNLEN + 1], filler[UNLEN + 1];
5227 DWORD required_len, buffer_len;
5228 BOOL ret;
5230 /* Test crashes on Windows. */
5231 if (0)
5233 SetLastError(0xdeadbeef);
5234 GetUserNameW(NULL, NULL);
5237 SetLastError(0xdeadbeef);
5238 required_len = 0;
5239 ret = GetUserNameW(NULL, &required_len);
5240 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5241 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5242 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5244 SetLastError(0xdeadbeef);
5245 required_len = 1;
5246 ret = GetUserNameW(NULL, &required_len);
5247 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5248 ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
5249 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5251 /* Tests crash on Windows. */
5252 if (0)
5254 SetLastError(0xdeadbeef);
5255 required_len = UNLEN + 1;
5256 GetUserNameW(NULL, &required_len);
5258 SetLastError(0xdeadbeef);
5259 GetUserNameW(buffer, NULL);
5262 memset(filler, 'x', sizeof(filler));
5264 SetLastError(0xdeadbeef);
5265 memcpy(buffer, filler, sizeof(filler));
5266 required_len = 0;
5267 ret = GetUserNameW(buffer, &required_len);
5268 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5269 ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
5270 ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
5271 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5273 SetLastError(0xdeadbeef);
5274 memcpy(buffer, filler, sizeof(filler));
5275 buffer_len = required_len;
5276 ret = GetUserNameW(buffer, &buffer_len);
5277 ok(ret == TRUE, "GetUserNameW returned %d, last error %u\n", ret, GetLastError());
5278 ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
5279 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
5281 /* GetUserNameW on XP and newer writes a truncated portion of the username string to the buffer. */
5282 SetLastError(0xdeadbeef);
5283 memcpy(buffer, filler, sizeof(filler));
5284 buffer_len--;
5285 ret = GetUserNameW(buffer, &buffer_len);
5286 ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
5287 ok(!memcmp(buffer, filler, sizeof(filler)) ||
5288 broken(memcmp(buffer, filler, sizeof(filler)) != 0), /* XP+ */
5289 "Output buffer was altered\n");
5290 ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
5291 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
5294 static void test_CreateRestrictedToken(void)
5296 HANDLE process_token, token, r_token;
5297 PTOKEN_GROUPS token_groups, groups2;
5298 SID_AND_ATTRIBUTES sattr;
5299 SECURITY_IMPERSONATION_LEVEL level;
5300 TOKEN_TYPE type;
5301 BOOL is_member;
5302 DWORD size;
5303 BOOL ret;
5304 DWORD i, j;
5306 if (!pCreateRestrictedToken)
5308 win_skip("CreateRestrictedToken is not available\n");
5309 return;
5312 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
5313 ok(ret, "got error %d\n", GetLastError());
5315 ret = DuplicateTokenEx(process_token, TOKEN_DUPLICATE|TOKEN_ADJUST_GROUPS|TOKEN_QUERY,
5316 NULL, SecurityImpersonation, TokenImpersonation, &token);
5317 ok(ret, "got error %d\n", GetLastError());
5319 /* groups */
5320 ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
5321 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
5322 "got %d with error %d\n", ret, GetLastError());
5323 token_groups = HeapAlloc(GetProcessHeap(), 0, size);
5324 ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
5325 ok(ret, "got error %d\n", GetLastError());
5327 for (i = 0; i < token_groups->GroupCount; i++)
5329 if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
5330 break;
5333 if (i == token_groups->GroupCount)
5335 HeapFree(GetProcessHeap(), 0, token_groups);
5336 CloseHandle(token);
5337 skip("User not a member of any group\n");
5338 return;
5341 is_member = FALSE;
5342 ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
5343 ok(ret, "got error %d\n", GetLastError());
5344 ok(is_member, "not a member\n");
5346 /* disable a SID in new token */
5347 sattr.Sid = token_groups->Groups[i].Sid;
5348 sattr.Attributes = 0;
5349 r_token = NULL;
5350 ret = pCreateRestrictedToken(token, 0, 1, &sattr, 0, NULL, 0, NULL, &r_token);
5351 ok(ret, "got error %d\n", GetLastError());
5353 if (ret)
5355 /* check if a SID is enabled */
5356 is_member = TRUE;
5357 ret = pCheckTokenMembership(r_token, token_groups->Groups[i].Sid, &is_member);
5358 ok(ret, "got error %d\n", GetLastError());
5359 todo_wine ok(!is_member, "not a member\n");
5361 ret = GetTokenInformation(r_token, TokenGroups, NULL, 0, &size);
5362 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d with error %d\n",
5363 ret, GetLastError());
5364 groups2 = HeapAlloc(GetProcessHeap(), 0, size);
5365 ret = GetTokenInformation(r_token, TokenGroups, groups2, size, &size);
5366 ok(ret, "got error %d\n", GetLastError());
5368 for (j = 0; j < groups2->GroupCount; j++)
5370 if (EqualSid(groups2->Groups[j].Sid, token_groups->Groups[i].Sid))
5371 break;
5374 todo_wine ok(groups2->Groups[j].Attributes & SE_GROUP_USE_FOR_DENY_ONLY,
5375 "got wrong attributes\n");
5376 todo_wine ok((groups2->Groups[j].Attributes & SE_GROUP_ENABLED) == 0,
5377 "got wrong attributes\n");
5379 HeapFree(GetProcessHeap(), 0, groups2);
5381 size = sizeof(type);
5382 ret = GetTokenInformation(r_token, TokenType, &type, size, &size);
5383 ok(ret, "got error %d\n", GetLastError());
5384 ok(type == TokenImpersonation, "got type %u\n", type);
5386 size = sizeof(level);
5387 ret = GetTokenInformation(r_token, TokenImpersonationLevel, &level, size, &size);
5388 ok(ret, "got error %d\n", GetLastError());
5389 ok(level == SecurityImpersonation, "got level %u\n", type);
5392 HeapFree(GetProcessHeap(), 0, token_groups);
5393 CloseHandle(r_token);
5394 CloseHandle(token);
5395 CloseHandle(process_token);
5398 static void validate_default_security_descriptor(SECURITY_DESCRIPTOR *sd)
5400 BOOL ret, present, defaulted;
5401 ACL *acl;
5402 void *sid;
5404 ret = IsValidSecurityDescriptor(sd);
5405 ok(ret, "security descriptor is not valid\n");
5407 present = -1;
5408 defaulted = -1;
5409 acl = (void *)0xdeadbeef;
5410 SetLastError(0xdeadbeef);
5411 ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
5412 ok(ret, "GetSecurityDescriptorDacl error %d\n", GetLastError());
5413 todo_wine
5414 ok(present == 1, "acl is not present\n");
5415 todo_wine
5416 ok(acl != (void *)0xdeadbeef && acl != NULL, "acl pointer is not set\n");
5417 ok(defaulted == 0, "defaulted is set to TRUE\n");
5419 defaulted = -1;
5420 sid = (void *)0xdeadbeef;
5421 SetLastError(0xdeadbeef);
5422 ret = GetSecurityDescriptorOwner(sd, &sid, &defaulted);
5423 ok(ret, "GetSecurityDescriptorOwner error %d\n", GetLastError());
5424 todo_wine
5425 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
5426 ok(defaulted == 0, "defaulted is set to TRUE\n");
5428 defaulted = -1;
5429 sid = (void *)0xdeadbeef;
5430 SetLastError(0xdeadbeef);
5431 ret = GetSecurityDescriptorGroup(sd, &sid, &defaulted);
5432 ok(ret, "GetSecurityDescriptorGroup error %d\n", GetLastError());
5433 todo_wine
5434 ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
5435 ok(defaulted == 0, "defaulted is set to TRUE\n");
5438 static void test_default_handle_security(HANDLE token, HANDLE handle, GENERIC_MAPPING *mapping)
5440 DWORD ret, granted, priv_set_len;
5441 BOOL status;
5442 PRIVILEGE_SET priv_set;
5443 SECURITY_DESCRIPTOR *sd;
5445 sd = test_get_security_descriptor(handle, __LINE__);
5446 validate_default_security_descriptor(sd);
5448 priv_set_len = sizeof(priv_set);
5449 granted = 0xdeadbeef;
5450 status = 0xdeadbeef;
5451 SetLastError(0xdeadbeef);
5452 ret = AccessCheck(sd, token, MAXIMUM_ALLOWED, mapping, &priv_set, &priv_set_len, &granted, &status);
5453 todo_wine {
5454 ok(ret, "AccessCheck error %d\n", GetLastError());
5455 ok(status == 1, "expected 1, got %d\n", status);
5456 ok(granted == mapping->GenericAll, "expected all access %#x, got %#x\n", mapping->GenericAll, granted);
5458 priv_set_len = sizeof(priv_set);
5459 granted = 0xdeadbeef;
5460 status = 0xdeadbeef;
5461 SetLastError(0xdeadbeef);
5462 ret = AccessCheck(sd, token, 0, mapping, &priv_set, &priv_set_len, &granted, &status);
5463 todo_wine {
5464 ok(ret, "AccessCheck error %d\n", GetLastError());
5465 ok(status == 0 || broken(status == 1) /* NT4 */, "expected 0, got %d\n", status);
5466 ok(granted == 0 || broken(granted == mapping->GenericRead) /* NT4 */, "expected 0, got %#x\n", granted);
5468 priv_set_len = sizeof(priv_set);
5469 granted = 0xdeadbeef;
5470 status = 0xdeadbeef;
5471 SetLastError(0xdeadbeef);
5472 ret = AccessCheck(sd, token, ACCESS_SYSTEM_SECURITY, mapping, &priv_set, &priv_set_len, &granted, &status);
5473 todo_wine {
5474 ok(ret, "AccessCheck error %d\n", GetLastError());
5475 ok(status == 0, "expected 0, got %d\n", status);
5476 ok(granted == 0, "expected 0, got %#x\n", granted);
5478 priv_set_len = sizeof(priv_set);
5479 granted = 0xdeadbeef;
5480 status = 0xdeadbeef;
5481 SetLastError(0xdeadbeef);
5482 ret = AccessCheck(sd, token, mapping->GenericRead, mapping, &priv_set, &priv_set_len, &granted, &status);
5483 todo_wine {
5484 ok(ret, "AccessCheck error %d\n", GetLastError());
5485 ok(status == 1, "expected 1, got %d\n", status);
5486 ok(granted == mapping->GenericRead, "expected read access %#x, got %#x\n", mapping->GenericRead, granted);
5488 priv_set_len = sizeof(priv_set);
5489 granted = 0xdeadbeef;
5490 status = 0xdeadbeef;
5491 SetLastError(0xdeadbeef);
5492 ret = AccessCheck(sd, token, mapping->GenericWrite, mapping, &priv_set, &priv_set_len, &granted, &status);
5493 todo_wine {
5494 ok(ret, "AccessCheck error %d\n", GetLastError());
5495 ok(status == 1, "expected 1, got %d\n", status);
5496 ok(granted == mapping->GenericWrite, "expected write access %#x, got %#x\n", mapping->GenericWrite, granted);
5498 priv_set_len = sizeof(priv_set);
5499 granted = 0xdeadbeef;
5500 status = 0xdeadbeef;
5501 SetLastError(0xdeadbeef);
5502 ret = AccessCheck(sd, token, mapping->GenericExecute, mapping, &priv_set, &priv_set_len, &granted, &status);
5503 todo_wine {
5504 ok(ret, "AccessCheck error %d\n", GetLastError());
5505 ok(status == 1, "expected 1, got %d\n", status);
5506 ok(granted == mapping->GenericExecute, "expected execute access %#x, got %#x\n", mapping->GenericExecute, granted);
5508 HeapFree(GetProcessHeap(), 0, sd);
5511 static ACCESS_MASK get_obj_access(HANDLE obj)
5513 OBJECT_BASIC_INFORMATION info;
5514 NTSTATUS status;
5516 if (!pNtQueryObject) return 0;
5518 status = pNtQueryObject(obj, ObjectBasicInformation, &info, sizeof(info), NULL);
5519 ok(!status, "NtQueryObject error %#x\n", status);
5521 return info.GrantedAccess;
5524 static void test_mutex_security(HANDLE token)
5526 DWORD ret, i, access;
5527 HANDLE mutex, dup;
5528 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE | SYNCHRONIZE,
5529 STANDARD_RIGHTS_WRITE | MUTEX_MODIFY_STATE | SYNCHRONIZE,
5530 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
5531 STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS };
5532 static const struct
5534 int generic, mapped;
5535 } map[] =
5537 { 0, 0 },
5538 { GENERIC_READ, STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE },
5539 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE },
5540 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5541 { GENERIC_ALL, STANDARD_RIGHTS_ALL | MUTANT_QUERY_STATE }
5544 SetLastError(0xdeadbeef);
5545 mutex = OpenMutexA(0, FALSE, "WineTestMutex");
5546 ok(!mutex, "mutex should not exist\n");
5547 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
5549 SetLastError(0xdeadbeef);
5550 mutex = CreateMutexA(NULL, FALSE, "WineTestMutex");
5551 ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
5553 access = get_obj_access(mutex);
5554 ok(access == MUTANT_ALL_ACCESS, "expected MUTANT_ALL_ACCESS, got %#x\n", access);
5556 for (i = 0; i < ARRAY_SIZE(map); i++)
5558 SetLastError( 0xdeadbeef );
5559 ret = DuplicateHandle(GetCurrentProcess(), mutex, GetCurrentProcess(), &dup,
5560 map[i].generic, FALSE, 0);
5561 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5563 access = get_obj_access(dup);
5564 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5566 CloseHandle(dup);
5568 SetLastError(0xdeadbeef);
5569 dup = OpenMutexA(0, FALSE, "WineTestMutex");
5570 todo_wine
5571 ok(!dup, "OpenMutex should fail\n");
5572 todo_wine
5573 ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError());
5576 test_default_handle_security(token, mutex, &mapping);
5578 CloseHandle (mutex);
5581 static void test_event_security(HANDLE token)
5583 DWORD ret, i, access;
5584 HANDLE event, dup;
5585 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | EVENT_QUERY_STATE | SYNCHRONIZE,
5586 STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE | SYNCHRONIZE,
5587 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
5588 STANDARD_RIGHTS_ALL | EVENT_ALL_ACCESS };
5589 static const struct
5591 int generic, mapped;
5592 } map[] =
5594 { 0, 0 },
5595 { GENERIC_READ, STANDARD_RIGHTS_READ | EVENT_QUERY_STATE },
5596 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE },
5597 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5598 { GENERIC_ALL, STANDARD_RIGHTS_ALL | EVENT_QUERY_STATE | EVENT_MODIFY_STATE }
5601 SetLastError(0xdeadbeef);
5602 event = OpenEventA(0, FALSE, "WineTestEvent");
5603 ok(!event, "event should not exist\n");
5604 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
5606 SetLastError(0xdeadbeef);
5607 event = CreateEventA(NULL, FALSE, FALSE, "WineTestEvent");
5608 ok(event != 0, "CreateEvent error %d\n", GetLastError());
5610 access = get_obj_access(event);
5611 ok(access == EVENT_ALL_ACCESS, "expected EVENT_ALL_ACCESS, got %#x\n", access);
5613 for (i = 0; i < ARRAY_SIZE(map); i++)
5615 SetLastError( 0xdeadbeef );
5616 ret = DuplicateHandle(GetCurrentProcess(), event, GetCurrentProcess(), &dup,
5617 map[i].generic, FALSE, 0);
5618 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5620 access = get_obj_access(dup);
5621 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5623 CloseHandle(dup);
5625 SetLastError(0xdeadbeef);
5626 dup = OpenEventA(0, FALSE, "WineTestEvent");
5627 todo_wine
5628 ok(!dup, "OpenEvent should fail\n");
5629 todo_wine
5630 ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError());
5633 test_default_handle_security(token, event, &mapping);
5635 CloseHandle(event);
5638 static void test_semaphore_security(HANDLE token)
5640 DWORD ret, i, access;
5641 HANDLE sem, dup;
5642 GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | SEMAPHORE_QUERY_STATE,
5643 STANDARD_RIGHTS_WRITE | SEMAPHORE_MODIFY_STATE,
5644 STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
5645 STANDARD_RIGHTS_ALL | SEMAPHORE_ALL_ACCESS };
5646 static const struct
5648 int generic, mapped;
5649 } map[] =
5651 { 0, 0 },
5652 { GENERIC_READ, STANDARD_RIGHTS_READ | SEMAPHORE_QUERY_STATE },
5653 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | SEMAPHORE_MODIFY_STATE },
5654 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
5655 { GENERIC_ALL, STANDARD_RIGHTS_ALL | SEMAPHORE_QUERY_STATE | SEMAPHORE_MODIFY_STATE }
5658 SetLastError(0xdeadbeef);
5659 sem = OpenSemaphoreA(0, FALSE, "WineTestSemaphore");
5660 ok(!sem, "semaphore should not exist\n");
5661 ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
5663 SetLastError(0xdeadbeef);
5664 sem = CreateSemaphoreA(NULL, 0, 10, "WineTestSemaphore");
5665 ok(sem != 0, "CreateSemaphore error %d\n", GetLastError());
5667 access = get_obj_access(sem);
5668 ok(access == SEMAPHORE_ALL_ACCESS, "expected SEMAPHORE_ALL_ACCESS, got %#x\n", access);
5670 for (i = 0; i < ARRAY_SIZE(map); i++)
5672 SetLastError( 0xdeadbeef );
5673 ret = DuplicateHandle(GetCurrentProcess(), sem, GetCurrentProcess(), &dup,
5674 map[i].generic, FALSE, 0);
5675 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5677 access = get_obj_access(dup);
5678 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5680 CloseHandle(dup);
5683 test_default_handle_security(token, sem, &mapping);
5685 CloseHandle(sem);
5688 #define WINE_TEST_PIPE "\\\\.\\pipe\\WineTestPipe"
5689 static void test_named_pipe_security(HANDLE token)
5691 DWORD ret, i, access;
5692 HANDLE pipe, file, dup;
5693 GENERIC_MAPPING mapping = { FILE_GENERIC_READ,
5694 FILE_GENERIC_WRITE,
5695 FILE_GENERIC_EXECUTE,
5696 STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS };
5697 static const struct
5699 int generic, mapped;
5700 } map[] =
5702 { 0, 0 },
5703 { GENERIC_READ, FILE_GENERIC_READ },
5704 { GENERIC_WRITE, FILE_GENERIC_WRITE },
5705 { GENERIC_EXECUTE, FILE_GENERIC_EXECUTE },
5706 { GENERIC_ALL, STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS }
5708 static const struct
5710 DWORD open_mode;
5711 DWORD access;
5712 } creation_access[] =
5714 { PIPE_ACCESS_INBOUND, FILE_GENERIC_READ },
5715 { PIPE_ACCESS_OUTBOUND, FILE_GENERIC_WRITE },
5716 { PIPE_ACCESS_DUPLEX, FILE_GENERIC_READ|FILE_GENERIC_WRITE },
5717 { PIPE_ACCESS_INBOUND|WRITE_DAC, FILE_GENERIC_READ|WRITE_DAC },
5718 { PIPE_ACCESS_INBOUND|WRITE_OWNER, FILE_GENERIC_READ|WRITE_OWNER }
5719 /* ACCESS_SYSTEM_SECURITY is also valid, but will fail with ERROR_PRIVILEGE_NOT_HELD */
5722 /* Test the different security access options for pipes */
5723 for (i = 0; i < ARRAY_SIZE(creation_access); i++)
5725 SetLastError(0xdeadbeef);
5726 pipe = CreateNamedPipeA(WINE_TEST_PIPE, creation_access[i].open_mode,
5727 PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0,
5728 NMPWAIT_USE_DEFAULT_WAIT, NULL);
5729 ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe(0x%x) error %d\n",
5730 creation_access[i].open_mode, GetLastError());
5731 access = get_obj_access(pipe);
5732 ok(access == creation_access[i].access,
5733 "CreateNamedPipeA(0x%x) pipe expected access 0x%x (got 0x%x)\n",
5734 creation_access[i].open_mode, creation_access[i].access, access);
5735 CloseHandle(pipe);
5738 SetLastError(0xdeadbeef);
5739 pipe = CreateNamedPipeA(WINE_TEST_PIPE, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
5740 PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES,
5741 0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL);
5742 ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe error %d\n", GetLastError());
5744 test_default_handle_security(token, pipe, &mapping);
5746 SetLastError(0xdeadbeef);
5747 file = CreateFileA(WINE_TEST_PIPE, FILE_ALL_ACCESS, 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_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5753 for (i = 0; i < ARRAY_SIZE(map); i++)
5755 SetLastError( 0xdeadbeef );
5756 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5757 map[i].generic, FALSE, 0);
5758 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5760 access = get_obj_access(dup);
5761 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5763 CloseHandle(dup);
5766 CloseHandle(file);
5767 CloseHandle(pipe);
5769 SetLastError(0xdeadbeef);
5770 file = CreateFileA("\\\\.\\pipe\\", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
5771 ok(file != INVALID_HANDLE_VALUE || broken(file == INVALID_HANDLE_VALUE) /* before Vista */, "CreateFile error %d\n", GetLastError());
5773 if (file != INVALID_HANDLE_VALUE)
5775 access = get_obj_access(file);
5776 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5778 for (i = 0; i < ARRAY_SIZE(map); i++)
5780 SetLastError( 0xdeadbeef );
5781 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5782 map[i].generic, FALSE, 0);
5783 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5785 access = get_obj_access(dup);
5786 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5787 CloseHandle(dup);
5791 CloseHandle(file);
5794 static void test_file_security(HANDLE token)
5796 DWORD ret, i, access, bytes;
5797 HANDLE file, dup;
5798 static const struct
5800 int generic, mapped;
5801 } map[] =
5803 { 0, 0 },
5804 { GENERIC_READ, FILE_GENERIC_READ },
5805 { GENERIC_WRITE, FILE_GENERIC_WRITE },
5806 { GENERIC_EXECUTE, FILE_GENERIC_EXECUTE },
5807 { GENERIC_ALL, STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS }
5809 char temp_path[MAX_PATH];
5810 char file_name[MAX_PATH];
5811 char buf[16];
5813 GetTempPathA(MAX_PATH, temp_path);
5814 GetTempFileNameA(temp_path, "tmp", 0, file_name);
5816 /* file */
5817 SetLastError(0xdeadbeef);
5818 file = CreateFileA(file_name, GENERIC_ALL, 0, NULL, CREATE_ALWAYS, 0, NULL);
5819 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5821 access = get_obj_access(file);
5822 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5824 for (i = 0; i < ARRAY_SIZE(map); i++)
5826 SetLastError( 0xdeadbeef );
5827 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5828 map[i].generic, FALSE, 0);
5829 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5831 access = get_obj_access(dup);
5832 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5834 CloseHandle(dup);
5837 CloseHandle(file);
5839 SetLastError(0xdeadbeef);
5840 file = CreateFileA(file_name, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
5841 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5843 access = get_obj_access(file);
5844 ok(access == (FILE_READ_ATTRIBUTES | SYNCHRONIZE), "expected FILE_READ_ATTRIBUTES | SYNCHRONIZE, got %#x\n", access);
5846 bytes = 0xdeadbeef;
5847 SetLastError(0xdeadbeef);
5848 ret = ReadFile(file, buf, sizeof(buf), &bytes, NULL);
5849 ok(!ret, "ReadFile should fail\n");
5850 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
5851 ok(bytes == 0, "expected 0, got %u\n", bytes);
5853 CloseHandle(file);
5855 SetLastError(0xdeadbeef);
5856 file = CreateFileA(file_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
5857 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5859 access = get_obj_access(file);
5860 ok(access == (FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES), "expected FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES, got %#x\n", access);
5862 bytes = 0xdeadbeef;
5863 SetLastError(0xdeadbeef);
5864 ret = ReadFile(file, buf, sizeof(buf), &bytes, NULL);
5865 ok(!ret, "ReadFile should fail\n");
5866 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
5867 ok(bytes == 0, "expected 0, got %u\n", bytes);
5869 CloseHandle(file);
5870 DeleteFileA(file_name);
5872 /* directory */
5873 SetLastError(0xdeadbeef);
5874 file = CreateFileA(temp_path, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
5875 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5877 access = get_obj_access(file);
5878 ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
5880 for (i = 0; i < ARRAY_SIZE(map); i++)
5882 SetLastError( 0xdeadbeef );
5883 ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
5884 map[i].generic, FALSE, 0);
5885 ok(ret, "DuplicateHandle error %d\n", GetLastError());
5887 access = get_obj_access(dup);
5888 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
5890 CloseHandle(dup);
5893 CloseHandle(file);
5895 SetLastError(0xdeadbeef);
5896 file = CreateFileA(temp_path, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
5897 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5899 access = get_obj_access(file);
5900 ok(access == (FILE_READ_ATTRIBUTES | SYNCHRONIZE), "expected FILE_READ_ATTRIBUTES | SYNCHRONIZE, got %#x\n", access);
5902 CloseHandle(file);
5904 SetLastError(0xdeadbeef);
5905 file = CreateFileA(temp_path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
5906 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5908 access = get_obj_access(file);
5909 ok(access == (FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES), "expected FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES, got %#x\n", access);
5911 CloseHandle(file);
5914 static void test_filemap_security(void)
5916 char temp_path[MAX_PATH];
5917 char file_name[MAX_PATH];
5918 DWORD ret, i, access;
5919 HANDLE file, mapping, dup, created_mapping;
5920 static const struct
5922 int generic, mapped;
5923 BOOL open_only;
5924 } map[] =
5926 { 0, 0 },
5927 { GENERIC_READ, STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ },
5928 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE },
5929 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE },
5930 { GENERIC_ALL, STANDARD_RIGHTS_REQUIRED | SECTION_ALL_ACCESS },
5931 { SECTION_MAP_READ | SECTION_MAP_WRITE, SECTION_MAP_READ | SECTION_MAP_WRITE },
5932 { SECTION_MAP_WRITE, SECTION_MAP_WRITE },
5933 { SECTION_MAP_READ | SECTION_QUERY, SECTION_MAP_READ | SECTION_QUERY },
5934 { SECTION_QUERY, SECTION_MAP_READ, TRUE },
5935 { SECTION_QUERY | SECTION_MAP_READ, SECTION_QUERY | SECTION_MAP_READ }
5937 static const struct
5939 int prot, mapped;
5940 } prot_map[] =
5942 { 0, 0 },
5943 { PAGE_NOACCESS, 0 },
5944 { PAGE_READONLY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ },
5945 { PAGE_READWRITE, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE },
5946 { PAGE_WRITECOPY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ },
5947 { PAGE_EXECUTE, 0 },
5948 { PAGE_EXECUTE_READ, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE },
5949 { PAGE_EXECUTE_READWRITE, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE },
5950 { PAGE_EXECUTE_WRITECOPY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE }
5953 GetTempPathA(MAX_PATH, temp_path);
5954 GetTempFileNameA(temp_path, "tmp", 0, file_name);
5956 SetLastError(0xdeadbeef);
5957 file = CreateFileA(file_name, GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE, 0, NULL, CREATE_ALWAYS, 0, 0);
5958 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
5959 SetFilePointer(file, 4096, NULL, FILE_BEGIN);
5960 SetEndOfFile(file);
5962 for (i = 0; i < ARRAY_SIZE(prot_map); i++)
5964 if (map[i].open_only) continue;
5966 SetLastError(0xdeadbeef);
5967 mapping = CreateFileMappingW(file, NULL, prot_map[i].prot, 0, 4096, NULL);
5968 if (prot_map[i].mapped)
5970 if (!mapping)
5972 /* NT4 and win2k don't support EXEC on file mappings */
5973 if (prot_map[i].prot == PAGE_EXECUTE_READ || prot_map[i].prot == PAGE_EXECUTE_READWRITE || prot_map[i].prot == PAGE_EXECUTE_WRITECOPY)
5975 win_skip("CreateFileMapping doesn't support PAGE_EXECUTE protection\n");
5976 continue;
5979 ok(mapping != 0, "CreateFileMapping(%04x) error %d\n", prot_map[i].prot, GetLastError());
5981 else
5983 ok(!mapping, "CreateFileMapping(%04x) should fail\n", prot_map[i].prot);
5984 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
5985 continue;
5988 access = get_obj_access(mapping);
5989 ok(access == prot_map[i].mapped, "%d: expected %#x, got %#x\n", i, prot_map[i].mapped, access);
5991 CloseHandle(mapping);
5994 SetLastError(0xdeadbeef);
5995 mapping = CreateFileMappingW(file, NULL, PAGE_EXECUTE_READWRITE, 0, 4096, NULL);
5996 if (!mapping)
5998 /* NT4 and win2k don't support EXEC on file mappings */
5999 win_skip("CreateFileMapping doesn't support PAGE_EXECUTE protection\n");
6000 CloseHandle(file);
6001 DeleteFileA(file_name);
6002 return;
6004 ok(mapping != 0, "CreateFileMapping error %d\n", GetLastError());
6006 access = get_obj_access(mapping);
6007 ok(access == (STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE),
6008 "expected STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, got %#x\n", access);
6010 for (i = 0; i < ARRAY_SIZE(map); i++)
6012 if (map[i].open_only) continue;
6014 SetLastError( 0xdeadbeef );
6015 ret = DuplicateHandle(GetCurrentProcess(), mapping, GetCurrentProcess(), &dup,
6016 map[i].generic, FALSE, 0);
6017 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6019 access = get_obj_access(dup);
6020 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6022 CloseHandle(dup);
6025 CloseHandle(mapping);
6026 CloseHandle(file);
6027 DeleteFileA(file_name);
6029 created_mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 0x1000,
6030 "Wine Test Open Mapping");
6031 ok(created_mapping != NULL, "CreateFileMapping failed with error %u\n", GetLastError());
6033 for (i = 0; i < ARRAY_SIZE(map); i++)
6035 if (!map[i].generic) continue;
6037 mapping = OpenFileMappingA(map[i].generic, FALSE, "Wine Test Open Mapping");
6038 ok(mapping != NULL, "OpenFileMapping failed with error %d\n", GetLastError());
6039 access = get_obj_access(mapping);
6040 ok(access == map[i].mapped, "%d: unexpected access flags %#x, expected %#x\n",
6041 i, access, map[i].mapped);
6042 CloseHandle(mapping);
6045 CloseHandle(created_mapping);
6048 static void test_thread_security(void)
6050 DWORD ret, i, access;
6051 HANDLE thread, dup;
6052 static const struct
6054 int generic, mapped;
6055 } map[] =
6057 { 0, 0 },
6058 { GENERIC_READ, STANDARD_RIGHTS_READ | THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT },
6059 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | THREAD_SET_INFORMATION | THREAD_SET_CONTEXT | THREAD_TERMINATE | THREAD_SUSPEND_RESUME | 0x4 },
6060 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
6061 { GENERIC_ALL, THREAD_ALL_ACCESS_NT4 }
6064 SetLastError(0xdeadbeef);
6065 thread = CreateThread(NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
6066 ok(thread != 0, "CreateThread error %d\n", GetLastError());
6068 access = get_obj_access(thread);
6069 ok(access == THREAD_ALL_ACCESS_NT4 || access == THREAD_ALL_ACCESS_VISTA, "expected THREAD_ALL_ACCESS, got %#x\n", access);
6071 for (i = 0; i < ARRAY_SIZE(map); i++)
6073 SetLastError( 0xdeadbeef );
6074 ret = DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &dup,
6075 map[i].generic, FALSE, 0);
6076 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6078 access = get_obj_access(dup);
6079 switch (map[i].generic)
6081 case GENERIC_READ:
6082 case GENERIC_EXECUTE:
6083 ok(access == map[i].mapped ||
6084 access == (map[i].mapped | THREAD_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
6085 access == (map[i].mapped | THREAD_QUERY_LIMITED_INFORMATION | THREAD_RESUME) /* win8 */,
6086 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6087 break;
6088 case GENERIC_WRITE:
6089 todo_wine
6090 ok(access == map[i].mapped ||
6091 access == (map[i].mapped | THREAD_SET_LIMITED_INFORMATION) /* Vista+ */ ||
6092 access == (map[i].mapped | THREAD_SET_LIMITED_INFORMATION | THREAD_RESUME) /* win8 */,
6093 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6094 break;
6095 case GENERIC_ALL:
6096 ok(access == map[i].mapped || access == THREAD_ALL_ACCESS_VISTA,
6097 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6098 break;
6099 default:
6100 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6101 break;
6104 CloseHandle(dup);
6107 SetLastError( 0xdeadbeef );
6108 ret = DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &dup,
6109 THREAD_QUERY_INFORMATION, FALSE, 0);
6110 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6111 access = get_obj_access(dup);
6112 ok(access == (THREAD_QUERY_INFORMATION | THREAD_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
6113 access == THREAD_QUERY_INFORMATION /* before Vista */,
6114 "expected THREAD_QUERY_INFORMATION|THREAD_QUERY_LIMITED_INFORMATION, got %#x\n", access);
6115 CloseHandle(dup);
6117 TerminateThread(thread, 0);
6118 CloseHandle(thread);
6121 static void test_process_access(void)
6123 DWORD ret, i, access;
6124 HANDLE process, dup;
6125 STARTUPINFOA sti;
6126 PROCESS_INFORMATION pi;
6127 char cmdline[] = "winver.exe";
6128 static const struct
6130 int generic, mapped;
6131 } map[] =
6133 { 0, 0 },
6134 { GENERIC_READ, STANDARD_RIGHTS_READ | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ },
6135 { GENERIC_WRITE, STANDARD_RIGHTS_WRITE | PROCESS_SET_QUOTA | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME |
6136 PROCESS_VM_WRITE | PROCESS_DUP_HANDLE | PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION },
6137 { GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
6138 { GENERIC_ALL, PROCESS_ALL_ACCESS_NT4 }
6141 memset(&sti, 0, sizeof(sti));
6142 sti.cb = sizeof(sti);
6143 SetLastError(0xdeadbeef);
6144 ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
6145 ok(ret, "CreateProcess() error %d\n", GetLastError());
6147 CloseHandle(pi.hThread);
6148 process = pi.hProcess;
6150 access = get_obj_access(process);
6151 ok(access == PROCESS_ALL_ACCESS_NT4 || access == PROCESS_ALL_ACCESS_VISTA, "expected PROCESS_ALL_ACCESS, got %#x\n", access);
6153 for (i = 0; i < ARRAY_SIZE(map); i++)
6155 SetLastError( 0xdeadbeef );
6156 ret = DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &dup,
6157 map[i].generic, FALSE, 0);
6158 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6160 access = get_obj_access(dup);
6161 switch (map[i].generic)
6163 case GENERIC_READ:
6164 ok(access == map[i].mapped || access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION) /* Vista+ */,
6165 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6166 break;
6167 case GENERIC_WRITE:
6168 ok(access == map[i].mapped ||
6169 access == (map[i].mapped | PROCESS_TERMINATE) /* before Vista */ ||
6170 access == (map[i].mapped | PROCESS_SET_LIMITED_INFORMATION) /* win8 */ ||
6171 access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SET_LIMITED_INFORMATION) /* Win10 Anniversary Update */,
6172 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6173 break;
6174 case GENERIC_EXECUTE:
6175 ok(access == map[i].mapped || access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE) /* Vista+ */,
6176 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6177 break;
6178 case GENERIC_ALL:
6179 ok(access == map[i].mapped || access == PROCESS_ALL_ACCESS_VISTA,
6180 "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6181 break;
6182 default:
6183 ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
6184 break;
6187 CloseHandle(dup);
6190 SetLastError( 0xdeadbeef );
6191 ret = DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &dup,
6192 PROCESS_QUERY_INFORMATION, FALSE, 0);
6193 ok(ret, "DuplicateHandle error %d\n", GetLastError());
6194 access = get_obj_access(dup);
6195 ok(access == (PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
6196 access == PROCESS_QUERY_INFORMATION /* before Vista */,
6197 "expected PROCESS_QUERY_INFORMATION|PROCESS_QUERY_LIMITED_INFORMATION, got %#x\n", access);
6198 CloseHandle(dup);
6200 TerminateProcess(process, 0);
6201 CloseHandle(process);
6204 static BOOL validate_impersonation_token(HANDLE token, DWORD *token_type)
6206 DWORD ret, needed;
6207 TOKEN_TYPE type;
6208 SECURITY_IMPERSONATION_LEVEL sil;
6210 type = 0xdeadbeef;
6211 needed = 0;
6212 SetLastError(0xdeadbeef);
6213 ret = GetTokenInformation(token, TokenType, &type, sizeof(type), &needed);
6214 ok(ret, "GetTokenInformation error %d\n", GetLastError());
6215 ok(needed == sizeof(type), "GetTokenInformation should return required buffer length\n");
6216 ok(type == TokenPrimary || type == TokenImpersonation, "expected TokenPrimary or TokenImpersonation, got %d\n", type);
6218 *token_type = type;
6219 if (type != TokenImpersonation) return FALSE;
6221 needed = 0;
6222 SetLastError(0xdeadbeef);
6223 ret = GetTokenInformation(token, TokenImpersonationLevel, &sil, sizeof(sil), &needed);
6224 ok(ret, "GetTokenInformation error %d\n", GetLastError());
6225 ok(needed == sizeof(sil), "GetTokenInformation should return required buffer length\n");
6226 ok(sil == SecurityImpersonation, "expected SecurityImpersonation, got %d\n", sil);
6228 needed = 0xdeadbeef;
6229 SetLastError(0xdeadbeef);
6230 ret = GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &needed);
6231 ok(!ret, "GetTokenInformation should fail\n");
6232 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6233 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
6234 ok(needed > sizeof(TOKEN_DEFAULT_DACL), "GetTokenInformation returned empty default DACL\n");
6236 needed = 0xdeadbeef;
6237 SetLastError(0xdeadbeef);
6238 ret = GetTokenInformation(token, TokenOwner, NULL, 0, &needed);
6239 ok(!ret, "GetTokenInformation should fail\n");
6240 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6241 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
6242 ok(needed > sizeof(TOKEN_OWNER), "GetTokenInformation returned empty token owner\n");
6244 needed = 0xdeadbeef;
6245 SetLastError(0xdeadbeef);
6246 ret = GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &needed);
6247 ok(!ret, "GetTokenInformation should fail\n");
6248 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6249 ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
6250 ok(needed > sizeof(TOKEN_PRIMARY_GROUP), "GetTokenInformation returned empty token primary group\n");
6252 return TRUE;
6255 static void test_kernel_objects_security(void)
6257 HANDLE token, process_token;
6258 DWORD ret, token_type;
6260 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process_token);
6261 ok(ret, "OpenProcessToken error %d\n", GetLastError());
6263 ret = validate_impersonation_token(process_token, &token_type);
6264 ok(token_type == TokenPrimary, "expected TokenPrimary, got %d\n", token_type);
6265 ok(!ret, "access token should not be an impersonation token\n");
6267 ret = DuplicateToken(process_token, SecurityImpersonation, &token);
6268 ok(ret, "DuplicateToken error %d\n", GetLastError());
6270 ret = validate_impersonation_token(token, &token_type);
6271 ok(ret, "access token should be a valid impersonation token\n");
6272 ok(token_type == TokenImpersonation, "expected TokenImpersonation, got %d\n", token_type);
6274 test_mutex_security(token);
6275 test_event_security(token);
6276 test_named_pipe_security(token);
6277 test_semaphore_security(token);
6278 test_file_security(token);
6279 test_filemap_security();
6280 test_thread_security();
6281 test_process_access();
6282 /* FIXME: test other kernel object types */
6284 CloseHandle(process_token);
6285 CloseHandle(token);
6288 static void test_TokenIntegrityLevel(void)
6290 TOKEN_MANDATORY_LABEL *tml;
6291 BYTE buffer[64]; /* using max. 28 byte in win7 x64 */
6292 HANDLE token;
6293 DWORD size;
6294 DWORD res;
6295 static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6296 {SECURITY_MANDATORY_HIGH_RID}};
6297 static SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6298 {SECURITY_MANDATORY_MEDIUM_RID}};
6300 SetLastError(0xdeadbeef);
6301 res = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
6302 ok(res, "got %d with %d (expected TRUE)\n", res, GetLastError());
6304 SetLastError(0xdeadbeef);
6305 res = GetTokenInformation(token, TokenIntegrityLevel, buffer, sizeof(buffer), &size);
6307 /* not supported before Vista */
6308 if (!res && ((GetLastError() == ERROR_INVALID_PARAMETER) || GetLastError() == ERROR_INVALID_FUNCTION))
6310 win_skip("TokenIntegrityLevel not supported\n");
6311 CloseHandle(token);
6312 return;
6315 ok(res, "got %u with %u (expected TRUE)\n", res, GetLastError());
6316 if (!res)
6318 CloseHandle(token);
6319 return;
6322 tml = (TOKEN_MANDATORY_LABEL*) buffer;
6323 ok(tml->Label.Attributes == (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED),
6324 "got 0x%x (expected 0x%x)\n", tml->Label.Attributes, (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED));
6326 ok(EqualSid(tml->Label.Sid, &medium_level) || EqualSid(tml->Label.Sid, &high_level),
6327 "got %s (expected %s or %s)\n", debugstr_sid(tml->Label.Sid),
6328 debugstr_sid(&medium_level), debugstr_sid(&high_level));
6330 CloseHandle(token);
6333 static void test_default_dacl_owner_sid(void)
6335 HANDLE handle;
6336 BOOL ret, defaulted, present, found;
6337 DWORD size, index;
6338 SECURITY_DESCRIPTOR *sd;
6339 SECURITY_ATTRIBUTES sa;
6340 PSID owner;
6341 ACL *dacl;
6342 ACCESS_ALLOWED_ACE *ace;
6344 sd = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
6345 ret = InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION );
6346 ok( ret, "error %u\n", GetLastError() );
6348 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
6349 sa.lpSecurityDescriptor = sd;
6350 sa.bInheritHandle = FALSE;
6351 handle = CreateEventA( &sa, TRUE, TRUE, "test_event" );
6352 ok( handle != NULL, "error %u\n", GetLastError() );
6354 size = 0;
6355 ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, NULL, 0, &size );
6356 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "error %u\n", GetLastError() );
6358 sd = HeapAlloc( GetProcessHeap(), 0, size );
6359 ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, sd, size, &size );
6360 ok( ret, "error %u\n", GetLastError() );
6362 owner = (void *)0xdeadbeef;
6363 defaulted = TRUE;
6364 ret = GetSecurityDescriptorOwner( sd, &owner, &defaulted );
6365 ok( ret, "error %u\n", GetLastError() );
6366 ok( owner != (void *)0xdeadbeef, "owner not set\n" );
6367 ok( !defaulted, "owner defaulted\n" );
6369 dacl = (void *)0xdeadbeef;
6370 present = FALSE;
6371 defaulted = TRUE;
6372 ret = GetSecurityDescriptorDacl( sd, &present, &dacl, &defaulted );
6373 ok( ret, "error %u\n", GetLastError() );
6374 ok( present, "dacl not present\n" );
6375 ok( dacl != (void *)0xdeadbeef, "dacl not set\n" );
6376 ok( !defaulted, "dacl defaulted\n" );
6378 index = 0;
6379 found = FALSE;
6380 while (pGetAce( dacl, index++, (void **)&ace ))
6382 if (EqualSid( &ace->SidStart, owner )) found = TRUE;
6384 ok( found, "owner sid not found in dacl\n" );
6386 HeapFree( GetProcessHeap(), 0, sa.lpSecurityDescriptor );
6387 HeapFree( GetProcessHeap(), 0, sd );
6388 CloseHandle( handle );
6391 static void test_AdjustTokenPrivileges(void)
6393 TOKEN_PRIVILEGES tp;
6394 HANDLE token;
6395 DWORD len;
6396 LUID luid;
6397 BOOL ret;
6399 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
6400 return;
6402 if (!LookupPrivilegeValueA(NULL, SE_BACKUP_NAME, &luid))
6404 CloseHandle(token);
6405 return;
6408 tp.PrivilegeCount = 1;
6409 tp.Privileges[0].Luid = luid;
6410 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
6412 len = 0xdeadbeef;
6413 ret = AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, &len);
6414 ok(ret, "got %d\n", ret);
6415 ok(len == 0xdeadbeef, "got length %d\n", len);
6417 /* revert */
6418 tp.PrivilegeCount = 1;
6419 tp.Privileges[0].Luid = luid;
6420 tp.Privileges[0].Attributes = 0;
6421 ret = AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
6422 ok(ret, "got %d\n", ret);
6424 CloseHandle(token);
6427 static void test_AddAce(void)
6429 static SID const sidWorld = { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY} , { SECURITY_WORLD_RID } };
6431 char acl_buf[1024], ace_buf[256];
6432 ACCESS_ALLOWED_ACE *ace = (ACCESS_ALLOWED_ACE*)ace_buf;
6433 PACL acl = (PACL)acl_buf;
6434 BOOL ret;
6436 memset(ace, 0, sizeof(ace_buf));
6437 ace->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
6438 ace->Header.AceSize = sizeof(ACCESS_ALLOWED_ACE)-sizeof(DWORD)+sizeof(SID);
6439 memcpy(&ace->SidStart, &sidWorld, sizeof(sidWorld));
6441 ret = InitializeAcl(acl, sizeof(acl_buf), ACL_REVISION2);
6442 ok(ret, "InitializeAcl failed: %d\n", GetLastError());
6444 ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
6445 ok(ret, "AddAce failed: %d\n", GetLastError());
6446 ret = AddAce(acl, ACL_REVISION2, MAXDWORD, ace, ace->Header.AceSize);
6447 ok(ret, "AddAce failed: %d\n", GetLastError());
6448 ret = AddAce(acl, ACL_REVISION3, MAXDWORD, ace, ace->Header.AceSize);
6449 ok(ret, "AddAce failed: %d\n", GetLastError());
6450 ok(acl->AclRevision == ACL_REVISION3, "acl->AclRevision = %d\n", acl->AclRevision);
6451 ret = AddAce(acl, ACL_REVISION4, MAXDWORD, ace, ace->Header.AceSize);
6452 ok(ret, "AddAce failed: %d\n", GetLastError());
6453 ok(acl->AclRevision == ACL_REVISION4, "acl->AclRevision = %d\n", acl->AclRevision);
6454 ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
6455 ok(ret, "AddAce failed: %d\n", GetLastError());
6456 ok(acl->AclRevision == ACL_REVISION4, "acl->AclRevision = %d\n", acl->AclRevision);
6457 ret = AddAce(acl, ACL_REVISION2, MAXDWORD, ace, ace->Header.AceSize);
6458 ok(ret, "AddAce failed: %d\n", GetLastError());
6460 ret = AddAce(acl, MIN_ACL_REVISION-1, MAXDWORD, ace, ace->Header.AceSize);
6461 ok(ret, "AddAce failed: %d\n", GetLastError());
6462 /* next test succeededs but corrupts ACL */
6463 ret = AddAce(acl, MAX_ACL_REVISION+1, MAXDWORD, ace, ace->Header.AceSize);
6464 ok(ret, "AddAce failed: %d\n", GetLastError());
6465 ok(acl->AclRevision == MAX_ACL_REVISION+1, "acl->AclRevision = %d\n", acl->AclRevision);
6466 SetLastError(0xdeadbeef);
6467 ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
6468 ok(!ret, "AddAce succeeded\n");
6469 ok(GetLastError() == ERROR_INVALID_PARAMETER, "GetLastError() = %d\n", GetLastError());
6472 static void test_AddMandatoryAce(void)
6474 static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6475 {SECURITY_MANDATORY_LOW_RID}};
6476 static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
6477 {SECURITY_MANDATORY_MEDIUM_RID}};
6478 static SID_IDENTIFIER_AUTHORITY sia_world = {SECURITY_WORLD_SID_AUTHORITY};
6479 char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
6480 SECURITY_DESCRIPTOR *sd2, *sd = (SECURITY_DESCRIPTOR *)&buffer_sd;
6481 BOOL defaulted, present, ret, found, found2;
6482 ACL_SIZE_INFORMATION acl_size_info;
6483 SYSTEM_MANDATORY_LABEL_ACE *ace;
6484 char buffer_acl[256];
6485 ACL *acl = (ACL *)&buffer_acl;
6486 SECURITY_ATTRIBUTES sa;
6487 DWORD index, size;
6488 HANDLE handle;
6489 SID *everyone;
6490 ACL *sacl;
6492 if (!pAddMandatoryAce)
6494 win_skip("AddMandatoryAce not supported, skipping test\n");
6495 return;
6498 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
6499 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
6501 sa.nLength = sizeof(sa);
6502 sa.lpSecurityDescriptor = sd;
6503 sa.bInheritHandle = FALSE;
6505 handle = CreateEventA(&sa, TRUE, TRUE, "test_event");
6506 ok(handle != NULL, "CreateEventA failed with error %u\n", GetLastError());
6508 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6509 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6510 "Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
6512 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6513 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6514 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6516 sacl = (void *)0xdeadbeef;
6517 present = TRUE;
6518 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6519 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6520 ok(!present, "SACL is present\n");
6521 ok(sacl == (void *)0xdeadbeef, "SACL is set\n");
6523 HeapFree(GetProcessHeap(), 0, sd2);
6524 CloseHandle(handle);
6526 memset(buffer_acl, 0, sizeof(buffer_acl));
6527 ret = InitializeAcl(acl, 256, ACL_REVISION);
6528 ok(ret, "InitializeAcl failed with %u\n", GetLastError());
6530 SetLastError(0xdeadbeef);
6531 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, 0x1234, &low_level);
6532 ok(!ret, "AddMandatoryAce succeeded\n");
6533 ok(GetLastError() == ERROR_INVALID_PARAMETER,
6534 "Expected ERROR_INVALID_PARAMETER got %u\n", GetLastError());
6536 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &low_level);
6537 ok(ret, "AddMandatoryAce failed with %u\n", GetLastError());
6539 index = 0;
6540 found = FALSE;
6541 while (pGetAce(acl, index++, (void **)&ace))
6543 if (ace->Header.AceType != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
6544 ok(ace->Header.AceFlags == 0, "Expected flags 0, got %x\n", ace->Header.AceFlags);
6545 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
6546 "Expected mask SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, got %x\n", ace->Mask);
6547 ok(EqualSid(&ace->SidStart, &low_level), "Expected low integrity level\n");
6548 found = TRUE;
6550 ok(found, "Could not find mandatory label ace\n");
6552 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
6553 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6555 handle = CreateEventA(&sa, TRUE, TRUE, "test_event");
6556 ok(handle != NULL, "CreateEventA failed with error %u\n", GetLastError());
6558 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6559 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6560 "Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
6562 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6563 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6564 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6566 sacl = (void *)0xdeadbeef;
6567 present = FALSE;
6568 defaulted = TRUE;
6569 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6570 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6571 ok(present, "SACL not present\n");
6572 ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
6573 ok(!defaulted, "SACL defaulted\n");
6574 ret = pGetAclInformation(sacl, &acl_size_info, sizeof(acl_size_info), AclSizeInformation);
6575 ok(ret, "GetAclInformation failed with error %u\n", GetLastError());
6576 ok(acl_size_info.AceCount == 1, "SACL contains an unexpected ACE count %u\n", acl_size_info.AceCount);
6578 ret = pGetAce(sacl, 0, (void **)&ace);
6579 ok(ret, "GetAce failed with error %u\n", GetLastError());
6580 ok (ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE, "Unexpected ACE type %#x\n", ace->Header.AceType);
6581 ok(!ace->Header.AceFlags, "Unexpected ACE flags %#x\n", ace->Header.AceFlags);
6582 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, "Unexpected ACE mask %#x\n", ace->Mask);
6583 ok(EqualSid(&ace->SidStart, &low_level), "Expected low integrity level\n");
6585 HeapFree(GetProcessHeap(), 0, sd2);
6587 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, &medium_level);
6588 ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
6590 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6591 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6593 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6594 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6595 "Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
6597 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6598 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6599 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6601 sacl = (void *)0xdeadbeef;
6602 present = FALSE;
6603 defaulted = TRUE;
6604 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6605 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6606 ok(present, "SACL not present\n");
6607 ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
6608 ok(sacl->AceCount == 2, "Expected 2 ACEs, got %d\n", sacl->AceCount);
6609 ok(!defaulted, "SACL defaulted\n");
6611 index = 0;
6612 found = found2 = FALSE;
6613 while (pGetAce(sacl, index++, (void **)&ace))
6615 if (ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
6617 if (EqualSid(&ace->SidStart, &low_level))
6619 found = TRUE;
6620 ok(!ace->Header.AceFlags, "Expected 0 as flags, got %#x\n", ace->Header.AceFlags);
6621 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
6622 "Expected SYSTEM_MANDATORY_LABEL_NO_WRITE_UP as mask, got %#x\n", ace->Mask);
6624 if (EqualSid(&ace->SidStart, &medium_level))
6626 found2 = TRUE;
6627 ok(!ace->Header.AceFlags, "Expected 0 as flags, got %#x\n", ace->Header.AceFlags);
6628 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP,
6629 "Expected SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP as mask, got %#x\n", ace->Mask);
6633 ok(found, "Could not find low mandatory label\n");
6634 ok(found2, "Could not find medium mandatory label\n");
6636 HeapFree(GetProcessHeap(), 0, sd2);
6638 ret = SetSecurityDescriptorSacl(sd, FALSE, NULL, FALSE);
6639 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6641 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6642 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6644 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6645 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6646 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6648 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6649 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6650 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6652 sacl = (void *)0xdeadbeef;
6653 present = FALSE;
6654 defaulted = TRUE;
6655 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6656 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6657 ok(present, "SACL not present\n");
6658 ok(sacl && sacl != (void *)0xdeadbeef, "SACL not set\n");
6659 ok(!defaulted, "SACL defaulted\n");
6660 ok(!sacl->AceCount, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
6662 HeapFree(GetProcessHeap(), 0, sd2);
6664 ret = InitializeAcl(acl, 256, ACL_REVISION);
6665 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
6667 ret = pAddMandatoryAce(acl, ACL_REVISION3, 0, SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, &medium_level);
6668 ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
6670 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
6671 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6673 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6674 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6676 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6677 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6678 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6680 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6681 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6682 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6684 sacl = (void *)0xdeadbeef;
6685 present = FALSE;
6686 defaulted = TRUE;
6687 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6688 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6689 ok(present, "SACL not present\n");
6690 ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
6691 ok(sacl->AclRevision == ACL_REVISION3, "Expected revision 3, got %d\n", sacl->AclRevision);
6692 ok(!defaulted, "SACL defaulted\n");
6694 HeapFree(GetProcessHeap(), 0, sd2);
6696 ret = InitializeAcl(acl, 256, ACL_REVISION);
6697 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
6699 ret = AllocateAndInitializeSid(&sia_world, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, (void **)&everyone);
6700 ok(ret, "AllocateAndInitializeSid failed with error %u\n", GetLastError());
6702 ret = AddAccessAllowedAce(acl, ACL_REVISION, KEY_READ, everyone);
6703 ok(ret, "AddAccessAllowedAce failed with error %u\n", GetLastError());
6705 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
6706 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6708 ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
6709 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
6711 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
6712 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6713 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
6715 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
6716 ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
6717 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
6719 sacl = (void *)0xdeadbeef;
6720 present = FALSE;
6721 defaulted = TRUE;
6722 ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
6723 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
6724 ok(present, "SACL not present\n");
6725 ok(sacl && sacl != (void *)0xdeadbeef, "SACL not set\n");
6726 ok(!defaulted, "SACL defaulted\n");
6727 ok(!sacl->AceCount, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
6729 FreeSid(everyone);
6730 HeapFree(GetProcessHeap(), 0, sd2);
6731 CloseHandle(handle);
6734 static void test_system_security_access(void)
6736 static const WCHAR testkeyW[] =
6737 {'S','O','F','T','W','A','R','E','\\','W','i','n','e','\\','S','A','C','L','t','e','s','t',0};
6738 LONG res;
6739 HKEY hkey;
6740 PSECURITY_DESCRIPTOR sd;
6741 ACL *sacl;
6742 DWORD err, len = 128;
6743 TOKEN_PRIVILEGES priv, *priv_prev;
6744 HANDLE token;
6745 LUID luid;
6746 BOOL ret;
6748 if (!OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token )) return;
6749 if (!LookupPrivilegeValueA( NULL, SE_SECURITY_NAME, &luid ))
6751 CloseHandle( token );
6752 return;
6755 /* ACCESS_SYSTEM_SECURITY requires special privilege */
6756 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ|ACCESS_SYSTEM_SECURITY, NULL, &hkey, NULL );
6757 if (res == ERROR_ACCESS_DENIED)
6759 skip( "unprivileged user\n" );
6760 CloseHandle( token );
6761 return;
6763 todo_wine ok( res == ERROR_PRIVILEGE_NOT_HELD, "got %d\n", res );
6765 priv.PrivilegeCount = 1;
6766 priv.Privileges[0].Luid = luid;
6767 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
6769 priv_prev = HeapAlloc( GetProcessHeap(), 0, len );
6770 ret = AdjustTokenPrivileges( token, FALSE, &priv, len, priv_prev, &len );
6771 ok( ret, "got %u\n", GetLastError());
6773 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ|ACCESS_SYSTEM_SECURITY, NULL, &hkey, NULL );
6774 if (res == ERROR_PRIVILEGE_NOT_HELD)
6776 win_skip( "privilege not held\n" );
6777 HeapFree( GetProcessHeap(), 0, priv_prev );
6778 CloseHandle( token );
6779 return;
6781 ok( !res, "got %d\n", res );
6783 /* restore privileges */
6784 ret = AdjustTokenPrivileges( token, FALSE, priv_prev, 0, NULL, NULL );
6785 ok( ret, "got %u\n", GetLastError() );
6786 HeapFree( GetProcessHeap(), 0, priv_prev );
6788 /* privilege is checked on access */
6789 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6790 todo_wine ok( err == ERROR_PRIVILEGE_NOT_HELD || err == ERROR_ACCESS_DENIED, "got %u\n", err );
6791 if (err == ERROR_SUCCESS)
6792 LocalFree( sd );
6794 priv.PrivilegeCount = 1;
6795 priv.Privileges[0].Luid = luid;
6796 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
6798 priv_prev = HeapAlloc( GetProcessHeap(), 0, len );
6799 ret = AdjustTokenPrivileges( token, FALSE, &priv, len, priv_prev, &len );
6800 ok( ret, "got %u\n", GetLastError());
6802 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6803 ok( err == ERROR_SUCCESS, "got %u\n", err );
6804 RegCloseKey( hkey );
6805 LocalFree( sd );
6807 /* handle created without ACCESS_SYSTEM_SECURITY, privilege held */
6808 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ, NULL, &hkey, NULL );
6809 ok( res == ERROR_SUCCESS, "got %d\n", res );
6811 sd = NULL;
6812 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6813 todo_wine ok( err == ERROR_SUCCESS, "got %u\n", err );
6814 RegCloseKey( hkey );
6815 LocalFree( sd );
6817 /* restore privileges */
6818 ret = AdjustTokenPrivileges( token, FALSE, priv_prev, 0, NULL, NULL );
6819 ok( ret, "got %u\n", GetLastError() );
6820 HeapFree( GetProcessHeap(), 0, priv_prev );
6822 /* handle created without ACCESS_SYSTEM_SECURITY, privilege not held */
6823 res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ, NULL, &hkey, NULL );
6824 ok( res == ERROR_SUCCESS, "got %d\n", res );
6826 err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
6827 ok( err == ERROR_PRIVILEGE_NOT_HELD || err == ERROR_ACCESS_DENIED, "got %u\n", err );
6828 RegCloseKey( hkey );
6830 res = RegDeleteKeyW( HKEY_LOCAL_MACHINE, testkeyW );
6831 ok( !res, "got %d\n", res );
6832 CloseHandle( token );
6835 static void test_GetWindowsAccountDomainSid(void)
6837 char *user, buffer1[SECURITY_MAX_SID_SIZE], buffer2[SECURITY_MAX_SID_SIZE];
6838 SID_IDENTIFIER_AUTHORITY domain_ident = { SECURITY_NT_AUTHORITY };
6839 PSID domain_sid = (PSID *)&buffer1;
6840 PSID domain_sid2 = (PSID *)&buffer2;
6841 DWORD sid_size;
6842 PSID user_sid;
6843 HANDLE token;
6844 BOOL bret = TRUE;
6845 int i;
6847 if (!pGetWindowsAccountDomainSid)
6849 win_skip("GetWindowsAccountDomainSid not available\n");
6850 return;
6853 if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
6855 if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
6856 else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
6858 if (!bret)
6860 win_skip("Failed to get current user token\n");
6861 return;
6864 bret = GetTokenInformation(token, TokenUser, NULL, 0, &sid_size);
6865 ok(!bret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
6866 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
6867 user = HeapAlloc(GetProcessHeap(), 0, sid_size);
6868 bret = GetTokenInformation(token, TokenUser, user, sid_size, &sid_size);
6869 ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
6870 CloseHandle(token);
6871 user_sid = ((TOKEN_USER *)user)->User.Sid;
6873 SetLastError(0xdeadbeef);
6874 bret = pGetWindowsAccountDomainSid(0, 0, 0);
6875 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6876 ok(GetLastError() == ERROR_INVALID_SID, "expected ERROR_INVALID_SID, got %d\n", GetLastError());
6878 SetLastError(0xdeadbeef);
6879 bret = pGetWindowsAccountDomainSid(user_sid, 0, 0);
6880 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6881 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
6883 sid_size = SECURITY_MAX_SID_SIZE;
6884 SetLastError(0xdeadbeef);
6885 bret = pGetWindowsAccountDomainSid(user_sid, 0, &sid_size);
6886 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6887 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
6888 ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
6890 SetLastError(0xdeadbeef);
6891 bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, 0);
6892 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6893 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
6895 sid_size = 1;
6896 SetLastError(0xdeadbeef);
6897 bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, &sid_size);
6898 ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
6899 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
6900 ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
6902 sid_size = SECURITY_MAX_SID_SIZE;
6903 bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, &sid_size);
6904 ok(bret, "GetWindowsAccountDomainSid failed with error %d\n", GetLastError());
6905 ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
6906 InitializeSid(domain_sid2, &domain_ident, 4);
6907 for (i = 0; i < 4; i++)
6908 *GetSidSubAuthority(domain_sid2, i) = *GetSidSubAuthority(user_sid, i);
6909 ok(EqualSid(domain_sid, domain_sid2), "unexpected domain sid %s != %s\n",
6910 debugstr_sid(domain_sid), debugstr_sid(domain_sid2));
6912 HeapFree(GetProcessHeap(), 0, user);
6915 static void test_GetSidIdentifierAuthority(void)
6917 char buffer[SECURITY_MAX_SID_SIZE];
6918 PSID authority_sid = (PSID *)buffer;
6919 PSID_IDENTIFIER_AUTHORITY id;
6920 BOOL ret;
6922 if (!pGetSidIdentifierAuthority)
6924 win_skip("GetSidIdentifierAuthority not available\n");
6925 return;
6928 memset(buffer, 0xcc, sizeof(buffer));
6929 ret = IsValidSid(authority_sid);
6930 ok(!ret, "expected FALSE, got %u\n", ret);
6932 SetLastError(0xdeadbeef);
6933 id = GetSidIdentifierAuthority(authority_sid);
6934 ok(id != NULL, "got NULL pointer as identifier authority\n");
6935 ok(GetLastError() == ERROR_SUCCESS, "expected ERROR_SUCCESS, got %u\n", GetLastError());
6937 SetLastError(0xdeadbeef);
6938 id = GetSidIdentifierAuthority(NULL);
6939 ok(id != NULL, "got NULL pointer as identifier authority\n");
6940 ok(GetLastError() == ERROR_SUCCESS, "expected ERROR_SUCCESS, got %u\n", GetLastError());
6943 static void test_pseudo_tokens(void)
6945 TOKEN_STATISTICS statistics1, statistics2;
6946 HANDLE token;
6947 DWORD retlen;
6948 BOOL ret;
6950 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
6951 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
6952 memset(&statistics1, 0x11, sizeof(statistics1));
6953 ret = GetTokenInformation(token, TokenStatistics, &statistics1, sizeof(statistics1), &retlen);
6954 ok(ret, "GetTokenInformation failed with %u\n", GetLastError());
6955 CloseHandle(token);
6957 /* test GetCurrentProcessToken() */
6958 SetLastError(0xdeadbeef);
6959 memset(&statistics2, 0x22, sizeof(statistics2));
6960 ret = GetTokenInformation(GetCurrentProcessToken(), TokenStatistics,
6961 &statistics2, sizeof(statistics2), &retlen);
6962 ok(ret || broken(GetLastError() == ERROR_INVALID_HANDLE),
6963 "GetTokenInformation failed with %u\n", GetLastError());
6964 if (ret)
6965 ok(!memcmp(&statistics1, &statistics2, sizeof(statistics1)), "Token statistics do not match\n");
6966 else
6967 win_skip("CurrentProcessToken not supported, skipping test\n");
6969 /* test GetCurrentThreadEffectiveToken() */
6970 SetLastError(0xdeadbeef);
6971 memset(&statistics2, 0x22, sizeof(statistics2));
6972 ret = GetTokenInformation(GetCurrentThreadEffectiveToken(), TokenStatistics,
6973 &statistics2, sizeof(statistics2), &retlen);
6974 ok(ret || broken(GetLastError() == ERROR_INVALID_HANDLE),
6975 "GetTokenInformation failed with %u\n", GetLastError());
6976 if (ret)
6977 ok(!memcmp(&statistics1, &statistics2, sizeof(statistics1)), "Token statistics do not match\n");
6978 else
6979 win_skip("CurrentThreadEffectiveToken not supported, skipping test\n");
6981 SetLastError(0xdeadbeef);
6982 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
6983 ok(!ret, "OpenThreadToken should have failed\n");
6984 ok(GetLastError() == ERROR_NO_TOKEN, "Expected ERROR_NO_TOKEN, got %u\n", GetLastError());
6986 /* test GetCurrentThreadToken() */
6987 SetLastError(0xdeadbeef);
6988 ret = GetTokenInformation(GetCurrentThreadToken(), TokenStatistics,
6989 &statistics2, sizeof(statistics2), &retlen);
6990 todo_wine ok(GetLastError() == ERROR_NO_TOKEN || broken(GetLastError() == ERROR_INVALID_HANDLE),
6991 "Expected ERROR_NO_TOKEN, got %u\n", GetLastError());
6994 static void test_maximum_allowed(void)
6996 HANDLE (WINAPI *pCreateEventExA)(SECURITY_ATTRIBUTES *, LPCSTR, DWORD, DWORD);
6997 char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH], buffer_acl[256];
6998 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&buffer_sd;
6999 SECURITY_ATTRIBUTES sa;
7000 ACL *acl = (ACL *)&buffer_acl;
7001 HMODULE hkernel32 = GetModuleHandleA("kernel32.dll");
7002 ACCESS_MASK mask;
7003 HANDLE handle;
7004 BOOL ret;
7006 pCreateEventExA = (void *)GetProcAddress(hkernel32, "CreateEventExA");
7007 if (!pCreateEventExA)
7009 win_skip("CreateEventExA is not available\n");
7010 return;
7013 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7014 ok(ret, "InitializeSecurityDescriptor failed with %u\n", GetLastError());
7015 memset(buffer_acl, 0, sizeof(buffer_acl));
7016 ret = InitializeAcl(acl, 256, ACL_REVISION);
7017 ok(ret, "InitializeAcl failed with %u\n", GetLastError());
7018 ret = SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
7019 ok(ret, "SetSecurityDescriptorDacl failed with %u\n", GetLastError());
7021 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
7022 sa.lpSecurityDescriptor = sd;
7023 sa.bInheritHandle = FALSE;
7025 handle = pCreateEventExA(&sa, NULL, 0, MAXIMUM_ALLOWED | 0x4);
7026 ok(handle != NULL, "CreateEventExA failed with error %u\n", GetLastError());
7027 mask = get_obj_access(handle);
7028 ok(mask == EVENT_ALL_ACCESS, "Expected %x, got %x\n", EVENT_ALL_ACCESS, mask);
7029 CloseHandle(handle);
7032 static void test_token_label(void)
7034 static SID medium_sid = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
7035 {SECURITY_MANDATORY_MEDIUM_RID}};
7036 static SID high_sid = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
7037 {SECURITY_MANDATORY_HIGH_RID}};
7038 SECURITY_DESCRIPTOR_CONTROL control;
7039 SYSTEM_MANDATORY_LABEL_ACE *ace;
7040 BOOL ret, present, defaulted;
7041 SECURITY_DESCRIPTOR *sd;
7042 ACL *sacl = NULL, *dacl;
7043 DWORD size, revision;
7044 HANDLE token;
7045 char *str;
7046 SID *sid;
7048 ret = OpenProcessToken(GetCurrentProcess(), READ_CONTROL | WRITE_OWNER, &token);
7049 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
7051 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
7052 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7053 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7055 sd = HeapAlloc(GetProcessHeap(), 0, size);
7056 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd, size, &size);
7057 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7059 ret = GetSecurityDescriptorControl(sd, &control, &revision);
7060 ok(ret, "GetSecurityDescriptorControl failed with error %u\n", GetLastError());
7061 todo_wine ok(control == (SE_SELF_RELATIVE | SE_SACL_AUTO_INHERITED | SE_SACL_PRESENT) ||
7062 broken(control == SE_SELF_RELATIVE) /* WinXP, Win2003 */,
7063 "Unexpected security descriptor control %#x\n", control);
7064 ok(revision == 1, "Unexpected security descriptor revision %u\n", revision);
7066 sid = (void *)0xdeadbeef;
7067 defaulted = TRUE;
7068 ret = GetSecurityDescriptorOwner(sd, (void **)&sid, &defaulted);
7069 ok(ret, "GetSecurityDescriptorOwner failed with error %u\n", GetLastError());
7070 ok(!sid, "Owner present\n");
7071 ok(!defaulted, "Owner defaulted\n");
7073 sid = (void *)0xdeadbeef;
7074 defaulted = TRUE;
7075 ret = GetSecurityDescriptorGroup(sd, (void **)&sid, &defaulted);
7076 ok(ret, "GetSecurityDescriptorGroup failed with error %u\n", GetLastError());
7077 ok(!sid, "Group present\n");
7078 ok(!defaulted, "Group defaulted\n");
7080 ret = GetSecurityDescriptorSacl(sd, &present, &sacl, &defaulted);
7081 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
7082 ok(present || broken(!present) /* WinXP, Win2003 */, "No SACL in the security descriptor\n");
7083 ok(sacl || broken(!sacl) /* WinXP, Win2003 */, "NULL SACL in the security descriptor\n");
7085 if (present)
7087 ok(!defaulted, "SACL defaulted\n");
7088 ok(sacl->AceCount == 1, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
7090 ret = pGetAce(sacl, 0, (void **)&ace);
7091 ok(ret, "GetAce failed with error %u\n", GetLastError());
7093 ok(ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE,
7094 "Unexpected ACE type %#x\n", ace->Header.AceType);
7095 ok(!ace->Header.AceFlags, "Unexpected ACE flags %#x\n", ace->Header.AceFlags);
7096 ok(ace->Header.AceSize, "Unexpected ACE size %u\n", ace->Header.AceSize);
7097 ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, "Unexpected ACE mask %#x\n", ace->Mask);
7099 sid = (SID *)&ace->SidStart;
7100 ConvertSidToStringSidA(sid, &str);
7101 ok(EqualSid(sid, &medium_sid) || EqualSid(sid, &high_sid), "Got unexpected SID %s\n", str);
7102 LocalFree(str);
7105 ret = GetSecurityDescriptorDacl(sd, &present, &dacl, &defaulted);
7106 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7107 todo_wine ok(!present, "DACL present\n");
7109 HeapFree(GetProcessHeap(), 0, sd);
7110 CloseHandle(token);
7113 static void test_token_security_descriptor(void)
7115 static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
7116 {SECURITY_MANDATORY_LOW_RID}};
7117 char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
7118 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&buffer_sd, *sd2;
7119 char buffer_acl[256], buffer[MAX_PATH];
7120 ACL *acl = (ACL *)&buffer_acl, *acl2, *acl_child;
7121 BOOL defaulted, present, ret, found;
7122 HANDLE token, token2, token3;
7123 EXPLICIT_ACCESSW exp_access;
7124 PROCESS_INFORMATION info;
7125 DWORD size, index, retd;
7126 ACCESS_ALLOWED_ACE *ace;
7127 SECURITY_ATTRIBUTES sa;
7128 STARTUPINFOA startup;
7129 PSID psid;
7131 if (!pDuplicateTokenEx || !pConvertStringSidToSidA || !pAddAccessAllowedAceEx || !pGetAce
7132 || !pSetEntriesInAclW)
7134 win_skip("Some functions not available\n");
7135 return;
7138 /* Test whether we can create tokens with security descriptors */
7139 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
7140 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
7142 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7143 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
7145 memset(buffer_acl, 0, sizeof(buffer_acl));
7146 ret = InitializeAcl(acl, 256, ACL_REVISION);
7147 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
7149 ret = pConvertStringSidToSidA("S-1-5-6", &psid);
7150 ok(ret, "ConvertStringSidToSidA failed with error %u\n", GetLastError());
7152 ret = pAddAccessAllowedAceEx(acl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, GENERIC_ALL, psid);
7153 ok(ret, "AddAccessAllowedAceEx failed with error %u\n", GetLastError());
7155 ret = SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
7156 ok(ret, "SetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7158 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
7159 sa.lpSecurityDescriptor = sd;
7160 sa.bInheritHandle = FALSE;
7162 ret = pDuplicateTokenEx(token, MAXIMUM_ALLOWED, &sa, SecurityImpersonation, TokenImpersonation, &token2);
7163 ok(ret, "DuplicateTokenEx failed with error %u\n", GetLastError());
7165 ret = GetKernelObjectSecurity(token2, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7166 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7167 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7169 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
7170 ret = GetKernelObjectSecurity(token2, DACL_SECURITY_INFORMATION, sd2, size, &size);
7171 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7173 acl2 = (void *)0xdeadbeef;
7174 present = FALSE;
7175 defaulted = TRUE;
7176 ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
7177 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7178 ok(present, "acl2 not present\n");
7179 ok(acl2 != (void *)0xdeadbeef, "acl2 not set\n");
7180 ok(acl2->AceCount == 1, "Expected 1 ACE, got %d\n", acl2->AceCount);
7181 ok(!defaulted, "acl2 defaulted\n");
7183 ret = pGetAce(acl2, 0, (void **)&ace);
7184 ok(ret, "GetAce failed with error %u\n", GetLastError());
7185 ok(ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE, "Unexpected ACE type %#x\n", ace->Header.AceType);
7186 ok(EqualSid(&ace->SidStart, psid), "Expected access allowed ACE\n");
7187 ok(ace->Header.AceFlags == NO_PROPAGATE_INHERIT_ACE,
7188 "Expected NO_PROPAGATE_INHERIT_ACE as flags, got %x\n", ace->Header.AceFlags);
7190 HeapFree(GetProcessHeap(), 0, sd2);
7192 /* Duplicate token without security attributes.
7193 * Tokens do not inherit the security descriptor in DuplicateToken. */
7194 ret = pDuplicateTokenEx(token2, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenImpersonation, &token3);
7195 ok(ret, "DuplicateTokenEx failed with error %u\n", GetLastError());
7197 ret = GetKernelObjectSecurity(token3, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7198 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7199 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7201 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
7202 ret = GetKernelObjectSecurity(token3, DACL_SECURITY_INFORMATION, sd2, size, &size);
7203 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7205 acl2 = (void *)0xdeadbeef;
7206 present = FALSE;
7207 defaulted = TRUE;
7208 ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
7209 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7210 todo_wine
7211 ok(present, "DACL not present\n");
7213 if (present)
7215 ok(acl2 != (void *)0xdeadbeef, "DACL not set\n");
7216 ok(!defaulted, "DACL defaulted\n");
7218 index = 0;
7219 found = FALSE;
7220 while (pGetAce(acl2, index++, (void **)&ace))
7222 if (ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE && EqualSid(&ace->SidStart, psid))
7223 found = TRUE;
7225 ok(!found, "Access allowed ACE was inherited\n");
7228 HeapFree(GetProcessHeap(), 0, sd2);
7230 /* When creating a child process, the process does inherit the token of
7231 * the parent but not the DACL of the token */
7232 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7233 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7234 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7236 sd2 = HeapAlloc(GetProcessHeap(), 0, size);
7237 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd2, size, &size);
7238 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7240 acl2 = (void *)0xdeadbeef;
7241 present = FALSE;
7242 defaulted = TRUE;
7243 ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
7244 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7245 ok(present, "DACL not present\n");
7246 ok(acl2 != (void *)0xdeadbeef, "DACL not set\n");
7247 ok(!defaulted, "DACL defaulted\n");
7249 exp_access.grfAccessPermissions = GENERIC_ALL;
7250 exp_access.grfAccessMode = GRANT_ACCESS;
7251 exp_access.grfInheritance = NO_PROPAGATE_INHERIT_ACE;
7252 exp_access.Trustee.pMultipleTrustee = NULL;
7253 exp_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
7254 exp_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
7255 exp_access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
7256 exp_access.Trustee.ptstrName = (void*)psid;
7258 retd = pSetEntriesInAclW(1, &exp_access, acl2, &acl_child);
7259 ok(retd == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", retd);
7261 memset(sd, 0, sizeof(buffer_sd));
7262 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7263 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
7265 ret = SetSecurityDescriptorDacl(sd, TRUE, acl_child, FALSE);
7266 ok(ret, "SetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7268 ret = SetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd);
7269 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
7271 /* The security label is also not inherited */
7272 if (pAddMandatoryAce)
7274 ret = InitializeAcl(acl, 256, ACL_REVISION);
7275 ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
7277 ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &low_level);
7278 ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
7280 memset(sd, 0, sizeof(buffer_sd));
7281 ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
7282 ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
7284 ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
7285 ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
7287 ret = SetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd);
7288 ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
7290 else
7291 win_skip("SYSTEM_MANDATORY_LABEL not supported\n");
7293 /* Start child process with our modified token */
7294 memset(&startup, 0, sizeof(startup));
7295 startup.cb = sizeof(startup);
7296 startup.dwFlags = STARTF_USESHOWWINDOW;
7297 startup.wShowWindow = SW_SHOWNORMAL;
7299 sprintf(buffer, "%s tests/security.c test_token_sd", myARGV[0]);
7300 ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &info);
7301 ok(ret, "CreateProcess failed with error %u\n", GetLastError());
7302 winetest_wait_child_process(info.hProcess);
7303 CloseHandle(info.hProcess);
7304 CloseHandle(info.hThread);
7306 LocalFree(acl_child);
7307 HeapFree(GetProcessHeap(), 0, sd2);
7308 LocalFree(psid);
7310 CloseHandle(token3);
7311 CloseHandle(token2);
7312 CloseHandle(token);
7315 static void test_child_token_sd(void)
7317 static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
7318 {SECURITY_MANDATORY_LOW_RID}};
7319 SYSTEM_MANDATORY_LABEL_ACE *ace_label;
7320 BOOL ret, present, defaulted;
7321 ACCESS_ALLOWED_ACE *acc_ace;
7322 SECURITY_DESCRIPTOR *sd;
7323 DWORD size, i;
7324 HANDLE token;
7325 PSID psid;
7326 ACL *acl;
7328 ret = pConvertStringSidToSidA("S-1-5-6", &psid);
7329 ok(ret, "ConvertStringSidToSidA failed with error %u\n", GetLastError());
7331 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
7332 ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
7334 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, NULL, 0, &size);
7335 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7336 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7338 sd = HeapAlloc(GetProcessHeap(), 0, size);
7339 ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd, size, &size);
7340 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7342 acl = NULL;
7343 present = FALSE;
7344 defaulted = TRUE;
7345 ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
7346 ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
7347 ok(present, "DACL not present\n");
7348 ok(acl && acl != (void *)0xdeadbeef, "Got invalid DACL\n");
7349 ok(!defaulted, "DACL defaulted\n");
7351 ok(acl->AceCount, "Expected at least one ACE\n");
7352 for (i = 0; i < acl->AceCount; i++)
7354 ok(pGetAce(acl, i, (void **)&acc_ace), "GetAce failed with error %u\n", GetLastError());
7355 ok(acc_ace->Header.AceType != ACCESS_ALLOWED_ACE_TYPE || !EqualSid(&acc_ace->SidStart, psid),
7356 "ACE inherited from the parent\n");
7359 LocalFree(psid);
7360 HeapFree(GetProcessHeap(), 0, sd);
7362 if (!pAddMandatoryAce)
7364 win_skip("SYSTEM_MANDATORY_LABEL not supported\n");
7365 return;
7368 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
7369 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
7370 "Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
7372 sd = HeapAlloc(GetProcessHeap(), 0, size);
7373 ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd, size, &size);
7374 ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
7376 acl = NULL;
7377 present = FALSE;
7378 defaulted = TRUE;
7379 ret = GetSecurityDescriptorSacl(sd, &present, &acl, &defaulted);
7380 ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
7381 ok(present, "SACL not present\n");
7382 ok(acl && acl != (void *)0xdeadbeef, "Got invalid SACL\n");
7383 ok(!defaulted, "SACL defaulted\n");
7384 ok(acl->AceCount == 1, "Expected exactly one ACE\n");
7385 ret = pGetAce(acl, 0, (void **)&ace_label);
7386 ok(ret, "GetAce failed with error %u\n", GetLastError());
7387 ok(ace_label->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE,
7388 "Unexpected ACE type %#x\n", ace_label->Header.AceType);
7389 ok(!EqualSid(&ace_label->SidStart, &low_level),
7390 "Low integrity level should not have been inherited\n");
7392 HeapFree(GetProcessHeap(), 0, sd);
7395 static void test_GetExplicitEntriesFromAclW(void)
7397 static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
7398 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
7399 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
7400 PSID everyone_sid = NULL, users_sid = NULL;
7401 EXPLICIT_ACCESSW access;
7402 EXPLICIT_ACCESSW *access2;
7403 PACL new_acl, old_acl = NULL;
7404 ULONG count;
7405 DWORD res;
7407 if (!pGetExplicitEntriesFromAclW)
7409 win_skip("GetExplicitEntriesFromAclW is not available\n");
7410 return;
7413 if (!pSetEntriesInAclW)
7415 win_skip("SetEntriesInAclW is not available\n");
7416 return;
7419 old_acl = HeapAlloc(GetProcessHeap(), 0, 256);
7420 res = InitializeAcl(old_acl, 256, ACL_REVISION);
7421 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
7423 win_skip("ACLs not implemented - skipping tests\n");
7424 HeapFree(GetProcessHeap(), 0, old_acl);
7425 return;
7427 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
7429 res = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyone_sid);
7430 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
7432 res = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
7433 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &users_sid);
7434 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
7436 res = AddAccessAllowedAce(old_acl, ACL_REVISION, KEY_READ, users_sid);
7437 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
7439 access2 = NULL;
7440 res = pGetExplicitEntriesFromAclW(old_acl, &count, &access2);
7441 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7442 ok(count == 1, "Expected count == 1, got %d\n", count);
7443 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7444 ok(access2[0].grfAccessPermissions == KEY_READ, "Expected KEY_READ, got %d\n", access2[0].grfAccessPermissions);
7445 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7446 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7447 ok(EqualSid(access2[0].Trustee.ptstrName, users_sid), "Expected equal SIDs\n");
7448 LocalFree(access2);
7450 access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
7451 access.Trustee.pMultipleTrustee = NULL;
7453 access.grfAccessPermissions = KEY_WRITE;
7454 access.grfAccessMode = GRANT_ACCESS;
7455 access.grfInheritance = NO_INHERITANCE;
7456 access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
7457 access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
7458 access.Trustee.ptstrName = everyone_sid;
7459 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7460 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7461 ok(new_acl != NULL, "returned acl was NULL\n");
7463 access2 = NULL;
7464 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7465 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7466 ok(count == 2, "Expected count == 2, got %d\n", count);
7467 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7468 ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
7469 ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
7470 "Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
7471 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7472 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7473 ok(EqualSid(access2[0].Trustee.ptstrName, everyone_sid), "Expected equal SIDs\n");
7474 LocalFree(access2);
7475 LocalFree(new_acl);
7477 access.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
7478 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7479 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7480 ok(new_acl != NULL, "returned acl was NULL\n");
7482 access2 = NULL;
7483 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7484 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7485 ok(count == 2, "Expected count == 2, got %d\n", count);
7486 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7487 ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
7488 ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
7489 "Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
7490 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7491 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7492 ok(EqualSid(access2[0].Trustee.ptstrName, everyone_sid), "Expected equal SIDs\n");
7493 LocalFree(access2);
7494 LocalFree(new_acl);
7496 access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
7497 access.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
7498 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7499 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7500 ok(new_acl != NULL, "returned acl was NULL\n");
7502 access2 = NULL;
7503 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7504 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7505 ok(count == 2, "Expected count == 2, got %d\n", count);
7506 ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
7507 ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
7508 ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
7509 "Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
7510 ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
7511 ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
7512 LocalFree(access2);
7513 LocalFree(new_acl);
7515 access.grfAccessMode = REVOKE_ACCESS;
7516 access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
7517 access.Trustee.ptstrName = users_sid;
7518 res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
7519 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
7520 ok(new_acl != NULL, "returned acl was NULL\n");
7522 access2 = (void *)0xdeadbeef;
7523 res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
7524 ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
7525 ok(count == 0, "Expected count == 0, got %d\n", count);
7526 ok(access2 == NULL, "access2 was not NULL\n");
7527 LocalFree(new_acl);
7529 FreeSid(users_sid);
7530 FreeSid(everyone_sid);
7531 HeapFree(GetProcessHeap(), 0, old_acl);
7534 static void test_BuildSecurityDescriptorW(void)
7536 SECURITY_DESCRIPTOR old_sd, *new_sd, *rel_sd;
7537 ULONG new_sd_size;
7538 DWORD buf_size;
7539 char buf[1024];
7540 BOOL success;
7541 DWORD ret;
7543 InitializeSecurityDescriptor(&old_sd, SECURITY_DESCRIPTOR_REVISION);
7545 buf_size = sizeof(buf);
7546 rel_sd = (SECURITY_DESCRIPTOR *)buf;
7547 success = MakeSelfRelativeSD(&old_sd, rel_sd, &buf_size);
7548 ok(success, "MakeSelfRelativeSD failed with %u\n", GetLastError());
7550 new_sd = NULL;
7551 new_sd_size = 0;
7552 ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, NULL, &new_sd_size, (void **)&new_sd);
7553 ok(ret == ERROR_SUCCESS, "BuildSecurityDescriptor failed with %u\n", ret);
7554 ok(new_sd != NULL, "expected new_sd != NULL\n");
7555 LocalFree(new_sd);
7557 new_sd = (void *)0xdeadbeef;
7558 ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, &old_sd, &new_sd_size, (void **)&new_sd);
7559 ok(ret == ERROR_INVALID_SECURITY_DESCR, "expected ERROR_INVALID_SECURITY_DESCR, got %u\n", ret);
7560 ok(new_sd == (void *)0xdeadbeef, "expected new_sd == 0xdeadbeef, got %p\n", new_sd);
7562 new_sd = NULL;
7563 new_sd_size = 0;
7564 ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, rel_sd, &new_sd_size, (void **)&new_sd);
7565 ok(ret == ERROR_SUCCESS, "BuildSecurityDescriptor failed with %u\n", ret);
7566 ok(new_sd != NULL, "expected new_sd != NULL\n");
7567 LocalFree(new_sd);
7570 START_TEST(security)
7572 init();
7573 if (!hmod) return;
7575 if (myARGC >= 3)
7577 if (!strcmp(myARGV[2], "test_token_sd"))
7578 test_child_token_sd();
7579 else
7580 test_process_security_child();
7581 return;
7583 test_kernel_objects_security();
7584 test_sid();
7585 test_trustee();
7586 test_luid();
7587 test_CreateWellKnownSid();
7588 test_FileSecurity();
7589 test_AccessCheck();
7590 test_token_attr();
7591 test_GetTokenInformation();
7592 test_LookupAccountSid();
7593 test_LookupAccountName();
7594 test_security_descriptor();
7595 test_process_security();
7596 test_impersonation_level();
7597 test_SetEntriesInAclW();
7598 test_SetEntriesInAclA();
7599 test_CreateDirectoryA();
7600 test_GetNamedSecurityInfoA();
7601 test_ConvertStringSecurityDescriptor();
7602 test_ConvertSecurityDescriptorToString();
7603 test_PrivateObjectSecurity();
7604 test_acls();
7605 test_GetWindowsAccountDomainSid();
7606 test_GetSecurityInfo();
7607 test_GetSidSubAuthority();
7608 test_CheckTokenMembership();
7609 test_EqualSid();
7610 test_GetUserNameA();
7611 test_GetUserNameW();
7612 test_CreateRestrictedToken();
7613 test_TokenIntegrityLevel();
7614 test_default_dacl_owner_sid();
7615 test_AdjustTokenPrivileges();
7616 test_AddAce();
7617 test_AddMandatoryAce();
7618 test_system_security_access();
7619 test_GetSidIdentifierAuthority();
7620 test_pseudo_tokens();
7621 test_maximum_allowed();
7622 test_token_label();
7623 test_GetExplicitEntriesFromAclW();
7624 test_BuildSecurityDescriptorW();
7626 /* Must be the last test, modifies process token */
7627 test_token_security_descriptor();