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