029568c50a04406f420fd1c00220c7b449c93ff3
[reactos.git] / rostests / winetests / advapi32 / security.c
1 /*
2 * Unit tests for security functions
3 *
4 * Copyright (c) 2004 Mike McCormack
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 */
20
21 #include <stdarg.h>
22 #include <stdio.h>
23
24 #include "ntstatus.h"
25 #define WIN32_NO_STATUS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winerror.h"
29 #include "aclapi.h"
30 #include "winnt.h"
31 #include "sddl.h"
32 #include "ntsecapi.h"
33 #include "lmcons.h"
34
35 #include "wine/test.h"
36
37 /* copied from Wine winternl.h - not included in the Windows SDK */
38 typedef enum _OBJECT_INFORMATION_CLASS {
39 ObjectBasicInformation,
40 ObjectNameInformation,
41 ObjectTypeInformation,
42 ObjectAllInformation,
43 ObjectDataInformation
44 } OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;
45
46 typedef struct _OBJECT_BASIC_INFORMATION {
47 ULONG Attributes;
48 ACCESS_MASK GrantedAccess;
49 ULONG HandleCount;
50 ULONG PointerCount;
51 ULONG PagedPoolUsage;
52 ULONG NonPagedPoolUsage;
53 ULONG Reserved[3];
54 ULONG NameInformationLength;
55 ULONG TypeInformationLength;
56 ULONG SecurityDescriptorLength;
57 LARGE_INTEGER CreateTime;
58 } OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;
59
60 #define expect_eq(expr, value, type, format) { type ret = expr; ok((value) == ret, #expr " expected " format " got " format "\n", (value), (ret)); }
61
62 static BOOL (WINAPI *pAddAccessAllowedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
63 static BOOL (WINAPI *pAddAccessDeniedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
64 static BOOL (WINAPI *pAddAuditAccessAceEx)(PACL, DWORD, DWORD, DWORD, PSID, BOOL, BOOL);
65 typedef VOID (WINAPI *fnBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
66 typedef VOID (WINAPI *fnBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
67 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
68 POBJECTS_AND_NAME_A pObjName,
69 SE_OBJECT_TYPE ObjectType,
70 LPSTR ObjectTypeName,
71 LPSTR InheritedObjectTypeName,
72 LPSTR Name );
73 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
74 POBJECTS_AND_SID pObjSid,
75 GUID* pObjectGuid,
76 GUID* pInheritedObjectGuid,
77 PSID pSid );
78 typedef LPSTR (WINAPI *fnGetTrusteeNameA)( PTRUSTEEA pTrustee );
79 typedef BOOL (WINAPI *fnMakeSelfRelativeSD)( PSECURITY_DESCRIPTOR, PSECURITY_DESCRIPTOR, LPDWORD );
80 typedef BOOL (WINAPI *fnConvertSidToStringSidA)( PSID pSid, LPSTR *str );
81 typedef BOOL (WINAPI *fnConvertStringSidToSidA)( LPCSTR str, PSID pSid );
82 static BOOL (WINAPI *pCheckTokenMembership)(HANDLE, PSID, PBOOL);
83 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
84 PSECURITY_DESCRIPTOR*, PULONG );
85 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorW)(LPCWSTR, DWORD,
86 PSECURITY_DESCRIPTOR*, PULONG );
87 static BOOL (WINAPI *pConvertSecurityDescriptorToStringSecurityDescriptorA)(PSECURITY_DESCRIPTOR, DWORD,
88 SECURITY_INFORMATION, LPSTR *, PULONG );
89 typedef BOOL (WINAPI *fnGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
90 PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
91 typedef BOOL (WINAPI *fnSetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
92 PSECURITY_DESCRIPTOR);
93 static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
94 PSID*, PSID*, PACL*, PACL*,
95 PSECURITY_DESCRIPTOR*);
96 static PDWORD (WINAPI *pGetSidSubAuthority)(PSID, DWORD);
97 static PUCHAR (WINAPI *pGetSidSubAuthorityCount)(PSID);
98 static BOOL (WINAPI *pIsValidSid)(PSID);
99 typedef DWORD (WINAPI *fnRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
100 typedef BOOL (WINAPI *fnCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
101 typedef BOOL (WINAPI *fnDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
102 SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
103
104 typedef NTSTATUS (WINAPI *fnLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
105 typedef NTSTATUS (WINAPI *fnLsaClose)(LSA_HANDLE);
106 typedef NTSTATUS (WINAPI *fnLsaFreeMemory)(PVOID);
107 typedef NTSTATUS (WINAPI *fnLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
108 static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
109 static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
110 static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
111 SECURITY_DESCRIPTOR_CONTROL);
112 static DWORD (WINAPI *pGetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
113 PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
114 static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
115 PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
116
117 static HMODULE hmod;
118 static int myARGC;
119 static char** myARGV;
120
121 fnBuildTrusteeWithSidA pBuildTrusteeWithSidA;
122 fnBuildTrusteeWithNameA pBuildTrusteeWithNameA;
123 fnBuildTrusteeWithObjectsAndNameA pBuildTrusteeWithObjectsAndNameA;
124 fnBuildTrusteeWithObjectsAndSidA pBuildTrusteeWithObjectsAndSidA;
125 fnGetTrusteeNameA pGetTrusteeNameA;
126 fnMakeSelfRelativeSD pMakeSelfRelativeSD;
127 fnConvertSidToStringSidA pConvertSidToStringSidA;
128 fnConvertStringSidToSidA pConvertStringSidToSidA;
129 fnGetFileSecurityA pGetFileSecurityA;
130 fnSetFileSecurityA pSetFileSecurityA;
131 fnRtlAdjustPrivilege pRtlAdjustPrivilege;
132 fnCreateWellKnownSid pCreateWellKnownSid;
133 fnDuplicateTokenEx pDuplicateTokenEx;
134 fnLsaQueryInformationPolicy pLsaQueryInformationPolicy;
135 fnLsaClose pLsaClose;
136 fnLsaFreeMemory pLsaFreeMemory;
137 fnLsaOpenPolicy pLsaOpenPolicy;
138
139 struct sidRef
140 {
141 SID_IDENTIFIER_AUTHORITY auth;
142 const char *refStr;
143 };
144
145 static void init(void)
146 {
147 HMODULE hntdll;
148
149 hntdll = GetModuleHandleA("ntdll.dll");
150 pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
151 pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
152
153 hmod = GetModuleHandle("advapi32.dll");
154 pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
155 pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
156 pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
157 pCheckTokenMembership = (void *)GetProcAddress(hmod, "CheckTokenMembership");
158 pConvertStringSecurityDescriptorToSecurityDescriptorA =
159 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
160 pConvertStringSecurityDescriptorToSecurityDescriptorW =
161 (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
162 pConvertSecurityDescriptorToStringSecurityDescriptorA =
163 (void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
164 pGetFileSecurityA = (fnGetFileSecurityA)GetProcAddress(hmod, "GetFileSecurityA" );
165 pSetFileSecurityA = (fnSetFileSecurityA)GetProcAddress(hmod, "SetFileSecurityA" );
166 pCreateWellKnownSid = (fnCreateWellKnownSid)GetProcAddress( hmod, "CreateWellKnownSid" );
167 pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
168 pGetSidSubAuthority = (void *)GetProcAddress(hmod, "GetSidSubAuthority");
169 pGetSidSubAuthorityCount = (void *)GetProcAddress(hmod, "GetSidSubAuthorityCount");
170 pIsValidSid = (void *)GetProcAddress(hmod, "IsValidSid");
171 pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
172 pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
173 pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
174 pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
175
176 myARGC = winetest_get_mainargs( &myARGV );
177 }
178
179 static void test_str_sid(const char *str_sid)
180 {
181 PSID psid;
182 char *temp;
183
184 if (pConvertStringSidToSidA(str_sid, &psid))
185 {
186 if (pConvertSidToStringSidA(psid, &temp))
187 {
188 trace(" %s: %s\n", str_sid, temp);
189 LocalFree(temp);
190 }
191 LocalFree(psid);
192 }
193 else
194 {
195 if (GetLastError() != ERROR_INVALID_SID)
196 trace(" %s: couldn't be converted, returned %d\n", str_sid, GetLastError());
197 else
198 trace(" %s: couldn't be converted\n", str_sid);
199 }
200 }
201
202 static void test_sid(void)
203 {
204 struct sidRef refs[] = {
205 { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
206 { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
207 { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
208 { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
209 { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
210 { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
211 };
212 const char noSubAuthStr[] = "S-1-5";
213 unsigned int i;
214 PSID psid = NULL;
215 SID *pisid;
216 BOOL r;
217 LPSTR str = NULL;
218
219 pConvertSidToStringSidA = (fnConvertSidToStringSidA)
220 GetProcAddress( hmod, "ConvertSidToStringSidA" );
221 if( !pConvertSidToStringSidA )
222 return;
223 pConvertStringSidToSidA = (fnConvertStringSidToSidA)
224 GetProcAddress( hmod, "ConvertStringSidToSidA" );
225 if( !pConvertStringSidToSidA )
226 return;
227
228 r = pConvertStringSidToSidA( NULL, NULL );
229 ok( !r, "expected failure with NULL parameters\n" );
230 if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
231 return;
232 ok( GetLastError() == ERROR_INVALID_PARAMETER,
233 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
234 GetLastError() );
235
236 r = pConvertStringSidToSidA( refs[0].refStr, NULL );
237 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
238 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
239 GetLastError() );
240
241 r = pConvertStringSidToSidA( NULL, &str );
242 ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
243 "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
244 GetLastError() );
245
246 r = pConvertStringSidToSidA( noSubAuthStr, &psid );
247 ok( !r,
248 "expected failure with no sub authorities\n" );
249 ok( GetLastError() == ERROR_INVALID_SID,
250 "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
251 GetLastError() );
252
253 ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
254 pisid = psid;
255 ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
256 ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expceted 21, got %d\n", pisid->SubAuthority[0]);
257 ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expceted 4576, got %d\n", pisid->SubAuthority[3]);
258 LocalFree(str);
259 LocalFree(psid);
260
261 for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
262 {
263 PISID pisid;
264
265 r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
266 &psid );
267 ok( r, "failed to allocate sid\n" );
268 r = pConvertSidToStringSidA( psid, &str );
269 ok( r, "failed to convert sid\n" );
270 if (r)
271 {
272 ok( !strcmp( str, refs[i].refStr ),
273 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
274 LocalFree( str );
275 }
276 if( psid )
277 FreeSid( psid );
278
279 r = pConvertStringSidToSidA( refs[i].refStr, &psid );
280 ok( r, "failed to parse sid string\n" );
281 pisid = psid;
282 ok( pisid &&
283 !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
284 sizeof(refs[i].auth) ),
285 "string sid %s didn't parse to expected value\n"
286 "(got 0x%04x%08x, expected 0x%04x%08x)\n",
287 refs[i].refStr,
288 MAKEWORD( pisid->IdentifierAuthority.Value[1],
289 pisid->IdentifierAuthority.Value[0] ),
290 MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
291 pisid->IdentifierAuthority.Value[4] ),
292 MAKEWORD( pisid->IdentifierAuthority.Value[3],
293 pisid->IdentifierAuthority.Value[2] ) ),
294 MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
295 MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
296 MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
297 if( psid )
298 LocalFree( psid );
299 }
300
301 trace("String SIDs:\n");
302 test_str_sid("AO");
303 test_str_sid("RU");
304 test_str_sid("AN");
305 test_str_sid("AU");
306 test_str_sid("BA");
307 test_str_sid("BG");
308 test_str_sid("BO");
309 test_str_sid("BU");
310 test_str_sid("CA");
311 test_str_sid("CG");
312 test_str_sid("CO");
313 test_str_sid("DA");
314 test_str_sid("DC");
315 test_str_sid("DD");
316 test_str_sid("DG");
317 test_str_sid("DU");
318 test_str_sid("EA");
319 test_str_sid("ED");
320 test_str_sid("WD");
321 test_str_sid("PA");
322 test_str_sid("IU");
323 test_str_sid("LA");
324 test_str_sid("LG");
325 test_str_sid("LS");
326 test_str_sid("SY");
327 test_str_sid("NU");
328 test_str_sid("NO");
329 test_str_sid("NS");
330 test_str_sid("PO");
331 test_str_sid("PS");
332 test_str_sid("PU");
333 test_str_sid("RS");
334 test_str_sid("RD");
335 test_str_sid("RE");
336 test_str_sid("RC");
337 test_str_sid("SA");
338 test_str_sid("SO");
339 test_str_sid("SU");
340 }
341
342 static void test_trustee(void)
343 {
344 GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
345 GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
346 GUID ZeroGuid;
347 OBJECTS_AND_NAME_ oan;
348 OBJECTS_AND_SID oas;
349 TRUSTEE trustee;
350 PSID psid;
351 char szObjectTypeName[] = "ObjectTypeName";
352 char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
353 char szTrusteeName[] = "szTrusteeName";
354 SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
355
356 memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
357
358 pBuildTrusteeWithSidA = (fnBuildTrusteeWithSidA)
359 GetProcAddress( hmod, "BuildTrusteeWithSidA" );
360 pBuildTrusteeWithNameA = (fnBuildTrusteeWithNameA)
361 GetProcAddress( hmod, "BuildTrusteeWithNameA" );
362 pBuildTrusteeWithObjectsAndNameA = (fnBuildTrusteeWithObjectsAndNameA)
363 GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
364 pBuildTrusteeWithObjectsAndSidA = (fnBuildTrusteeWithObjectsAndSidA)
365 GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
366 pGetTrusteeNameA = (fnGetTrusteeNameA)
367 GetProcAddress (hmod, "GetTrusteeNameA" );
368 if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
369 !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
370 !pGetTrusteeNameA )
371 return;
372
373 if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
374 {
375 trace( "failed to init SID\n" );
376 return;
377 }
378
379 /* test BuildTrusteeWithSidA */
380 memset( &trustee, 0xff, sizeof trustee );
381 pBuildTrusteeWithSidA( &trustee, psid );
382
383 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
384 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
385 "MultipleTrusteeOperation wrong\n");
386 ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
387 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
388 ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
389
390 /* test BuildTrusteeWithObjectsAndSidA (test 1) */
391 memset( &trustee, 0xff, sizeof trustee );
392 memset( &oas, 0xff, sizeof(oas) );
393 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
394 &InheritedObjectType, psid);
395
396 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
397 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
398 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
399 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
400 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
401
402 ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
403 ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
404 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
405 ok(oas.pSid == psid, "pSid wrong\n");
406
407 /* test GetTrusteeNameA */
408 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
409
410 /* test BuildTrusteeWithObjectsAndSidA (test 2) */
411 memset( &trustee, 0xff, sizeof trustee );
412 memset( &oas, 0xff, sizeof(oas) );
413 pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
414 &InheritedObjectType, psid);
415
416 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
417 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
418 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
419 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
420 ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
421
422 ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
423 ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
424 ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
425 ok(oas.pSid == psid, "pSid wrong\n");
426
427 FreeSid( psid );
428
429 /* test BuildTrusteeWithNameA */
430 memset( &trustee, 0xff, sizeof trustee );
431 pBuildTrusteeWithNameA( &trustee, szTrusteeName );
432
433 ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
434 ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
435 "MultipleTrusteeOperation wrong\n");
436 ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
437 ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
438 ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
439
440 /* test BuildTrusteeWithObjectsAndNameA (test 1) */
441 memset( &trustee, 0xff, sizeof trustee );
442 memset( &oan, 0xff, sizeof(oan) );
443 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
444 szInheritedObjectTypeName, szTrusteeName);
445
446 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
447 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
448 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
449 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
450 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
451
452 ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
453 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
454 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
455 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
456
457 /* test GetTrusteeNameA */
458 ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
459
460 /* test BuildTrusteeWithObjectsAndNameA (test 2) */
461 memset( &trustee, 0xff, sizeof trustee );
462 memset( &oan, 0xff, sizeof(oan) );
463 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
464 szInheritedObjectTypeName, szTrusteeName);
465
466 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
467 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
468 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
469 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
470 ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
471
472 ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
473 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
474 ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
475 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
476
477 /* test BuildTrusteeWithObjectsAndNameA (test 3) */
478 memset( &trustee, 0xff, sizeof trustee );
479 memset( &oan, 0xff, sizeof(oan) );
480 pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
481 NULL, szTrusteeName);
482
483 ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
484 ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
485 ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
486 ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
487 ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
488
489 ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
490 ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
491 ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
492 ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
493 }
494
495 /* If the first isn't defined, assume none is */
496 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
497 #define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
498 #define SE_CREATE_TOKEN_PRIVILEGE 2L
499 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
500 #define SE_LOCK_MEMORY_PRIVILEGE 4L
501 #define SE_INCREASE_QUOTA_PRIVILEGE 5L
502 #define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
503 #define SE_TCB_PRIVILEGE 7L
504 #define SE_SECURITY_PRIVILEGE 8L
505 #define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
506 #define SE_LOAD_DRIVER_PRIVILEGE 10L
507 #define SE_SYSTEM_PROFILE_PRIVILEGE 11L
508 #define SE_SYSTEMTIME_PRIVILEGE 12L
509 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
510 #define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
511 #define SE_CREATE_PAGEFILE_PRIVILEGE 15L
512 #define SE_CREATE_PERMANENT_PRIVILEGE 16L
513 #define SE_BACKUP_PRIVILEGE 17L
514 #define SE_RESTORE_PRIVILEGE 18L
515 #define SE_SHUTDOWN_PRIVILEGE 19L
516 #define SE_DEBUG_PRIVILEGE 20L
517 #define SE_AUDIT_PRIVILEGE 21L
518 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
519 #define SE_CHANGE_NOTIFY_PRIVILEGE 23L
520 #define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
521 #define SE_UNDOCK_PRIVILEGE 25L
522 #define SE_SYNC_AGENT_PRIVILEGE 26L
523 #define SE_ENABLE_DELEGATION_PRIVILEGE 27L
524 #define SE_MANAGE_VOLUME_PRIVILEGE 28L
525 #define SE_IMPERSONATE_PRIVILEGE 29L
526 #define SE_CREATE_GLOBAL_PRIVILEGE 30L
527 #define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
528 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
529
530 static void test_allocateLuid(void)
531 {
532 BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
533 LUID luid1, luid2;
534 BOOL ret;
535
536 pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
537 if (!pAllocateLocallyUniqueId) return;
538
539 ret = pAllocateLocallyUniqueId(&luid1);
540 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
541 return;
542
543 ok(ret,
544 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
545 ret = pAllocateLocallyUniqueId(&luid2);
546 ok( ret,
547 "AllocateLocallyUniqueId failed: %d\n", GetLastError());
548 ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
549 "AllocateLocallyUniqueId returned a well-known LUID\n");
550 ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
551 "AllocateLocallyUniqueId returned non-unique LUIDs\n");
552 ret = pAllocateLocallyUniqueId(NULL);
553 ok( !ret && GetLastError() == ERROR_NOACCESS,
554 "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
555 GetLastError());
556 }
557
558 static void test_lookupPrivilegeName(void)
559 {
560 BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
561 char buf[MAX_PATH]; /* arbitrary, seems long enough */
562 DWORD cchName = sizeof(buf);
563 LUID luid = { 0, 0 };
564 LONG i;
565 BOOL ret;
566
567 /* check whether it's available first */
568 pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
569 if (!pLookupPrivilegeNameA) return;
570 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
571 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
572 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
573 return;
574
575 /* check with a short buffer */
576 cchName = 0;
577 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
578 ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
579 ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
580 "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
581 GetLastError());
582 ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
583 "LookupPrivilegeNameA returned an incorrect required length for\n"
584 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
585 lstrlenA("SeCreateTokenPrivilege") + 1);
586 /* check a known value and its returned length on success */
587 cchName = sizeof(buf);
588 ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
589 cchName == strlen("SeCreateTokenPrivilege"),
590 "LookupPrivilegeNameA returned an incorrect output length for\n"
591 "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
592 (int)strlen("SeCreateTokenPrivilege"));
593 /* check known values */
594 for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
595 {
596 luid.LowPart = i;
597 cchName = sizeof(buf);
598 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
599 ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
600 "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
601 }
602 /* check a bogus LUID */
603 luid.LowPart = 0xdeadbeef;
604 cchName = sizeof(buf);
605 ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
606 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
607 "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
608 GetLastError());
609 /* check on a bogus system */
610 luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
611 cchName = sizeof(buf);
612 ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
613 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
614 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
615 "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
616 GetLastError());
617 }
618
619 struct NameToLUID
620 {
621 const char *name;
622 DWORD lowPart;
623 };
624
625 static void test_lookupPrivilegeValue(void)
626 {
627 static const struct NameToLUID privs[] = {
628 { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
629 { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
630 { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
631 { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
632 { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
633 { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
634 { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
635 { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
636 { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
637 { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
638 { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
639 { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
640 { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
641 { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
642 { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
643 { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
644 { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
645 { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
646 { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
647 { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
648 { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
649 { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
650 { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
651 { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
652 { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
653 { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
654 { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
655 { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
656 { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
657 };
658 BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
659 int i;
660 LUID luid;
661 BOOL ret;
662
663 /* check whether it's available first */
664 pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
665 if (!pLookupPrivilegeValueA) return;
666 ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
667 if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
668 return;
669
670 /* check a bogus system name */
671 ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
672 ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
673 GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
674 "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
675 GetLastError());
676 /* check a NULL string */
677 ret = pLookupPrivilegeValueA(NULL, 0, &luid);
678 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
679 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
680 GetLastError());
681 /* check a bogus privilege name */
682 ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
683 ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
684 "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
685 GetLastError());
686 /* check case insensitive */
687 ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
688 ok( ret,
689 "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
690 GetLastError());
691 for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
692 {
693 /* Not all privileges are implemented on all Windows versions, so
694 * don't worry if the call fails
695 */
696 if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
697 {
698 ok(luid.LowPart == privs[i].lowPart,
699 "LookupPrivilegeValueA returned an invalid LUID for %s\n",
700 privs[i].name);
701 }
702 }
703 }
704
705 static void test_luid(void)
706 {
707 test_allocateLuid();
708 test_lookupPrivilegeName();
709 test_lookupPrivilegeValue();
710 }
711
712 static void test_FileSecurity(void)
713 {
714 char wintmpdir [MAX_PATH];
715 char path [MAX_PATH];
716 char file [MAX_PATH];
717 BOOL rc;
718 HANDLE fh;
719 DWORD sdSize;
720 DWORD retSize;
721 BYTE *sd;
722 SECURITY_INFORMATION const request = OWNER_SECURITY_INFORMATION
723 | GROUP_SECURITY_INFORMATION
724 | DACL_SECURITY_INFORMATION;
725
726 if (!pGetFileSecurityA) {
727 win_skip ("GetFileSecurity is not available\n");
728 return;
729 }
730
731 if (!pSetFileSecurityA) {
732 win_skip ("SetFileSecurity is not available\n");
733 return;
734 }
735
736 if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
737 win_skip ("GetTempPathA failed\n");
738 return;
739 }
740
741 /* Create a temporary directory and in it a temporary file */
742 strcat (strcpy (path, wintmpdir), "rary");
743 SetLastError(0xdeadbeef);
744 rc = CreateDirectoryA (path, NULL);
745 ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
746 "failed for '%s' with %d\n", path, GetLastError());
747
748 strcat (strcpy (file, path), "\\ess");
749 SetLastError(0xdeadbeef);
750 fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
751 ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
752 "failed for '%s' with %d\n", file, GetLastError());
753 CloseHandle (fh);
754
755 /* For the temporary file ... */
756
757 /* Get size needed */
758 retSize = 0;
759 SetLastError(0xdeadbeef);
760 rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
761 if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
762 win_skip("GetFileSecurityA is not implemented\n");
763 goto cleanup;
764 }
765 ok (!rc, "GetFileSecurityA "
766 "was expected to fail for '%s'\n", file);
767 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
768 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
769 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
770
771 sdSize = retSize;
772 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
773
774 /* Get security descriptor for real */
775 retSize = -1;
776 SetLastError(0xdeadbeef);
777 rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
778 ok (rc, "GetFileSecurityA "
779 "was not expected to fail '%s': %d\n", file, GetLastError());
780 ok (retSize == sdSize ||
781 broken(retSize == 0), /* NT4 */
782 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
783
784 /* Use it to set security descriptor */
785 SetLastError(0xdeadbeef);
786 rc = pSetFileSecurityA (file, request, sd);
787 ok (rc, "SetFileSecurityA "
788 "was not expected to fail '%s': %d\n", file, GetLastError());
789
790 HeapFree (GetProcessHeap (), 0, sd);
791
792 /* Repeat for the temporary directory ... */
793
794 /* Get size needed */
795 retSize = 0;
796 SetLastError(0xdeadbeef);
797 rc = pGetFileSecurityA (path, request, NULL, 0, &retSize);
798 ok (!rc, "GetFileSecurityA "
799 "was expected to fail for '%s'\n", path);
800 ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
801 "returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
802 ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
803
804 sdSize = retSize;
805 sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
806
807 /* Get security descriptor for real */
808 retSize = -1;
809 SetLastError(0xdeadbeef);
810 rc = pGetFileSecurityA (path, request, sd, sdSize, &retSize);
811 ok (rc, "GetFileSecurityA "
812 "was not expected to fail '%s': %d\n", path, GetLastError());
813 ok (retSize == sdSize ||
814 broken(retSize == 0), /* NT4 */
815 "GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
816
817 /* Use it to set security descriptor */
818 SetLastError(0xdeadbeef);
819 rc = pSetFileSecurityA (path, request, sd);
820 ok (rc, "SetFileSecurityA "
821 "was not expected to fail '%s': %d\n", path, GetLastError());
822 HeapFree (GetProcessHeap (), 0, sd);
823
824 /* Old test */
825 strcpy (wintmpdir, "\\Should not exist");
826 SetLastError(0xdeadbeef);
827 rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
828 ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
829 ok (GetLastError() == ERROR_FILE_NOT_FOUND,
830 "last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());
831
832 cleanup:
833 /* Remove temporary file and directory */
834 DeleteFileA(file);
835 RemoveDirectoryA(path);
836 }
837
838 static void test_AccessCheck(void)
839 {
840 PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
841 PACL Acl = NULL;
842 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
843 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
844 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
845 GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
846 ACCESS_MASK Access;
847 BOOL AccessStatus;
848 HANDLE Token;
849 HANDLE ProcessToken;
850 BOOL ret;
851 DWORD PrivSetLen;
852 PRIVILEGE_SET *PrivSet;
853 BOOL res;
854 HMODULE NtDllModule;
855 BOOLEAN Enabled;
856 DWORD err;
857 NTSTATUS ntret, ntAccessStatus;
858
859 NtDllModule = GetModuleHandle("ntdll.dll");
860 if (!NtDllModule)
861 {
862 skip("not running on NT, skipping test\n");
863 return;
864 }
865 pRtlAdjustPrivilege = (fnRtlAdjustPrivilege)
866 GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
867 if (!pRtlAdjustPrivilege)
868 {
869 win_skip("missing RtlAdjustPrivilege, skipping test\n");
870 return;
871 }
872
873 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
874 res = InitializeAcl(Acl, 256, ACL_REVISION);
875 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
876 {
877 skip("ACLs not implemented - skipping tests\n");
878 HeapFree(GetProcessHeap(), 0, Acl);
879 return;
880 }
881 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
882
883 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
884 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
885
886 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
887 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
888 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
889
890 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
891 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
892 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
893
894 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
895
896 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
897 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
898
899 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
900 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
901
902 PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
903 PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
904 PrivSet->PrivilegeCount = 16;
905
906 res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
907 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
908
909 pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
910
911 res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
912 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
913
914 /* SD without owner/group */
915 SetLastError(0xdeadbeef);
916 Access = AccessStatus = 0xdeadbeef;
917 ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
918 PrivSet, &PrivSetLen, &Access, &AccessStatus);
919 err = GetLastError();
920 ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
921 "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
922 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
923 "Access and/or AccessStatus were changed!\n");
924
925 /* Set owner and group */
926 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
927 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
928 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
929 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
930
931 /* Generic access mask */
932 SetLastError(0xdeadbeef);
933 Access = AccessStatus = 0xdeadbeef;
934 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
935 PrivSet, &PrivSetLen, &Access, &AccessStatus);
936 err = GetLastError();
937 ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
938 "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
939 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
940 "Access and/or AccessStatus were changed!\n");
941
942 /* Generic access mask - no privilegeset buffer */
943 SetLastError(0xdeadbeef);
944 Access = AccessStatus = 0xdeadbeef;
945 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
946 NULL, &PrivSetLen, &Access, &AccessStatus);
947 err = GetLastError();
948 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
949 "with ERROR_NOACCESS, instead of %d\n", err);
950 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
951 "Access and/or AccessStatus were changed!\n");
952
953 /* Generic access mask - no returnlength */
954 SetLastError(0xdeadbeef);
955 Access = AccessStatus = 0xdeadbeef;
956 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
957 PrivSet, NULL, &Access, &AccessStatus);
958 err = GetLastError();
959 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
960 "with ERROR_NOACCESS, instead of %d\n", err);
961 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
962 "Access and/or AccessStatus were changed!\n");
963
964 /* Generic access mask - no privilegeset buffer, no returnlength */
965 SetLastError(0xdeadbeef);
966 Access = AccessStatus = 0xdeadbeef;
967 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
968 NULL, NULL, &Access, &AccessStatus);
969 err = GetLastError();
970 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
971 "with ERROR_NOACCESS, instead of %d\n", err);
972 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
973 "Access and/or AccessStatus were changed!\n");
974
975 /* sd with no dacl present */
976 Access = AccessStatus = 0xdeadbeef;
977 ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
978 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
979 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
980 PrivSet, &PrivSetLen, &Access, &AccessStatus);
981 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
982 ok(AccessStatus && (Access == KEY_READ),
983 "AccessCheck failed to grant access with error %d\n",
984 GetLastError());
985
986 /* sd with no dacl present - no privilegeset buffer */
987 SetLastError(0xdeadbeef);
988 Access = AccessStatus = 0xdeadbeef;
989 ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
990 NULL, &PrivSetLen, &Access, &AccessStatus);
991 err = GetLastError();
992 ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
993 "with ERROR_NOACCESS, instead of %d\n", err);
994 ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
995 "Access and/or AccessStatus were changed!\n");
996
997 if(pNtAccessCheck)
998 {
999 /* Generic access mask - no privilegeset buffer */
1000 SetLastError(0xdeadbeef);
1001 Access = ntAccessStatus = 0xdeadbeef;
1002 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1003 NULL, &PrivSetLen, &Access, &ntAccessStatus);
1004 err = GetLastError();
1005 ok(ntret == STATUS_ACCESS_VIOLATION,
1006 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1007 ok(err == 0xdeadbeef,
1008 "NtAccessCheck shouldn't set last error, got %d\n", err);
1009 ok(Access == 0xdeadbeef && ntAccessStatus == 0xdeadbeef,
1010 "Access and/or AccessStatus were changed!\n");
1011
1012 /* Generic access mask - no returnlength */
1013 SetLastError(0xdeadbeef);
1014 Access = ntAccessStatus = 0xdeadbeef;
1015 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1016 PrivSet, NULL, &Access, &ntAccessStatus);
1017 err = GetLastError();
1018 ok(ntret == STATUS_ACCESS_VIOLATION,
1019 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1020 ok(err == 0xdeadbeef,
1021 "NtAccessCheck shouldn't set last error, got %d\n", err);
1022 ok(Access == 0xdeadbeef && ntAccessStatus == 0xdeadbeef,
1023 "Access and/or AccessStatus were changed!\n");
1024
1025 /* Generic access mask - no privilegeset buffer, no returnlength */
1026 SetLastError(0xdeadbeef);
1027 Access = ntAccessStatus = 0xdeadbeef;
1028 ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
1029 NULL, NULL, &Access, &ntAccessStatus);
1030 err = GetLastError();
1031 ok(ntret == STATUS_ACCESS_VIOLATION,
1032 "NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
1033 ok(err == 0xdeadbeef,
1034 "NtAccessCheck shouldn't set last error, got %d\n", err);
1035 ok(Access == 0xdeadbeef && ntAccessStatus == 0xdeadbeef,
1036 "Access and/or AccessStatus were changed!\n");
1037 }
1038 else
1039 win_skip("NtAccessCheck unavailable. Skipping.\n");
1040
1041 /* sd with NULL dacl */
1042 Access = AccessStatus = 0xdeadbeef;
1043 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
1044 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1045 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1046 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1047 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1048 ok(AccessStatus && (Access == KEY_READ),
1049 "AccessCheck failed to grant access with error %d\n",
1050 GetLastError());
1051
1052 /* sd with blank dacl */
1053 ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1054 ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1055 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1056 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1057 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1058 err = GetLastError();
1059 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1060 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1061 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1062
1063 res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
1064 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
1065
1066 res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
1067 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1068
1069 /* sd with dacl */
1070 Access = AccessStatus = 0xdeadbeef;
1071 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1072 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1073 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1074 ok(AccessStatus && (Access == KEY_READ),
1075 "AccessCheck failed to grant access with error %d\n",
1076 GetLastError());
1077
1078 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1079 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1080 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1081 ok(AccessStatus,
1082 "AccessCheck failed to grant any access with error %d\n",
1083 GetLastError());
1084 trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
1085
1086 /* Access denied by SD */
1087 SetLastError(0xdeadbeef);
1088 Access = AccessStatus = 0xdeadbeef;
1089 ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
1090 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1091 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1092 err = GetLastError();
1093 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1094 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1095 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1096
1097 SetLastError(0);
1098 PrivSet->PrivilegeCount = 16;
1099 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1100 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1101 ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
1102 "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
1103 GetLastError());
1104
1105 ret = ImpersonateLoggedOnUser(Token);
1106 ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
1107 ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
1108 if (!ret)
1109 {
1110 SetLastError(0);
1111 PrivSet->PrivilegeCount = 16;
1112 ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
1113 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1114 ok(ret && AccessStatus && GetLastError() == 0,
1115 "AccessCheck should have succeeded, error %d\n",
1116 GetLastError());
1117 ok(Access == ACCESS_SYSTEM_SECURITY,
1118 "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
1119 Access);
1120 }
1121 else
1122 trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
1123 ret);
1124 ret = RevertToSelf();
1125 ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1126
1127 /* test INHERIT_ONLY_ACE */
1128 ret = InitializeAcl(Acl, 256, ACL_REVISION);
1129 ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
1130
1131 /* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
1132 * the next ones.
1133 */
1134 if (pAddAccessAllowedAceEx)
1135 {
1136 ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
1137 ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1138 }
1139 else
1140 win_skip("AddAccessAllowedAceEx is not available\n");
1141
1142 ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
1143 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1144 ok(ret, "AccessCheck failed with error %d\n", GetLastError());
1145 err = GetLastError();
1146 ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
1147 "with ERROR_ACCESS_DENIED, instead of %d\n", err);
1148 ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
1149
1150 CloseHandle(Token);
1151
1152 res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
1153 ok(res, "DuplicateToken failed with error %d\n", GetLastError());
1154
1155 SetLastError(0xdeadbeef);
1156 ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
1157 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1158 err = GetLastError();
1159 ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
1160 "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
1161
1162 CloseHandle(Token);
1163
1164 SetLastError(0xdeadbeef);
1165 ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
1166 PrivSet, &PrivSetLen, &Access, &AccessStatus);
1167 err = GetLastError();
1168 ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
1169 "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
1170
1171 CloseHandle(ProcessToken);
1172
1173 if (EveryoneSid)
1174 FreeSid(EveryoneSid);
1175 if (AdminSid)
1176 FreeSid(AdminSid);
1177 if (UsersSid)
1178 FreeSid(UsersSid);
1179 HeapFree(GetProcessHeap(), 0, Acl);
1180 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1181 HeapFree(GetProcessHeap(), 0, PrivSet);
1182 }
1183
1184 /* test GetTokenInformation for the various attributes */
1185 static void test_token_attr(void)
1186 {
1187 HANDLE Token, ImpersonationToken;
1188 DWORD Size, Size2;
1189 TOKEN_PRIVILEGES *Privileges;
1190 TOKEN_GROUPS *Groups;
1191 TOKEN_USER *User;
1192 TOKEN_DEFAULT_DACL *Dacl;
1193 BOOL ret;
1194 DWORD i, GLE;
1195 LPSTR SidString;
1196 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1197 ACL *acl;
1198
1199 /* cygwin-like use case */
1200 SetLastError(0xdeadbeef);
1201 ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
1202 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1203 {
1204 win_skip("OpenProcessToken is not implemented\n");
1205 return;
1206 }
1207 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1208 if (ret)
1209 {
1210 DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
1211 Size = sizeof(buf);
1212 ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
1213 ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
1214 Size = sizeof(ImpersonationLevel);
1215 ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1216 GLE = GetLastError();
1217 ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
1218 CloseHandle(Token);
1219 }
1220
1221 if(!pConvertSidToStringSidA)
1222 {
1223 win_skip("ConvertSidToStringSidA is not available\n");
1224 return;
1225 }
1226
1227 SetLastError(0xdeadbeef);
1228 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
1229 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1230
1231 /* groups */
1232 SetLastError(0xdeadbeef);
1233 ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
1234 ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1235 "GetTokenInformation(TokenGroups) %s with error %d\n",
1236 ret ? "succeeded" : "failed", GetLastError());
1237 Groups = HeapAlloc(GetProcessHeap(), 0, Size);
1238 SetLastError(0xdeadbeef);
1239 ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
1240 ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
1241 ok(GetLastError() == 0xdeadbeef,
1242 "GetTokenInformation shouldn't have set last error to %d\n",
1243 GetLastError());
1244 trace("TokenGroups:\n");
1245 for (i = 0; i < Groups->GroupCount; i++)
1246 {
1247 DWORD NameLength = 255;
1248 TCHAR Name[255];
1249 DWORD DomainLength = 255;
1250 TCHAR Domain[255];
1251 SID_NAME_USE SidNameUse;
1252 Name[0] = '\0';
1253 Domain[0] = '\0';
1254 ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
1255 if (ret)
1256 {
1257 pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
1258 trace("%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
1259 LocalFree(SidString);
1260 }
1261 else trace("attr: 0x%08x LookupAccountSid failed with error %d\n", Groups->Groups[i].Attributes, GetLastError());
1262 }
1263 HeapFree(GetProcessHeap(), 0, Groups);
1264
1265 /* user */
1266 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1267 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1268 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1269 User = HeapAlloc(GetProcessHeap(), 0, Size);
1270 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1271 ok(ret,
1272 "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1273
1274 pConvertSidToStringSidA(User->User.Sid, &SidString);
1275 trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
1276 LocalFree(SidString);
1277 HeapFree(GetProcessHeap(), 0, User);
1278
1279 /* privileges */
1280 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1281 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1282 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1283 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1284 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1285 ok(ret,
1286 "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1287 trace("TokenPrivileges:\n");
1288 for (i = 0; i < Privileges->PrivilegeCount; i++)
1289 {
1290 TCHAR Name[256];
1291 DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
1292 LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
1293 trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
1294 }
1295 HeapFree(GetProcessHeap(), 0, Privileges);
1296
1297 ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
1298 ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1299
1300 Size = sizeof(ImpersonationLevel);
1301 ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
1302 ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1303 ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
1304
1305 CloseHandle(ImpersonationToken);
1306
1307 /* default dacl */
1308 ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
1309 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
1310 "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1311
1312 Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
1313 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
1314 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1315
1316 SetLastError(0xdeadbeef);
1317 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
1318 GLE = GetLastError();
1319 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1320 ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);
1321
1322 SetLastError(0xdeadbeef);
1323 ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
1324 GLE = GetLastError();
1325 ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1326 ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);
1327
1328 acl = Dacl->DefaultDacl;
1329 Dacl->DefaultDacl = NULL;
1330
1331 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1332 ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
1333
1334 Size2 = 0;
1335 Dacl->DefaultDacl = (ACL *)0xdeadbeef;
1336 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1337 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1338 ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
1339 ok(Size2 == sizeof(TOKEN_DEFAULT_DACL), "got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
1340
1341 Dacl->DefaultDacl = acl;
1342 ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
1343 ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1344
1345 ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
1346 ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
1347
1348 HeapFree(GetProcessHeap(), 0, Dacl);
1349 CloseHandle(Token);
1350 }
1351
1352 typedef union _MAX_SID
1353 {
1354 SID sid;
1355 char max[SECURITY_MAX_SID_SIZE];
1356 } MAX_SID;
1357
1358 static void test_sid_str(PSID * sid)
1359 {
1360 char *str_sid;
1361 BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
1362 ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
1363 if (ret)
1364 {
1365 char account[MAX_PATH], domain[MAX_PATH];
1366 SID_NAME_USE use;
1367 DWORD acc_size = MAX_PATH;
1368 DWORD dom_size = MAX_PATH;
1369 ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
1370 ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
1371 "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
1372 if (ret)
1373 trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
1374 else if (GetLastError() == ERROR_NONE_MAPPED)
1375 trace(" %s couldn't be mapped\n", str_sid);
1376 LocalFree(str_sid);
1377 }
1378 }
1379
1380 struct well_known_sid_value
1381 {
1382 BOOL without_domain;
1383 const char *sid_string;
1384 } well_known_sid_values[] = {
1385 /* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
1386 /* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
1387 /* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
1388 /* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
1389 /* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
1390 /* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
1391 /* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
1392 /* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
1393 /* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
1394 /* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
1395 /* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
1396 /* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
1397 /* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
1398 /* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
1399 /* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
1400 /* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
1401 /* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
1402 /* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
1403 /* Added in Windows Server 2003 */
1404 /* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
1405 /* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
1406 /* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
1407 /* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
1408 /* Added in Windows Vista: */
1409 /* 62 */ {TRUE, "S-1-5-32-568"},
1410 /* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
1411 /* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
1412 /* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
1413 /* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
1414 /* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"}
1415 };
1416
1417 static void test_CreateWellKnownSid(void)
1418 {
1419 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1420 PSID domainsid, sid;
1421 DWORD size, error;
1422 BOOL ret;
1423 int i;
1424
1425 if (!pCreateWellKnownSid)
1426 {
1427 win_skip("CreateWellKnownSid not available\n");
1428 return;
1429 }
1430
1431 size = 0;
1432 SetLastError(0xdeadbeef);
1433 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
1434 error = GetLastError();
1435 ok(!ret, "CreateWellKnownSid succeeded\n");
1436 ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
1437 ok(size, "expected size > 0\n");
1438
1439 SetLastError(0xdeadbeef);
1440 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
1441 error = GetLastError();
1442 ok(!ret, "CreateWellKnownSid succeeded\n");
1443 ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);
1444
1445 sid = HeapAlloc(GetProcessHeap(), 0, size);
1446 ret = pCreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
1447 ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
1448 HeapFree(GetProcessHeap(), 0, sid);
1449
1450 /* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
1451 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
1452
1453 for (i = 0; i < sizeof(well_known_sid_values)/sizeof(well_known_sid_values[0]); i++)
1454 {
1455 struct well_known_sid_value *value = &well_known_sid_values[i];
1456 char sid_buffer[SECURITY_MAX_SID_SIZE];
1457 LPSTR str;
1458 DWORD cb;
1459
1460 if (value->sid_string == NULL)
1461 continue;
1462
1463 if (i > WinAccountRasAndIasServersSid)
1464 {
1465 /* These SIDs aren't implemented by all Windows versions - detect it and break the loop */
1466 cb = sizeof(sid_buffer);
1467 if (!pCreateWellKnownSid(i, domainsid, sid_buffer, &cb))
1468 {
1469 skip("Well known SIDs starting from %d are not implemented\n", i);
1470 break;
1471 }
1472 }
1473
1474 cb = sizeof(sid_buffer);
1475 ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %d\n", i);
1476 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1477 ok(IsValidSid(sid_buffer), "The sid is not valid\n");
1478 ok(pConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
1479 ok(strcmp(str, value->sid_string) == 0, "SID mismatch - expected %s, got %s\n",
1480 value->sid_string, str);
1481 LocalFree(str);
1482
1483 if (value->without_domain)
1484 {
1485 char buf2[SECURITY_MAX_SID_SIZE];
1486 cb = sizeof(buf2);
1487 ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %d with optional domain\n", i);
1488 expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
1489 ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%d)\n", i);
1490 }
1491 }
1492
1493 FreeSid(domainsid);
1494 }
1495
1496 static void test_LookupAccountSid(void)
1497 {
1498 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1499 CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
1500 DWORD acc_sizeA, dom_sizeA, user_sizeA;
1501 DWORD real_acc_sizeA, real_dom_sizeA;
1502 WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
1503 DWORD acc_sizeW, dom_sizeW;
1504 DWORD real_acc_sizeW, real_dom_sizeW;
1505 PSID pUsersSid = NULL;
1506 SID_NAME_USE use;
1507 BOOL ret;
1508 DWORD size,cbti = 0;
1509 MAX_SID max_sid;
1510 CHAR *str_sidA;
1511 int i;
1512 HANDLE hToken;
1513 PTOKEN_USER ptiUser = NULL;
1514
1515 /* native windows crashes if account size, domain size, or name use is NULL */
1516
1517 ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1518 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
1519 ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
1520 "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1521
1522 /* not running on NT so give up */
1523 if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1524 return;
1525
1526 real_acc_sizeA = MAX_PATH;
1527 real_dom_sizeA = MAX_PATH;
1528 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1529 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1530
1531 /* try NULL account */
1532 acc_sizeA = MAX_PATH;
1533 dom_sizeA = MAX_PATH;
1534 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1535 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1536
1537 /* try NULL domain */
1538 acc_sizeA = MAX_PATH;
1539 dom_sizeA = MAX_PATH;
1540 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1541 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1542
1543 /* try a small account buffer */
1544 acc_sizeA = 1;
1545 dom_sizeA = MAX_PATH;
1546 accountA[0] = 0;
1547 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1548 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1549 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1550 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1551
1552 /* try a 0 sized account buffer */
1553 acc_sizeA = 0;
1554 dom_sizeA = MAX_PATH;
1555 accountA[0] = 0;
1556 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1557 /* this can fail or succeed depending on OS version but the size will always be returned */
1558 ok(acc_sizeA == real_acc_sizeA + 1,
1559 "LookupAccountSidA() Expected acc_size = %u, got %u\n",
1560 real_acc_sizeA + 1, acc_sizeA);
1561
1562 /* try a 0 sized account buffer */
1563 acc_sizeA = 0;
1564 dom_sizeA = MAX_PATH;
1565 ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1566 /* this can fail or succeed depending on OS version but the size will always be returned */
1567 ok(acc_sizeA == real_acc_sizeA + 1,
1568 "LookupAccountSid() Expected acc_size = %u, got %u\n",
1569 real_acc_sizeA + 1, acc_sizeA);
1570
1571 /* try a small domain buffer */
1572 dom_sizeA = 1;
1573 acc_sizeA = MAX_PATH;
1574 accountA[0] = 0;
1575 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1576 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1577 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1578 "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1579
1580 /* try a 0 sized domain buffer */
1581 dom_sizeA = 0;
1582 acc_sizeA = MAX_PATH;
1583 accountA[0] = 0;
1584 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1585 /* this can fail or succeed depending on OS version but the size will always be returned */
1586 ok(dom_sizeA == real_dom_sizeA + 1,
1587 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1588 real_dom_sizeA + 1, dom_sizeA);
1589
1590 /* try a 0 sized domain buffer */
1591 dom_sizeA = 0;
1592 acc_sizeA = MAX_PATH;
1593 ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1594 /* this can fail or succeed depending on OS version but the size will always be returned */
1595 ok(dom_sizeA == real_dom_sizeA + 1,
1596 "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1597 real_dom_sizeA + 1, dom_sizeA);
1598
1599 real_acc_sizeW = MAX_PATH;
1600 real_dom_sizeW = MAX_PATH;
1601 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
1602 ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
1603
1604 /* try an invalid system name */
1605 real_acc_sizeA = MAX_PATH;
1606 real_dom_sizeA = MAX_PATH;
1607 ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1608 ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1609 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
1610 "LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
1611
1612 /* native windows crashes if domainW or accountW is NULL */
1613
1614 /* try a small account buffer */
1615 acc_sizeW = 1;
1616 dom_sizeW = MAX_PATH;
1617 accountW[0] = 0;
1618 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1619 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1620 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1621 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1622
1623 /* try a 0 sized account buffer */
1624 acc_sizeW = 0;
1625 dom_sizeW = MAX_PATH;
1626 accountW[0] = 0;
1627 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1628 /* this can fail or succeed depending on OS version but the size will always be returned */
1629 ok(acc_sizeW == real_acc_sizeW + 1,
1630 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1631 real_acc_sizeW + 1, acc_sizeW);
1632
1633 /* try a 0 sized account buffer */
1634 acc_sizeW = 0;
1635 dom_sizeW = MAX_PATH;
1636 ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1637 /* this can fail or succeed depending on OS version but the size will always be returned */
1638 ok(acc_sizeW == real_acc_sizeW + 1,
1639 "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1640 real_acc_sizeW + 1, acc_sizeW);
1641
1642 /* try a small domain buffer */
1643 dom_sizeW = 1;
1644 acc_sizeW = MAX_PATH;
1645 accountW[0] = 0;
1646 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1647 ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1648 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1649 "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1650
1651 /* try a 0 sized domain buffer */
1652 dom_sizeW = 0;
1653 acc_sizeW = MAX_PATH;
1654 accountW[0] = 0;
1655 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1656 /* this can fail or succeed depending on OS version but the size will always be returned */
1657 ok(dom_sizeW == real_dom_sizeW + 1,
1658 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1659 real_dom_sizeW + 1, dom_sizeW);
1660
1661 /* try a 0 sized domain buffer */
1662 dom_sizeW = 0;
1663 acc_sizeW = MAX_PATH;
1664 ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1665 /* this can fail or succeed depending on OS version but the size will always be returned */
1666 ok(dom_sizeW == real_dom_sizeW + 1,
1667 "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1668 real_dom_sizeW + 1, dom_sizeW);
1669
1670 FreeSid(pUsersSid);
1671
1672 /* Test LookupAccountSid with Sid retrieved from token information.
1673 This assumes this process is running under the account of the current user.*/
1674 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
1675 ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
1676 ptiUser = HeapAlloc(GetProcessHeap(), 0, cbti);
1677 if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
1678 {
1679 acc_sizeA = dom_sizeA = MAX_PATH;
1680 ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1681 ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1682 user_sizeA = MAX_PATH;
1683 ret = GetUserNameA(usernameA , &user_sizeA);
1684 ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
1685 todo_wine
1686 {
1687 ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
1688 }
1689 }
1690 HeapFree(GetProcessHeap(), 0, ptiUser);
1691
1692 if (pCreateWellKnownSid && pConvertSidToStringSidA)
1693 {
1694 trace("Well Known SIDs:\n");
1695 for (i = 0; i <= 60; i++)
1696 {
1697 size = SECURITY_MAX_SID_SIZE;
1698 if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
1699 {
1700 if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1701 {
1702 acc_sizeA = MAX_PATH;
1703 dom_sizeA = MAX_PATH;
1704 if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
1705 trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
1706 LocalFree(str_sidA);
1707 }
1708 }
1709 else
1710 {
1711 if (GetLastError() != ERROR_INVALID_PARAMETER)
1712 trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1713 else
1714 trace(" %d: not supported\n", i);
1715 }
1716 }
1717
1718 pLsaQueryInformationPolicy = (fnLsaQueryInformationPolicy)GetProcAddress( hmod, "LsaQueryInformationPolicy");
1719 pLsaOpenPolicy = (fnLsaOpenPolicy)GetProcAddress( hmod, "LsaOpenPolicy");
1720 pLsaFreeMemory = (fnLsaFreeMemory)GetProcAddress( hmod, "LsaFreeMemory");
1721 pLsaClose = (fnLsaClose)GetProcAddress( hmod, "LsaClose");
1722
1723 if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
1724 {
1725 NTSTATUS status;
1726 LSA_HANDLE handle;
1727 LSA_OBJECT_ATTRIBUTES object_attributes;
1728
1729 ZeroMemory(&object_attributes, sizeof(object_attributes));
1730 object_attributes.Length = sizeof(object_attributes);
1731
1732 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1733 ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1734 "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1735
1736 /* try a more restricted access mask if necessary */
1737 if (status == STATUS_ACCESS_DENIED) {
1738 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
1739 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1740 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
1741 }
1742
1743 if (status == STATUS_SUCCESS)
1744 {
1745 PPOLICY_ACCOUNT_DOMAIN_INFO info;
1746 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
1747 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
1748 if (status == STATUS_SUCCESS)
1749 {
1750 ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
1751 if (info->DomainSid)
1752 {
1753 int count = *GetSidSubAuthorityCount(info->DomainSid);
1754 CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
1755 test_sid_str((PSID)&max_sid.sid);
1756 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
1757 max_sid.sid.SubAuthorityCount = count + 1;
1758 test_sid_str((PSID)&max_sid.sid);
1759 max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
1760 test_sid_str((PSID)&max_sid.sid);
1761 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
1762 test_sid_str((PSID)&max_sid.sid);
1763 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
1764 test_sid_str((PSID)&max_sid.sid);
1765 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
1766 test_sid_str((PSID)&max_sid.sid);
1767 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
1768 test_sid_str((PSID)&max_sid.sid);
1769 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
1770 test_sid_str((PSID)&max_sid.sid);
1771 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
1772 test_sid_str((PSID)&max_sid.sid);
1773 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
1774 test_sid_str((PSID)&max_sid.sid);
1775 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
1776 test_sid_str((PSID)&max_sid.sid);
1777 max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
1778 test_sid_str((PSID)&max_sid.sid);
1779 max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
1780 test_sid_str((PSID)&max_sid.sid);
1781 max_sid.sid.SubAuthority[count] = 1000; /* first user account */
1782 test_sid_str((PSID)&max_sid.sid);
1783 }
1784
1785 pLsaFreeMemory((LPVOID)info);
1786 }
1787
1788 status = pLsaClose(handle);
1789 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
1790 }
1791 }
1792 }
1793 }
1794
1795 static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
1796 {
1797 static CHAR account[UNLEN + 1];
1798 static CHAR domain[UNLEN + 1];
1799 DWORD size, dom_size;
1800 SID_NAME_USE use;
1801
1802 *user = account;
1803 *dom = domain;
1804
1805 size = dom_size = UNLEN + 1;
1806 account[0] = '\0';
1807 domain[0] = '\0';
1808 SetLastError(0xdeadbeef);
1809 return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
1810 }
1811
1812 static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
1813 {
1814 SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
1815 PSID domainsid = NULL;
1816 char wk_sid[SECURITY_MAX_SID_SIZE];
1817 DWORD cb;
1818
1819 DWORD sid_size, domain_size;
1820 SID_NAME_USE sid_use;
1821 LPSTR domain, account, sid_domain, wk_domain, wk_account;
1822 PSID psid;
1823 BOOL ret ,ret2;
1824
1825 sid_size = 0;
1826 domain_size = 0;
1827 ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
1828 psid = HeapAlloc(GetProcessHeap(),0,sid_size);
1829 domain = HeapAlloc(GetProcessHeap(),0,domain_size);
1830 ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);
1831
1832 if (!result)
1833 {
1834 ok(!ret, " %s Should have failed to lookup account name\n",name);
1835 goto cleanup;
1836 }
1837
1838 AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
1839 cb = sizeof(wk_sid);
1840 if (!pCreateWellKnownSid(result, domainsid, wk_sid, &cb))
1841 {
1842 win_skip("SID %i is not available on the system\n",result);
1843 goto cleanup;
1844 }
1845
1846 ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
1847 if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
1848 {
1849 win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
1850 goto cleanup;
1851 }
1852
1853 get_sid_info(psid, &account, &sid_domain);
1854
1855 ok(ret, "Failed to lookup account name %s\n",name);
1856 ok(sid_size != 0, "sid_size was zero\n");
1857
1858 ok(EqualSid(psid,wk_sid),"(%s) Sids fail to match well known sid!\n",name);
1859
1860 ok(!lstrcmp(account, wk_account), "Expected %s , got %s\n", account, wk_account);
1861 ok(!lstrcmp(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
1862 ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
1863
1864 cleanup:
1865 FreeSid(domainsid);
1866 HeapFree(GetProcessHeap(),0,psid);
1867 HeapFree(GetProcessHeap(),0,domain);
1868 }
1869
1870 static void test_LookupAccountName(void)
1871 {
1872 DWORD sid_size, domain_size, user_size;
1873 DWORD sid_save, domain_save;
1874 CHAR user_name[UNLEN + 1];
1875 CHAR computer_name[UNLEN + 1];
1876 SID_NAME_USE sid_use;
1877 LPSTR domain, account, sid_dom;
1878 PSID psid;
1879 BOOL ret;
1880
1881 /* native crashes if (assuming all other parameters correct):
1882 * - peUse is NULL
1883 * - Sid is NULL and cbSid is > 0
1884 * - cbSid or cchReferencedDomainName are NULL
1885 * - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
1886 */
1887
1888 user_size = UNLEN + 1;
1889 SetLastError(0xdeadbeef);
1890 ret = GetUserNameA(user_name, &user_size);
1891 if (!ret && (GetLastError() == ERROR_NOT_LOGGED_ON))
1892 {
1893 /* Probably on win9x where the user used 'Cancel' instead of properly logging in */
1894 skip("Cannot get the user name (win9x and not logged in properly)\n");
1895 return;
1896 }
1897 ok(ret, "Failed to get user name : %d\n", GetLastError());
1898
1899 /* get sizes */
1900 sid_size = 0;
1901 domain_size = 0;
1902 sid_use = 0xcafebabe;
1903 SetLastError(0xdeadbeef);
1904 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
1905 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1906 {
1907 win_skip("LookupAccountNameA is not implemented\n");
1908 return;
1909 }
1910 ok(!ret, "Expected 0, got %d\n", ret);
1911 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1912 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1913 ok(sid_size != 0, "Expected non-zero sid size\n");
1914 ok(domain_size != 0, "Expected non-zero domain size\n");
1915 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1916
1917 sid_save = sid_size;
1918 domain_save = domain_size;
1919
1920 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1921 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1922
1923 /* try valid account name */
1924 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
1925 get_sid_info(psid, &account, &sid_dom);
1926 ok(ret, "Failed to lookup account name\n");
1927 ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
1928 todo_wine
1929 {
1930 ok(!lstrcmp(account, user_name), "Expected %s, got %s\n", user_name, account);
1931 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1932 }
1933 ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
1934 ok(lstrlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
1935 ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
1936 domain_size = domain_save;
1937 sid_size = sid_save;
1938
1939 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
1940 {
1941 skip("Non-english locale (test with hardcoded 'Everyone')\n");
1942 }
1943 else
1944 {
1945 ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
1946 get_sid_info(psid, &account, &sid_dom);
1947 ok(ret, "Failed to lookup account name\n");
1948 ok(sid_size != 0, "sid_size was zero\n");
1949 ok(!lstrcmp(account, "Everyone"), "Expected Everyone, got %s\n", account);
1950 ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1951 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
1952 ok(lstrlen(domain) == domain_size, "Expected %d, got %d\n", lstrlen(domain), domain_size);
1953 ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
1954 domain_size = domain_save;
1955 }
1956
1957 /* NULL Sid with zero sid size */
1958 SetLastError(0xdeadbeef);
1959 sid_size = 0;
1960 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1961 ok(!ret, "Expected 0, got %d\n", ret);
1962 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1963 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1964 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1965 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1966
1967 /* try cchReferencedDomainName - 1 */
1968 SetLastError(0xdeadbeef);
1969 domain_size--;
1970 ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1971 ok(!ret, "Expected 0, got %d\n", ret);
1972 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1973 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1974 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1975 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1976
1977 /* NULL ReferencedDomainName with zero domain name size */
1978 SetLastError(0xdeadbeef);
1979 domain_size = 0;
1980 ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
1981 ok(!ret, "Expected 0, got %d\n", ret);
1982 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1983 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1984 ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1985 ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1986
1987 HeapFree(GetProcessHeap(), 0, psid);
1988 HeapFree(GetProcessHeap(), 0, domain);
1989
1990 /* get sizes for NULL account name */
1991 sid_size = 0;
1992 domain_size = 0;
1993 sid_use = 0xcafebabe;
1994 SetLastError(0xdeadbeef);
1995 ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
1996 if (!ret && GetLastError() == ERROR_NONE_MAPPED)
1997 win_skip("NULL account name doesn't work on NT4\n");
1998 else
1999 {
2000 ok(!ret, "Expected 0, got %d\n", ret);
2001 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2002 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2003 ok(sid_size != 0, "Expected non-zero sid size\n");
2004 ok(domain_size != 0, "Expected non-zero domain size\n");
2005 ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
2006
2007 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2008 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2009
2010 /* try NULL account name */
2011 ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
2012 get_sid_info(psid, &account, &sid_dom);
2013 ok(ret, "Failed to lookup account name\n");
2014 /* Using a fixed string will not work on different locales */
2015 ok(!lstrcmp(account, domain),
2016 "Got %s for account and %s for domain, these should be the same\n",
2017 account, domain);
2018 ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
2019
2020 HeapFree(GetProcessHeap(), 0, psid);
2021 HeapFree(GetProcessHeap(), 0, domain);
2022 }
2023
2024 /* try an invalid account name */
2025 SetLastError(0xdeadbeef);
2026 sid_size = 0;
2027 domain_size = 0;
2028 ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
2029 ok(!ret, "Expected 0, got %d\n", ret);
2030 ok(GetLastError() == ERROR_NONE_MAPPED ||
2031 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
2032 "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
2033 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2034 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2035
2036 /* try an invalid system name */
2037 SetLastError(0xdeadbeef);
2038 sid_size = 0;
2039 domain_size = 0;
2040 ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
2041 ok(!ret, "Expected 0, got %d\n", ret);
2042 ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
2043 "Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
2044 ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
2045 ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
2046
2047 /* try with the computer name as the account name */
2048 domain_size = sizeof(computer_name);
2049 GetComputerNameA(computer_name, &domain_size);
2050 sid_size = 0;
2051 domain_size = 0;
2052 ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
2053 ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
2054 GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
2055 broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
2056 broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
2057 "LookupAccountNameA failed: %d\n", GetLastError());
2058 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2059 {
2060 psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
2061 domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
2062 ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
2063 ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
2064 ok(sid_use == SidTypeDomain ||
2065 (sid_use == SidTypeUser && ! strcmp(computer_name, user_name)), "expected SidTypeDomain for %s, got %d\n", computer_name, sid_use);
2066 HeapFree(GetProcessHeap(), 0, domain);
2067 HeapFree(GetProcessHeap(), 0, psid);
2068 }
2069
2070 /* Well Known names */
2071 if (!pCreateWellKnownSid)
2072 {
2073 win_skip("CreateWellKnownSid not available\n");
2074 return;
2075 }
2076
2077 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
2078 {
2079 skip("Non-english locale (skipping well known name creation tests)\n");
2080 return;
2081 }
2082
2083 check_wellknown_name("LocalService", WinLocalServiceSid);
2084 check_wellknown_name("Local Service", WinLocalServiceSid);
2085 /* 2 spaces */
2086 check_wellknown_name("Local Service", 0);
2087 check_wellknown_name("NetworkService", WinNetworkServiceSid);
2088 check_wellknown_name("Network Service", WinNetworkServiceSid);
2089
2090 /* example of some names where the spaces are not optional */
2091 check_wellknown_name("Terminal Server User", WinTerminalServerSid);
2092 check_wellknown_name("TerminalServer User", 0);
2093 check_wellknown_name("TerminalServerUser", 0);
2094 check_wellknown_name("Terminal ServerUser", 0);
2095
2096 check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
2097 check_wellknown_name("enterprisedomain controllers", 0);
2098 check_wellknown_name("enterprise domaincontrollers", 0);
2099 check_wellknown_name("enterprisedomaincontrollers", 0);
2100
2101 /* case insensitivity */
2102 check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
2103
2104 /* fully qualified account names */
2105 check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
2106 check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
2107 check_wellknown_name("nt authority test\\Network Service", 0);
2108 check_wellknown_name("Dummy\\Network Service", 0);
2109 check_wellknown_name("ntauthority\\Network Service", 0);
2110 }
2111
2112 static void test_security_descriptor(void)
2113 {
2114 SECURITY_DESCRIPTOR sd;
2115 char buf[8192];
2116 DWORD size;
2117 BOOL isDefault, isPresent, ret;
2118 PACL pacl;
2119 PSID psid;
2120
2121 SetLastError(0xdeadbeef);
2122 ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
2123 if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2124 {
2125 win_skip("InitializeSecurityDescriptor is not implemented\n");
2126 return;
2127 }
2128
2129 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2130 expect_eq(psid, NULL, PSID, "%p");
2131 expect_eq(isDefault, FALSE, BOOL, "%d");
2132 sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
2133
2134 SetLastError(0xdeadbeef);
2135 size = 5;
2136 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
2137 expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
2138 ok(size > 5, "Size not increased\n");
2139 if (size <= 8192)
2140 {
2141 expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
2142 ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
2143 expect_eq(psid, NULL, PSID, "%p");
2144 expect_eq(isDefault, FALSE, BOOL, "%d");
2145 ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
2146 expect_eq(psid, NULL, PSID, "%p");
2147 expect_eq(isDefault, FALSE, BOOL, "%d");
2148 ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
2149 expect_eq(isPresent, TRUE, BOOL, "%d");
2150 expect_eq(psid, NULL, PSID, "%p");
2151 expect_eq(isDefault, FALSE, BOOL, "%d");
2152 ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
2153 expect_eq(isPresent, TRUE, BOOL, "%d");
2154 expect_eq(psid, NULL, PSID, "%p");
2155 expect_eq(isDefault, FALSE, BOOL, "%d");
2156 }
2157 }
2158
2159 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
2160 #define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
2161 static void test_granted_access(HANDLE handle, ACCESS_MASK access,
2162 ACCESS_MASK alt, int line)
2163 {
2164 OBJECT_BASIC_INFORMATION obj_info;
2165 NTSTATUS status;
2166
2167 if (!pNtQueryObject)
2168 {
2169 skip_(__FILE__, line)("Not NT platform - skipping tests\n");
2170 return;
2171 }
2172
2173 status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
2174 sizeof(obj_info), NULL );
2175 ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
2176 if (alt)
2177 ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
2178 obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
2179 "or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
2180 else
2181 ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
2182 "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
2183 }
2184
2185 #define CHECK_SET_SECURITY(o,i,e) \
2186 do{ \
2187 BOOL res; \
2188 DWORD err; \
2189 SetLastError( 0xdeadbeef ); \
2190 res = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
2191 err = GetLastError(); \
2192 if (e == ERROR_SUCCESS) \
2193 ok(res, "SetKernelObjectSecurity failed with %d\n", err); \
2194 else \
2195 ok(!res && err == e, "SetKernelObjectSecurity should have failed " \
2196 "with %s, instead of %d\n", #e, err); \
2197 }while(0)
2198
2199 static void test_process_security(void)
2200 {
2201 BOOL res;
2202 PTOKEN_OWNER owner;
2203 PTOKEN_PRIMARY_GROUP group;
2204 PSID AdminSid = NULL, UsersSid = NULL;
2205 PACL Acl = NULL;
2206 SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
2207 char buffer[MAX_PATH];
2208 PROCESS_INFORMATION info;
2209 STARTUPINFOA startup;
2210 SECURITY_ATTRIBUTES psa;
2211 HANDLE token, event;
2212 DWORD size;
2213
2214 Acl = HeapAlloc(GetProcessHeap(), 0, 256);
2215 res = InitializeAcl(Acl, 256, ACL_REVISION);
2216 if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2217 {
2218 win_skip("ACLs not implemented - skipping tests\n");
2219 HeapFree(GetProcessHeap(), 0, Acl);
2220 return;
2221 }
2222 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2223
2224 /* get owner from the token we might be running as a user not admin */
2225 res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
2226 ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
2227 if (!res)
2228 {
2229 HeapFree(GetProcessHeap(), 0, Acl);
2230 return;
2231 }
2232
2233 res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
2234 ok(!res, "Expected failure, got %d\n", res);
2235 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2236 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2237
2238 owner = HeapAlloc(GetProcessHeap(), 0, size);
2239 res = GetTokenInformation( token, TokenOwner, owner, size, &size );
2240 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2241 AdminSid = ((TOKEN_OWNER*)owner)->Owner;
2242
2243 res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
2244 ok(!res, "Expected failure, got %d\n", res);
2245 ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
2246 "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
2247
2248 group = HeapAlloc(GetProcessHeap(), 0, size);
2249 res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
2250 ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
2251 UsersSid = ((TOKEN_PRIMARY_GROUP*)group)->PrimaryGroup;
2252
2253 CloseHandle( token );
2254 if (!res)
2255 {
2256 HeapFree(GetProcessHeap(), 0, group);
2257 HeapFree(GetProcessHeap(), 0, owner);
2258 HeapFree(GetProcessHeap(), 0, Acl);
2259 return;
2260 }
2261
2262 res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
2263 ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
2264 res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
2265 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2266
2267 SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
2268 res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
2269 ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
2270
2271 event = CreateEvent( NULL, TRUE, TRUE, "test_event" );
2272 ok(event != NULL, "CreateEvent %d\n", GetLastError());
2273
2274 SecurityDescriptor->Revision = 0;
2275 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
2276 SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
2277
2278 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2279 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
2280 CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
2281 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2282 /* NULL DACL is valid and means default DACL from token */
2283 SecurityDescriptor->Control |= SE_DACL_PRESENT;
2284 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2285
2286 /* Set owner and group and dacl */
2287 res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
2288 ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2289 CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
2290 res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
2291 ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2292 CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
2293 res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
2294 ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
2295 CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
2296
2297 sprintf(buffer, "%s tests/security.c test", myARGV[0]);
2298 memset(&startup, 0, sizeof(startup));
2299 startup.cb = sizeof(startup);
2300 startup.dwFlags = STARTF_USESHOWWINDOW;
2301 startup.wShowWindow = SW_SHOWNORMAL;
2302
2303 psa.nLength = sizeof(psa);
2304 psa.lpSecurityDescriptor = SecurityDescriptor;
2305 psa.bInheritHandle = TRUE;
2306
2307 /* Doesn't matter what ACL say we should get full access for ourselves */
2308 ok(CreateProcessA( NULL, buffer, &psa, NULL, FALSE, 0, NULL, NULL, &startup, &info ),
2309 "CreateProcess with err:%d\n", GetLastError());
2310 TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS,
2311 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2312 winetest_wait_child_process( info.hProcess );
2313
2314 CloseHandle( info.hProcess );
2315 CloseHandle( info.hThread );
2316 CloseHandle( event );
2317 HeapFree(GetProcessHeap(), 0, group);
2318 HeapFree(GetProcessHeap(), 0, owner);
2319 HeapFree(GetProcessHeap(), 0, Acl);
2320 HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
2321 }
2322
2323 static void test_process_security_child(void)
2324 {
2325 HANDLE handle, handle1;
2326 BOOL ret;
2327 DWORD err;
2328
2329 handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
2330 ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
2331 TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
2332
2333 ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2334 &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS ),
2335 "duplicating handle err:%d\n", GetLastError());
2336 TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
2337
2338 CloseHandle( handle1 );
2339
2340 SetLastError( 0xdeadbeef );
2341 ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2342 &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
2343 err = GetLastError();
2344 todo_wine
2345 ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
2346 "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
2347
2348 CloseHandle( handle );
2349
2350 /* These two should fail - they are denied by ACL */
2351 handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
2352 todo_wine
2353 ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
2354 handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
2355 todo_wine
2356 ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
2357
2358 /* Documented privilege elevation */
2359 ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
2360 &handle, 0, TRUE, DUPLICATE_SAME_ACCESS ),
2361 "duplicating handle err:%d\n", GetLastError());
2362 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS,
2363 STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
2364
2365 CloseHandle( handle );
2366
2367 /* Same only explicitly asking for all access rights */
2368 ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
2369 &handle, PROCESS_ALL_ACCESS, TRUE, 0 ),
2370 "duplicating handle err:%d\n", GetLastError());
2371 TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS,
2372 PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
2373 ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
2374 &handle1, PROCESS_VM_READ, TRUE, 0 ),
2375 "duplicating handle err:%d\n", GetLastError());
2376 TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
2377 CloseHandle( handle1 );
2378 CloseHandle( handle );
2379 }
2380
2381 static void test_impersonation_level(void)
2382 {
2383 HANDLE Token, ProcessToken;
2384 HANDLE Token2;
2385 DWORD Size;
2386 TOKEN_PRIVILEGES *Privileges;
2387 TOKEN_USER *User;
2388 PRIVILEGE_SET *PrivilegeSet;
2389 BOOL AccessGranted;
2390 BOOL ret;
2391 HKEY hkey;
2392 DWORD error;
2393
2394 pDuplicateTokenEx = (fnDuplicateTokenEx) GetProcAddress(hmod, "DuplicateTokenEx");
2395 if( !pDuplicateTokenEx ) {
2396 win_skip("DuplicateTokenEx is not available\n");
2397 return;
2398 }
2399 SetLastError(0xdeadbeef);
2400 ret = ImpersonateSelf(SecurityAnonymous);
2401 if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2402 {
2403 win_skip("ImpersonateSelf is not implemented\n");
2404 return;
2405 }
2406 ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
2407 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2408 ok(!ret, "OpenThreadToken should have failed\n");
2409 error = GetLastError();
2410 ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2411 /* can't perform access check when opening object against an anonymous impersonation token */
2412 todo_wine {
2413 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2414 ok(error == ERROR_INVALID_HANDLE || error == ERROR_CANT_OPEN_ANONYMOUS,
2415 "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE or ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
2416 }
2417 RevertToSelf();
2418
2419 ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
2420 ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
2421
2422 ret = pDuplicateTokenEx(ProcessToken,
2423 TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
2424 SecurityAnonymous, TokenImpersonation, &Token);
2425 ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
2426 /* can't increase the impersonation level */
2427 ret = DuplicateToken(Token, SecurityIdentification, &Token2);
2428 error = GetLastError();
2429 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
2430 "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2431 /* we can query anything from an anonymous token, including the user */
2432 ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
2433 error = GetLastError();
2434 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2435 User = HeapAlloc(GetProcessHeap(), 0, Size);
2436 ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
2437 ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
2438 HeapFree(GetProcessHeap(), 0, User);
2439
2440 /* PrivilegeCheck fails with SecurityAnonymous level */
2441 ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
2442 error = GetLastError();
2443 ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
2444 Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
2445 ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
2446 ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
2447
2448 PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
2449 PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
2450 memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
2451 PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
2452 HeapFree(GetProcessHeap(), 0, Privileges);
2453
2454 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2455 error = GetLastError();
2456 ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2457
2458 CloseHandle(Token);
2459
2460 ret = ImpersonateSelf(SecurityIdentification);
2461 ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
2462 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2463 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2464
2465 /* can't perform access check when opening object against an identification impersonation token */
2466 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2467 todo_wine {
2468 ok(error == ERROR_INVALID_HANDLE || error == ERROR_BAD_IMPERSONATION_LEVEL,
2469 "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE or ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
2470 }
2471 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2472 ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
2473 CloseHandle(Token);
2474 RevertToSelf();
2475
2476 ret = ImpersonateSelf(SecurityImpersonation);
2477 ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
2478 ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
2479 ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
2480 error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
2481 ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
2482 RegCloseKey(hkey);
2483 ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
2484 ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
2485 RevertToSelf();
2486
2487 CloseHandle(Token);
2488 CloseHandle(ProcessToken);
2489
2490 HeapFree(GetProcessHeap(), 0, PrivilegeSet);
2491 }
2492
2493 static void test_SetEntriesInAcl(void)
2494 {
2495 DWORD res;
2496 PSID EveryoneSid = NULL, UsersSid = NULL;
2497 PACL OldAcl = NULL, NewAcl;
2498 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
2499 SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
2500 EXPLICIT_ACCESSW ExplicitAccess;
2501 static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
2502 static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
2503
2504 if (!pSetEntriesInAclW)
2505 {
2506 win_skip("SetEntriesInAclW is not available\n");
2507 return;
2508 }
2509
2510 NewAcl = (PACL)0xdeadbeef;
2511 res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
2512 if(res == ERROR_CALL_NOT_IMPLEMENTED)
2513 {
2514 win_skip("SetEntriesInAclW is not implemented\n");
2515 return;
2516 }
2517 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2518 ok(NewAcl == NULL ||
2519 broken(NewAcl != NULL), /* NT4 */
2520 "NewAcl=%p, expected NULL\n", NewAcl);
2521 LocalFree(NewAcl);
2522
2523 OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
2524 res = InitializeAcl(OldAcl, 256, ACL_REVISION);
2525 if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2526 {
2527 win_skip("ACLs not implemented - skipping tests\n");
2528 HeapFree(GetProcessHeap(), 0, OldAcl);
2529 return;
2530 }
2531 ok(res, "InitializeAcl failed with error %d\n", GetLastError());
2532
2533 res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
2534 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2535
2536 res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
2537 DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
2538 ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
2539
2540 res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
2541 ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
2542
2543 ExplicitAccess.grfAccessPermissions = KEY_WRITE;
2544 ExplicitAccess.grfAccessMode = GRANT_ACCESS;
2545 ExplicitAccess.grfInheritance = NO_INHERITANCE;
2546 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
2547 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2548 ExplicitAccess.Trustee.ptstrName = EveryoneSid;
2549 ExplicitAccess.Trustee.MultipleTrusteeOperation = 0xDEADBEEF;
2550 ExplicitAccess.Trustee.pMultipleTrustee = (PVOID)0xDEADBEEF;
2551 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2552 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2553 ok(NewAcl != NULL, "returned acl was NULL\n");
2554 LocalFree(NewAcl);
2555
2556 ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
2557 ExplicitAccess.Trustee.pMultipleTrustee = NULL;
2558 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2559 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2560 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2561 ok(NewAcl != NULL, "returned acl was NULL\n");
2562 LocalFree(NewAcl);
2563
2564 if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
2565 {
2566 skip("Non-english locale (test with hardcoded 'Everyone')\n");
2567 }
2568 else
2569 {
2570 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2571 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
2572 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2573 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2574 ok(NewAcl != NULL, "returned acl was NULL\n");
2575 LocalFree(NewAcl);
2576
2577 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
2578 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2579 ok(res == ERROR_INVALID_PARAMETER ||
2580 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2581 "SetEntriesInAclW failed: %u\n", res);
2582 ok(NewAcl == NULL ||
2583 broken(NewAcl != NULL), /* NT4 */
2584 "returned acl wasn't NULL: %p\n", NewAcl);
2585
2586 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2587 ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
2588 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2589 ok(res == ERROR_INVALID_PARAMETER ||
2590 broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
2591 "SetEntriesInAclW failed: %u\n", res);
2592 ok(NewAcl == NULL ||
2593 broken(NewAcl != NULL), /* NT4 */
2594 "returned acl wasn't NULL: %p\n", NewAcl);
2595
2596 ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
2597 ExplicitAccess.grfAccessMode = SET_ACCESS;
2598 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2599 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2600 ok(NewAcl != NULL, "returned acl was NULL\n");
2601 LocalFree(NewAcl);
2602 }
2603
2604 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_USER;
2605 ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
2606 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2607 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2608 ok(NewAcl != NULL, "returned acl was NULL\n");
2609 LocalFree(NewAcl);
2610
2611 ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
2612 ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
2613 ExplicitAccess.Trustee.ptstrName = UsersSid;
2614 res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
2615 ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
2616 ok(NewAcl != NULL, "returned acl was NULL\n");
2617 LocalFree(NewAcl);
2618
2619 FreeSid(UsersSid);
2620 FreeSid(EveryoneSid);
2621 HeapFree(GetProcessHeap(), 0, OldAcl);
2622 }
2623
2624 static void test_GetNamedSecurityInfoA(void)
2625 {
2626 PSECURITY_DESCRIPTOR pSecDesc;
2627 DWORD revision;
2628 SECURITY_DESCRIPTOR_CONTROL control;
2629 PSID owner;
2630 PSID group;
2631 BOOL owner_defaulted;
2632 BOOL group_defaulted;
2633 DWORD error;
2634 BOOL ret;
2635 CHAR windows_dir[MAX_PATH];
2636
2637 if (!pGetNamedSecurityInfoA)
2638 {
2639 win_skip("GetNamedSecurityInfoA is not available\n");
2640 return;
2641 }
2642
2643 ret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
2644 ok(ret, "GetWindowsDirectory failed with error %d\n", GetLastError());
2645
2646 SetLastError(0xdeadbeef);
2647 error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
2648 OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
2649 NULL, NULL, NULL, NULL, &pSecDesc);
2650 if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
2651 {
2652 win_skip("GetNamedSecurityInfoA is not implemented\n");
2653 return;
2654 }
2655 ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
2656
2657 ret = GetSecurityDescriptorControl(pSecDesc, &control, &revision);
2658 ok(ret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
2659 ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
2660 broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
2661 "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
2662 ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
2663 ret = GetSecurityDescriptorOwner(pSecDesc, &owner, &owner_defaulted);
2664 ok(ret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
2665 ok(owner != NULL, "owner should not be NULL\n");
2666 ret = GetSecurityDescriptorGroup(pSecDesc, &group, &group_defaulted);
2667 ok(ret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
2668 ok(group != NULL, "group should not be NULL\n");
2669 LocalFree(pSecDesc);
2670 }
2671
2672 static void test_ConvertStringSecurityDescriptor(void)
2673 {
2674 BOOL ret;
2675 PSECURITY_DESCRIPTOR pSD;
2676 static const WCHAR Blank[] = { 0 };
2677 int i;
2678 static const struct
2679 {
2680 const char *sidstring;
2681 DWORD revision;
2682 BOOL ret;
2683 DWORD GLE;
2684 DWORD altGLE;
2685 } cssd[] =
2686 {
2687 { "D:(A;;GA;;;WD)", 0xdeadbeef, FALSE, ERROR_UNKNOWN_REVISION },
2688 /* test ACE string type */
2689 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
2690 { "D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
2691 { "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
2692 /* test ACE string with spaces */
2693 { " D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
2694 { "D: (D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
2695 { "D:( D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
2696 { "D:(D ;;GA;;;WD)", SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
2697 { "D:(D; ;GA;;;WD)", SDDL_REVISION_1, TRUE },
2698 { "D:(D;; GA;;;WD)", SDDL_REVISION_1, TRUE },
2699 { "D:(D;;GA ;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
2700 { "D:(D;;GA; ;;WD)", SDDL_REVISION_1, TRUE },
2701 { "D:(D;;GA;; ;WD)", SDDL_REVISION_1, TRUE },
2702 { "D:(D;;GA;;; WD)", SDDL_REVISION_1, TRUE },
2703 { "D:(D;;GA;;;WD )", SDDL_REVISION_1, TRUE },
2704 /* test ACE string access rights */
2705 { "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
2706 { "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, TRUE },
2707 { "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, TRUE },
2708 { "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, TRUE },
2709 { "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, TRUE },
2710 { "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, TRUE },
2711 { "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
2712 { "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
2713 /* test ACE string access right error case */
2714 { "D:(A;;ROB;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
2715 /* test behaviour with empty strings */
2716 { "", SDDL_REVISION_1, TRUE },
2717 /* test ACE string SID */
2718 { "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, TRUE },
2719 { "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
2720 };
2721
2722 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
2723 {
2724 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
2725 return;
2726 }
2727
2728 for (i = 0; i < sizeof(cssd)/sizeof(cssd[0]); i++)
2729 {
2730 DWORD GLE;
2731
2732 SetLastError(0xdeadbeef);
2733 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2734 cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
2735 GLE = GetLastError();
2736 ok(ret == cssd[i].ret, "(%02d) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
2737 if (!cssd[i].ret)
2738 ok(GLE == cssd[i].GLE ||
2739 (cssd[i].altGLE && GLE == cssd[i].altGLE),
2740 "(%02d) Unexpected last error %d\n", i, GLE);
2741 if (ret)
2742 LocalFree(pSD);
2743 }
2744
2745 /* test behaviour with NULL parameters */
2746 SetLastError(0xdeadbeef);
2747 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2748 NULL, 0xdeadbeef, &pSD, NULL);
2749 todo_wine
2750 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2751 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2752 GetLastError());
2753
2754 SetLastError(0xdeadbeef);
2755 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
2756 NULL, 0xdeadbeef, &pSD, NULL);
2757 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2758 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2759 GetLastError());
2760
2761 SetLastError(0xdeadbeef);
2762 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2763 "D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
2764 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2765 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2766 GetLastError());
2767
2768 SetLastError(0xdeadbeef);
2769 ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
2770 "D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
2771 ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
2772 "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
2773 GetLastError());
2774
2775 /* test behaviour with empty strings */
2776 SetLastError(0xdeadbeef);
2777 ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
2778 Blank, SDDL_REVISION_1, &pSD, NULL);
2779 ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
2780 LocalFree(pSD);
2781 }
2782
2783 static void test_ConvertSecurityDescriptorToString(void)
2784 {
2785 SECURITY_DESCRIPTOR desc;
2786 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
2787 LPSTR string;
2788 DWORD size;
2789 PSID psid, psid2;
2790 PACL pacl;
2791 char sid_buf[256];
2792 char acl_buf[8192];
2793 ULONG len;
2794
2795 if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
2796 {
2797 win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
2798 return;
2799 }
2800 if (!pCreateWellKnownSid)
2801 {
2802 win_skip("CreateWellKnownSid is not available\n");
2803 return;
2804 }
2805
2806 /* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
2807 * don't replicate this feature so we only test len >= strlen+1. */
2808 #define CHECK_RESULT_AND_FREE(exp_str) \
2809 ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
2810 ok(len >= (lstrlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(exp_str) + 1, len); \
2811 LocalFree(string);
2812
2813 #define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
2814 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); \
2815 ok(len >= (strlen(string) + 1), "Length mismatch (expected %d, got %d)\n", lstrlen(string) + 1, len); \
2816 LocalFree(string);
2817
2818 InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
2819 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2820 CHECK_RESULT_AND_FREE("");
2821
2822 size = 4096;
2823 pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
2824 SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
2825 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2826 CHECK_RESULT_AND_FREE("O:S-1-2-0");
2827
2828 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
2829 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2830 CHECK_RESULT_AND_FREE("O:S-1-2-0");
2831
2832 size = sizeof(sid_buf);
2833 pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
2834 SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
2835 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2836 CHECK_RESULT_AND_FREE("O:SY");
2837
2838 pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
2839 SetSecurityDescriptorGroup(&desc, psid, TRUE);
2840 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2841 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
2842
2843 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
2844 CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
2845
2846 pacl = (PACL)acl_buf;
2847 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
2848 SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
2849 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2850 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
2851
2852 SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
2853 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2854 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
2855
2856 pConvertStringSidToSidA("S-1-5-6", &psid2);
2857 pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
2858 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2859 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
2860
2861 pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
2862 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2863 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
2864
2865 pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
2866 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2867 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)");
2868
2869
2870 pacl = (PACL)acl_buf;
2871 InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
2872 SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
2873 ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
2874 CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
2875
2876 /* fails in win2k */
2877 SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
2878 pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
2879 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
2880 {
2881 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
2882 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
2883 }
2884
2885 /* fails in win2k */
2886 pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
2887 if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
2888 {
2889 CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
2890 "O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
2891 }
2892
2893 LocalFree(psid2);
2894 LocalFree(psid);
2895 }
2896
2897 static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
2898 {
2899 SECURITY_DESCRIPTOR_CONTROL ref;
2900 SECURITY_DESCRIPTOR_CONTROL test;
2901
2902 SECURITY_DESCRIPTOR_CONTROL const mutable
2903 = SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
2904 | SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
2905 | SE_DACL_PROTECTED | SE_SACL_PROTECTED
2906 | 0x00000040 | 0x00000080 /* not defined in winnt.h */
2907 ;
2908 SECURITY_DESCRIPTOR_CONTROL const immutable
2909 = SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
2910 | SE_DACL_PRESENT | SE_DACL_DEFAULTED
2911 | SE_SACL_PRESENT | SE_SACL_DEFAULTED
2912 | SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
2913 ;
2914
2915 int bit;
2916 DWORD dwRevision;
2917 LPCSTR fmt = "Expected error %s, got %u\n";
2918
2919 GetSecurityDescriptorControl (sec, &ref, &dwRevision);
2920
2921 /* The mutable bits are mutable regardless of the truth of
2922 SE_DACL_PRESENT and/or SE_SACL_PRESENT */
2923
2924 /* Check call barfs if any bit-of-interest is immutable */
2925 for (bit = 0; bit < 16; ++bit)
2926 {
2927 SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
2928 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
2929
2930 SECURITY_DESCRIPTOR_CONTROL ctrl;
2931
2932 DWORD dwExpect = (bitOfInterest & immutable)
2933 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
2934 LPCSTR strExpect = (bitOfInterest & immutable)
2935 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
2936
2937 ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
2938 setOrClear ^= bitOfInterest;
2939 SetLastError (0xbebecaca);
2940 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
2941 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2942 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2943 expect_eq(test, ctrl, int, "%x");
2944
2945 ctrl = ref;
2946 setOrClear ^= bitOfInterest;
2947 SetLastError (0xbebecaca);
2948 pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
2949 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2950 GetSecurityDescriptorControl (sec, &test, &dwRevision);
2951 expect_eq(test, ref, int, "%x");
2952 }
2953
2954 /* Check call barfs if any bit-to-set is immutable
2955 even when not a bit-of-interest */
2956 for (bit = 0; bit < 16; ++bit)
2957 {
2958 SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
2959 SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
2960
2961 SECURITY_DESCRIPTOR_CONTROL ctrl;
2962
2963 DWORD dwExpect = ((1 << bit) & immutable)
2964 ? ERROR_INVALID_PARAMETER : 0xbebecaca;
2965 LPCSTR strExpect = ((1 << bit) & immutable)
2966 ? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
2967
2968 ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
2969 setOrClear ^= bitsOfInterest;
2970 SetLastError (0xbebecaca);
2971 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
2972 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2973 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2974 expect_eq(test, ctrl, int, "%x");
2975
2976 ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
2977 setOrClear ^= bitsOfInterest;
2978 SetLastError (0xbebecaca);
2979 pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
2980 ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
2981 GetSecurityDescriptorControl(sec, &test, &dwRevision);
2982 expect_eq(test, ctrl, int, "%x");
2983 }
2984 }
2985
2986 static void test_PrivateObjectSecurity(void)
2987 {
2988 SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
2989 SECURITY_DESCRIPTOR_CONTROL ctrl;
2990 PSECURITY_DESCRIPTOR sec;
2991 DWORD dwDescSize;
2992 DWORD dwRevision;
2993 DWORD retSize;
2994 LPSTR string;
2995 ULONG len;
2996 PSECURITY_DESCRIPTOR buf;
2997
2998 if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
2999 {
3000 win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
3001 return;
3002 }
3003
3004 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3005 "O:SY"
3006 "G:S-1-5-21-93476-23408-4576"
3007 "D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
3008 "(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
3009 "S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
3010 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3011
3012 test_SetSecurityDescriptorControl(sec);
3013
3014 LocalFree(sec);
3015
3016 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
3017 "O:SY"
3018 "G:S-1-5-21-93476-23408-4576",
3019 SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
3020
3021 test_SetSecurityDescriptorControl(sec);
3022
3023 LocalFree(sec);
3024
3025 ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(