mshtml/htmltextcont: Initialize value (Coverity).
[wine] / dlls / advapi32 / tests / security.c
1 /*
2  * Unit tests for security functions
3  *
4  * Copyright (c) 2004 Mike McCormack
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22 #include <stdio.h>
23
24 #include "ntstatus.h"
25 #define WIN32_NO_STATUS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winerror.h"
29 #include "aclapi.h"
30 #include "winnt.h"
31 #include "sddl.h"
32 #include "ntsecapi.h"
33 #include "lmcons.h"
34 #include "winternl.h"
35
36 #include "wine/test.h"
37
38 typedef VOID (WINAPI *fnBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
39 typedef VOID (WINAPI *fnBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
40 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
41                                                           POBJECTS_AND_NAME_A pObjName,
42                                                           SE_OBJECT_TYPE ObjectType,
43                                                           LPSTR ObjectTypeName,
44                                                           LPSTR InheritedObjectTypeName,
45                                                           LPSTR Name );
46 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
47                                                          POBJECTS_AND_SID pObjSid,
48                                                          GUID* pObjectGuid,
49                                                          GUID* pInheritedObjectGuid,
50                                                          PSID pSid );
51 typedef LPSTR (WINAPI *fnGetTrusteeNameA)( PTRUSTEEA pTrustee );
52 typedef BOOL (WINAPI *fnConvertSidToStringSidA)( PSID pSid, LPSTR *str );
53 typedef BOOL (WINAPI *fnConvertStringSidToSidA)( LPCSTR str, PSID pSid );
54 static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
55                                                                             PSECURITY_DESCRIPTOR*, PULONG );
56 typedef BOOL (WINAPI *fnGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
57                                           PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
58 static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
59                                               PSID*, PSID*, PACL*, PACL*,
60                                               PSECURITY_DESCRIPTOR*);
61 typedef DWORD (WINAPI *fnRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
62 typedef BOOL (WINAPI *fnCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
63 typedef BOOL (WINAPI *fnDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
64                                         SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
65
66 typedef NTSTATUS (WINAPI *fnLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
67 typedef NTSTATUS (WINAPI *fnLsaClose)(LSA_HANDLE);
68 typedef NTSTATUS (WINAPI *fnLsaFreeMemory)(PVOID);
69 typedef NTSTATUS (WINAPI *fnLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
70 static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
71 static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
72
73 static HMODULE hmod;
74 static int     myARGC;
75 static char**  myARGV;
76
77 fnBuildTrusteeWithSidA   pBuildTrusteeWithSidA;
78 fnBuildTrusteeWithNameA  pBuildTrusteeWithNameA;
79 fnBuildTrusteeWithObjectsAndNameA pBuildTrusteeWithObjectsAndNameA;
80 fnBuildTrusteeWithObjectsAndSidA pBuildTrusteeWithObjectsAndSidA;
81 fnGetTrusteeNameA pGetTrusteeNameA;
82 fnConvertSidToStringSidA pConvertSidToStringSidA;
83 fnConvertStringSidToSidA pConvertStringSidToSidA;
84 fnGetFileSecurityA pGetFileSecurityA;
85 fnRtlAdjustPrivilege pRtlAdjustPrivilege;
86 fnCreateWellKnownSid pCreateWellKnownSid;
87 fnDuplicateTokenEx pDuplicateTokenEx;
88 fnLsaQueryInformationPolicy pLsaQueryInformationPolicy;
89 fnLsaClose pLsaClose;
90 fnLsaFreeMemory pLsaFreeMemory;
91 fnLsaOpenPolicy pLsaOpenPolicy;
92
93 struct sidRef
94 {
95     SID_IDENTIFIER_AUTHORITY auth;
96     const char *refStr;
97 };
98
99 static void init(void)
100 {
101     HMODULE hntdll;
102
103     hntdll = GetModuleHandleA("ntdll.dll");
104     pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
105
106     hmod = GetModuleHandle("advapi32.dll");
107     pConvertStringSecurityDescriptorToSecurityDescriptorA =
108         (void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
109     pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
110     pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
111
112     myARGC = winetest_get_mainargs( &myARGV );
113 }
114
115 static void test_str_sid(const char *str_sid)
116 {
117     PSID psid;
118     char *temp;
119
120     if (pConvertStringSidToSidA(str_sid, &psid))
121     {
122         if (pConvertSidToStringSidA(psid, &temp))
123         {
124             trace(" %s: %s\n", str_sid, temp);
125             LocalFree(temp);
126         }
127         LocalFree(psid);
128     }
129     else
130     {
131         if (GetLastError() != ERROR_INVALID_SID)
132             trace(" %s: couldn't be converted, returned %d\n", str_sid, GetLastError());
133         else
134             trace(" %s: couldn't be converted\n", str_sid);
135     }
136 }
137
138 static void test_sid(void)
139 {
140     struct sidRef refs[] = {
141      { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
142      { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1"  },
143      { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1"     },
144      { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1"       },
145      { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1"         },
146      { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1"        },
147     };
148     const char noSubAuthStr[] = "S-1-5";
149     unsigned int i;
150     PSID psid = NULL;
151     BOOL r;
152     LPSTR str = NULL;
153
154     pConvertSidToStringSidA = (fnConvertSidToStringSidA)
155                     GetProcAddress( hmod, "ConvertSidToStringSidA" );
156     if( !pConvertSidToStringSidA )
157         return;
158     pConvertStringSidToSidA = (fnConvertStringSidToSidA)
159                     GetProcAddress( hmod, "ConvertStringSidToSidA" );
160     if( !pConvertStringSidToSidA )
161         return;
162
163     r = pConvertStringSidToSidA( NULL, NULL );
164     ok( !r, "expected failure with NULL parameters\n" );
165     if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
166         return;
167     ok( GetLastError() == ERROR_INVALID_PARAMETER,
168      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
169      GetLastError() );
170
171     r = pConvertStringSidToSidA( refs[0].refStr, NULL );
172     ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
173      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
174      GetLastError() );
175
176     r = pConvertStringSidToSidA( NULL, &str );
177     ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
178      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
179      GetLastError() );
180
181     r = pConvertStringSidToSidA( noSubAuthStr, &psid );
182     ok( !r,
183      "expected failure with no sub authorities\n" );
184     ok( GetLastError() == ERROR_INVALID_SID,
185      "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
186      GetLastError() );
187
188     for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
189     {
190         PISID pisid;
191
192         r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
193          &psid );
194         ok( r, "failed to allocate sid\n" );
195         r = pConvertSidToStringSidA( psid, &str );
196         ok( r, "failed to convert sid\n" );
197         if (r)
198         {
199             ok( !strcmp( str, refs[i].refStr ),
200                 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
201             LocalFree( str );
202         }
203         if( psid )
204             FreeSid( psid );
205
206         r = pConvertStringSidToSidA( refs[i].refStr, &psid );
207         ok( r, "failed to parse sid string\n" );
208         pisid = (PISID)psid;
209         ok( pisid &&
210          !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
211          sizeof(refs[i].auth) ),
212          "string sid %s didn't parse to expected value\n"
213          "(got 0x%04x%08x, expected 0x%04x%08x)\n",
214          refs[i].refStr,
215          MAKEWORD( pisid->IdentifierAuthority.Value[1],
216          pisid->IdentifierAuthority.Value[0] ),
217          MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
218          pisid->IdentifierAuthority.Value[4] ),
219          MAKEWORD( pisid->IdentifierAuthority.Value[3],
220          pisid->IdentifierAuthority.Value[2] ) ),
221          MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
222          MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
223          MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
224         if( psid )
225             LocalFree( psid );
226     }
227
228     trace("String SIDs:\n");
229     test_str_sid("AO");
230     test_str_sid("RU");
231     test_str_sid("AN");
232     test_str_sid("AU");
233     test_str_sid("BA");
234     test_str_sid("BG");
235     test_str_sid("BO");
236     test_str_sid("BU");
237     test_str_sid("CA");
238     test_str_sid("CG");
239     test_str_sid("CO");
240     test_str_sid("DA");
241     test_str_sid("DC");
242     test_str_sid("DD");
243     test_str_sid("DG");
244     test_str_sid("DU");
245     test_str_sid("EA");
246     test_str_sid("ED");
247     test_str_sid("WD");
248     test_str_sid("PA");
249     test_str_sid("IU");
250     test_str_sid("LA");
251     test_str_sid("LG");
252     test_str_sid("LS");
253     test_str_sid("SY");
254     test_str_sid("NU");
255     test_str_sid("NO");
256     test_str_sid("NS");
257     test_str_sid("PO");
258     test_str_sid("PS");
259     test_str_sid("PU");
260     test_str_sid("RS");
261     test_str_sid("RD");
262     test_str_sid("RE");
263     test_str_sid("RC");
264     test_str_sid("SA");
265     test_str_sid("SO");
266     test_str_sid("SU");
267 }
268
269 static void test_trustee(void)
270 {
271     GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
272     GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
273     GUID ZeroGuid;
274     OBJECTS_AND_NAME_ oan;
275     OBJECTS_AND_SID oas;
276     TRUSTEE trustee;
277     PSID psid;
278     char szObjectTypeName[] = "ObjectTypeName";
279     char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
280     char szTrusteeName[] = "szTrusteeName";
281     SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
282
283     memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
284
285     pBuildTrusteeWithSidA = (fnBuildTrusteeWithSidA)
286                     GetProcAddress( hmod, "BuildTrusteeWithSidA" );
287     pBuildTrusteeWithNameA = (fnBuildTrusteeWithNameA)
288                     GetProcAddress( hmod, "BuildTrusteeWithNameA" );
289     pBuildTrusteeWithObjectsAndNameA = (fnBuildTrusteeWithObjectsAndNameA)
290                     GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
291     pBuildTrusteeWithObjectsAndSidA = (fnBuildTrusteeWithObjectsAndSidA)
292                     GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
293     pGetTrusteeNameA = (fnGetTrusteeNameA)
294                     GetProcAddress (hmod, "GetTrusteeNameA" );
295     if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
296         !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
297         !pGetTrusteeNameA )
298         return;
299
300     if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
301     {
302         trace( "failed to init SID\n" );
303        return;
304     }
305
306     /* test BuildTrusteeWithSidA */
307     memset( &trustee, 0xff, sizeof trustee );
308     pBuildTrusteeWithSidA( &trustee, psid );
309
310     ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
311     ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
312         "MultipleTrusteeOperation wrong\n");
313     ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
314     ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
315     ok( trustee.ptstrName == (LPSTR) psid, "ptstrName wrong\n" );
316
317     /* test BuildTrusteeWithObjectsAndSidA (test 1) */
318     memset( &trustee, 0xff, sizeof trustee );
319     memset( &oas, 0xff, sizeof(oas) );
320     pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
321                                     &InheritedObjectType, psid);
322
323     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
324     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
325     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
326     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
327     ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
328  
329     ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
330     ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
331     ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
332     ok(oas.pSid == psid, "pSid wrong\n");
333
334     /* test GetTrusteeNameA */
335     ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
336
337     /* test BuildTrusteeWithObjectsAndSidA (test 2) */
338     memset( &trustee, 0xff, sizeof trustee );
339     memset( &oas, 0xff, sizeof(oas) );
340     pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
341                                     &InheritedObjectType, psid);
342
343     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
344     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
345     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
346     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
347     ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
348  
349     ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
350     ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
351     ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
352     ok(oas.pSid == psid, "pSid wrong\n");
353
354     FreeSid( psid );
355
356     /* test BuildTrusteeWithNameA */
357     memset( &trustee, 0xff, sizeof trustee );
358     pBuildTrusteeWithNameA( &trustee, szTrusteeName );
359
360     ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
361     ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
362         "MultipleTrusteeOperation wrong\n");
363     ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
364     ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
365     ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
366
367     /* test BuildTrusteeWithObjectsAndNameA (test 1) */
368     memset( &trustee, 0xff, sizeof trustee );
369     memset( &oan, 0xff, sizeof(oan) );
370     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
371                                      szInheritedObjectTypeName, szTrusteeName);
372
373     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
374     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
375     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
376     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
377     ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
378  
379     ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
380     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
381     ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
382     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
383
384     /* test GetTrusteeNameA */
385     ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
386
387     /* test BuildTrusteeWithObjectsAndNameA (test 2) */
388     memset( &trustee, 0xff, sizeof trustee );
389     memset( &oan, 0xff, sizeof(oan) );
390     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
391                                      szInheritedObjectTypeName, szTrusteeName);
392
393     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
394     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
395     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
396     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
397     ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
398  
399     ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
400     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
401     ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
402     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
403
404     /* test BuildTrusteeWithObjectsAndNameA (test 3) */
405     memset( &trustee, 0xff, sizeof trustee );
406     memset( &oan, 0xff, sizeof(oan) );
407     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
408                                      NULL, szTrusteeName);
409
410     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
411     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
412     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
413     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
414     ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
415  
416     ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
417     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
418     ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
419     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
420 }
421  
422 /* If the first isn't defined, assume none is */
423 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
424 #define SE_MIN_WELL_KNOWN_PRIVILEGE       2L
425 #define SE_CREATE_TOKEN_PRIVILEGE         2L
426 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE   3L
427 #define SE_LOCK_MEMORY_PRIVILEGE          4L
428 #define SE_INCREASE_QUOTA_PRIVILEGE       5L
429 #define SE_MACHINE_ACCOUNT_PRIVILEGE      6L
430 #define SE_TCB_PRIVILEGE                  7L
431 #define SE_SECURITY_PRIVILEGE             8L
432 #define SE_TAKE_OWNERSHIP_PRIVILEGE       9L
433 #define SE_LOAD_DRIVER_PRIVILEGE         10L
434 #define SE_SYSTEM_PROFILE_PRIVILEGE      11L
435 #define SE_SYSTEMTIME_PRIVILEGE          12L
436 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
437 #define SE_INC_BASE_PRIORITY_PRIVILEGE   14L
438 #define SE_CREATE_PAGEFILE_PRIVILEGE     15L
439 #define SE_CREATE_PERMANENT_PRIVILEGE    16L
440 #define SE_BACKUP_PRIVILEGE              17L
441 #define SE_RESTORE_PRIVILEGE             18L
442 #define SE_SHUTDOWN_PRIVILEGE            19L
443 #define SE_DEBUG_PRIVILEGE               20L
444 #define SE_AUDIT_PRIVILEGE               21L
445 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE  22L
446 #define SE_CHANGE_NOTIFY_PRIVILLEGE      23L
447 #define SE_REMOTE_SHUTDOWN_PRIVILEGE     24L
448 #define SE_UNDOCK_PRIVILEGE              25L
449 #define SE_SYNC_AGENT_PRIVILEGE          26L
450 #define SE_ENABLE_DELEGATION_PRIVILEGE   27L
451 #define SE_MANAGE_VOLUME_PRIVILEGE       28L
452 #define SE_IMPERSONATE_PRIVILEGE         29L
453 #define SE_CREATE_GLOBAL_PRIVILEGE       30L
454 #define SE_MAX_WELL_KNOWN_PRIVILEGE      SE_CREATE_GLOBAL_PRIVILEGE
455 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
456
457 static void test_allocateLuid(void)
458 {
459     BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
460     LUID luid1, luid2;
461     BOOL ret;
462
463     pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
464     if (!pAllocateLocallyUniqueId) return;
465
466     ret = pAllocateLocallyUniqueId(&luid1);
467     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
468         return;
469
470     ok(ret,
471      "AllocateLocallyUniqueId failed: %d\n", GetLastError());
472     ret = pAllocateLocallyUniqueId(&luid2);
473     ok( ret,
474      "AllocateLocallyUniqueId failed: %d\n", GetLastError());
475     ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
476      "AllocateLocallyUniqueId returned a well-known LUID\n");
477     ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
478      "AllocateLocallyUniqueId returned non-unique LUIDs\n");
479     ret = pAllocateLocallyUniqueId(NULL);
480     ok( !ret && GetLastError() == ERROR_NOACCESS,
481      "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
482      GetLastError());
483 }
484
485 static void test_lookupPrivilegeName(void)
486 {
487     BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
488     char buf[MAX_PATH]; /* arbitrary, seems long enough */
489     DWORD cchName = sizeof(buf);
490     LUID luid = { 0, 0 };
491     LONG i;
492     BOOL ret;
493
494     /* check whether it's available first */
495     pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
496     if (!pLookupPrivilegeNameA) return;
497     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
498     ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
499     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
500         return;
501
502     /* check with a short buffer */
503     cchName = 0;
504     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
505     ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
506     ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
507      "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
508      GetLastError());
509     ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
510      "LookupPrivilegeNameA returned an incorrect required length for\n"
511      "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
512      lstrlenA("SeCreateTokenPrivilege") + 1);
513     /* check a known value and its returned length on success */
514     cchName = sizeof(buf);
515     ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
516      cchName == strlen("SeCreateTokenPrivilege"),
517      "LookupPrivilegeNameA returned an incorrect output length for\n"
518      "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
519      (int)strlen("SeCreateTokenPrivilege"));
520     /* check known values */
521     for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i < SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
522     {
523         luid.LowPart = i;
524         cchName = sizeof(buf);
525         ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
526         ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
527          "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
528     }
529     /* check a bogus LUID */
530     luid.LowPart = 0xdeadbeef;
531     cchName = sizeof(buf);
532     ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
533     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
534      "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
535      GetLastError());
536     /* check on a bogus system */
537     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
538     cchName = sizeof(buf);
539     ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
540     ok( !ret && GetLastError() == RPC_S_SERVER_UNAVAILABLE,
541      "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE: %d\n",
542      GetLastError());
543 }
544
545 struct NameToLUID
546 {
547     const char *name;
548     DWORD lowPart;
549 };
550
551 static void test_lookupPrivilegeValue(void)
552 {
553     static const struct NameToLUID privs[] = {
554      { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
555      { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
556      { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
557      { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
558      { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
559      { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
560      { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
561      { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
562      { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
563      { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
564      { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
565      { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
566      { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
567      { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
568      { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
569      { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
570      { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
571      { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
572      { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
573      { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
574      { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
575      { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILLEGE },
576      { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
577      { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
578      { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
579      { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
580      { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
581      { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
582      { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
583     };
584     BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
585     int i;
586     LUID luid;
587     BOOL ret;
588
589     /* check whether it's available first */
590     pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
591     if (!pLookupPrivilegeValueA) return;
592     ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
593     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
594         return;
595
596     /* check a bogus system name */
597     ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
598     ok( !ret && GetLastError() == RPC_S_SERVER_UNAVAILABLE,
599      "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE: %d\n",
600      GetLastError());
601     /* check a NULL string */
602     ret = pLookupPrivilegeValueA(NULL, 0, &luid);
603     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
604      "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
605      GetLastError());
606     /* check a bogus privilege name */
607     ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
608     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
609      "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
610      GetLastError());
611     /* check case insensitive */
612     ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
613     ok( ret,
614      "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
615      GetLastError());
616     for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
617     {
618         /* Not all privileges are implemented on all Windows versions, so
619          * don't worry if the call fails
620          */
621         if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
622         {
623             ok(luid.LowPart == privs[i].lowPart,
624              "LookupPrivilegeValueA returned an invalid LUID for %s\n",
625              privs[i].name);
626         }
627     }
628 }
629
630 static void test_luid(void)
631 {
632     test_allocateLuid();
633     test_lookupPrivilegeName();
634     test_lookupPrivilegeValue();
635 }
636
637 static void test_FileSecurity(void)
638 {
639     char directory[MAX_PATH];
640     DWORD retval, outSize;
641     BOOL result;
642     BYTE buffer[0x40];
643
644     pGetFileSecurityA = (fnGetFileSecurityA)
645                     GetProcAddress( hmod, "GetFileSecurityA" );
646     if( !pGetFileSecurityA )
647         return;
648
649     retval = GetTempPathA(sizeof(directory), directory);
650     if (!retval) {
651         trace("GetTempPathA failed\n");
652         return;
653     }
654
655     strcpy(directory, "\\Should not exist");
656
657     SetLastError(NO_ERROR);
658     result = pGetFileSecurityA( directory,OWNER_SECURITY_INFORMATION,buffer,0x40,&outSize);
659     ok(!result, "GetFileSecurityA should fail for not existing directories/files\n"); 
660     ok( (GetLastError() == ERROR_FILE_NOT_FOUND ) ||
661         (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) , 
662         "last error ERROR_FILE_NOT_FOUND / ERROR_CALL_NOT_IMPLEMENTED (98) "
663         "expected, got %d\n", GetLastError());
664 }
665
666 static void test_AccessCheck(void)
667 {
668     PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
669     PACL Acl = NULL;
670     SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
671     SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
672     SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
673     GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
674     ACCESS_MASK Access;
675     BOOL AccessStatus;
676     HANDLE Token;
677     HANDLE ProcessToken;
678     BOOL ret;
679     DWORD PrivSetLen;
680     PRIVILEGE_SET *PrivSet;
681     BOOL res;
682     HMODULE NtDllModule;
683     BOOLEAN Enabled;
684     DWORD err;
685
686     NtDllModule = GetModuleHandle("ntdll.dll");
687     if (!NtDllModule)
688     {
689         skip("not running on NT, skipping test\n");
690         return;
691     }
692     pRtlAdjustPrivilege = (fnRtlAdjustPrivilege)
693                           GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
694     if (!pRtlAdjustPrivilege)
695     {
696         skip("missing RtlAdjustPrivilege, skipping test\n");
697         return;
698     }
699
700     Acl = HeapAlloc(GetProcessHeap(), 0, 256);
701     res = InitializeAcl(Acl, 256, ACL_REVISION);
702     if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
703     {
704         skip("ACLs not implemented - skipping tests\n");
705         return;
706     }
707     ok(res, "InitializeAcl failed with error %d\n", GetLastError());
708
709     res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
710     ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
711
712     res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
713         DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
714     ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
715
716     res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
717         DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
718     ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
719
720     res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
721     ok(res, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
722
723     res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
724     ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
725
726     SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
727
728     res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
729     ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
730
731     res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
732     ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
733
734     PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
735     PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
736     PrivSet->PrivilegeCount = 16;
737
738     res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
739     ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
740
741     pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
742
743     res = DuplicateToken(ProcessToken, SecurityIdentification, &Token);
744     ok(res, "DuplicateToken failed with error %d\n", GetLastError());
745
746     /* SD without owner/group */
747     SetLastError(0xdeadbeef);
748     Access = AccessStatus = 0xdeadbeef;
749     ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
750                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
751     err = GetLastError();
752     ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
753        "failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
754     ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
755        "Access and/or AccessStatus were changed!\n");
756
757     /* Set owner and group */
758     res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
759     ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
760     res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
761     ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
762
763     /* Generic access mask */
764     SetLastError(0xdeadbeef);
765     ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
766                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
767     err = GetLastError();
768     ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
769        "with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
770     ok(Access == 0xdeadbeef && AccessStatus == 0xdeadbeef,
771        "Access and/or AccessStatus were changed!\n");
772
773     ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
774                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
775     ok(ret, "AccessCheck failed with error %d\n", GetLastError());
776     ok(AccessStatus && (Access == KEY_READ),
777         "AccessCheck failed to grant access with error %d\n",
778         GetLastError());
779
780     ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
781                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
782     ok(ret, "AccessCheck failed with error %d\n", GetLastError());
783     ok(AccessStatus,
784         "AccessCheck failed to grant any access with error %d\n",
785         GetLastError());
786     trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
787
788     /* Access denied by SD */
789     SetLastError(0xdeadbeef);
790     ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
791                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
792     ok(ret, "AccessCheck failed with error %d\n", GetLastError());
793     err = GetLastError();
794     ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
795        "with ERROR_ACCESS_DENIED, instead of %d\n", err);
796     ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
797
798     SetLastError(0);
799     PrivSet->PrivilegeCount = 16;
800     ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
801                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
802     ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
803         "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
804         GetLastError());
805
806     ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
807     if (!ret)
808     {
809         SetLastError(0);
810         PrivSet->PrivilegeCount = 16;
811         ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
812                           PrivSet, &PrivSetLen, &Access, &AccessStatus);
813         ok(ret && AccessStatus && GetLastError() == 0,
814             "AccessCheck should have succeeded, error %d\n",
815             GetLastError());
816         ok(Access == ACCESS_SYSTEM_SECURITY,
817             "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
818             Access);
819     }
820     else
821         trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
822             ret);
823
824     CloseHandle(Token);
825
826     res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
827     ok(res, "DuplicateToken failed with error %d\n", GetLastError());
828
829     SetLastError(0xdeadbeef);
830     ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
831                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
832     err = GetLastError();
833     ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
834        "with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
835
836     CloseHandle(Token);
837
838     SetLastError(0xdeadbeef);
839     ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
840                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
841     err = GetLastError();
842     ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
843        "with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
844
845     CloseHandle(ProcessToken);
846
847     if (EveryoneSid)
848         FreeSid(EveryoneSid);
849     if (AdminSid)
850         FreeSid(AdminSid);
851     if (UsersSid)
852         FreeSid(UsersSid);
853     HeapFree(GetProcessHeap(), 0, Acl);
854     HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
855     HeapFree(GetProcessHeap(), 0, PrivSet);
856 }
857
858 /* test GetTokenInformation for the various attributes */
859 static void test_token_attr(void)
860 {
861     HANDLE Token, ImpersonationToken;
862     DWORD Size;
863     TOKEN_PRIVILEGES *Privileges;
864     TOKEN_GROUPS *Groups;
865     TOKEN_USER *User;
866     BOOL ret;
867     DWORD i, GLE;
868     LPSTR SidString;
869     SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
870
871     /* cygwin-like use case */
872     SetLastError(0xdeadbeef);
873     ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
874     if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
875     {
876         skip("OpenProcessToken is not implemented\n");
877         return;
878     }
879     ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
880     if (ret)
881     {
882         BYTE buf[1024];
883         Size = sizeof(buf);
884         ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
885         ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
886         Size = sizeof(ImpersonationLevel);
887         ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
888         GLE = GetLastError();
889         ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
890         CloseHandle(Token);
891     }
892
893     if(!pConvertSidToStringSidA)
894     {
895         skip("ConvertSidToStringSidA is not available\n");
896         return;
897     }
898
899     SetLastError(0xdeadbeef);
900     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &Token);
901     ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
902
903     /* groups */
904     ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
905     Groups = HeapAlloc(GetProcessHeap(), 0, Size);
906     ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
907     ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
908     trace("TokenGroups:\n");
909     for (i = 0; i < Groups->GroupCount; i++)
910     {
911         DWORD NameLength = 255;
912         TCHAR Name[255];
913         DWORD DomainLength = 255;
914         TCHAR Domain[255];
915         SID_NAME_USE SidNameUse;
916         pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
917         Name[0] = '\0';
918         Domain[0] = '\0';
919         ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
920         if (ret)
921             trace("\t%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
922         else
923             trace("\t%s, attr: 0x%08x LookupAccountSid failed with error %d\n", SidString, Groups->Groups[i].Attributes, GetLastError());
924         LocalFree(SidString);
925     }
926     HeapFree(GetProcessHeap(), 0, Groups);
927
928     /* user */
929     ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
930     ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
931         "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
932     User = HeapAlloc(GetProcessHeap(), 0, Size);
933     ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
934     ok(ret,
935         "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
936
937     pConvertSidToStringSidA(User->User.Sid, &SidString);
938     trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
939     LocalFree(SidString);
940     HeapFree(GetProcessHeap(), 0, User);
941
942     /* privileges */
943     ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
944     ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
945         "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
946     Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
947     ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
948     ok(ret,
949         "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
950     trace("TokenPrivileges:\n");
951     for (i = 0; i < Privileges->PrivilegeCount; i++)
952     {
953         TCHAR Name[256];
954         DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
955         LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
956         trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
957     }
958     HeapFree(GetProcessHeap(), 0, Privileges);
959
960     ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
961     ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
962
963     Size = sizeof(ImpersonationLevel);
964     ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
965     ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
966     ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
967
968     CloseHandle(ImpersonationToken);
969     CloseHandle(Token);
970 }
971
972 typedef union _MAX_SID
973 {
974     SID sid;
975     char max[SECURITY_MAX_SID_SIZE];
976 } MAX_SID;
977
978 static void test_sid_str(PSID * sid)
979 {
980     char *str_sid;
981     BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
982     ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
983     if (ret)
984     {
985         char account[MAX_PATH], domain[MAX_PATH];
986         SID_NAME_USE use;
987         DWORD acc_size = MAX_PATH;
988         DWORD dom_size = MAX_PATH;
989         ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
990         ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
991            "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
992         if (ret)
993             trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
994         else if (GetLastError() == ERROR_NONE_MAPPED)
995             trace(" %s couldn't be mapped\n", str_sid);
996         LocalFree(str_sid);
997     }
998 }
999
1000 static void test_LookupAccountSid(void)
1001 {
1002     SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
1003     CHAR accountA[MAX_PATH], domainA[MAX_PATH];
1004     DWORD acc_sizeA, dom_sizeA;
1005     DWORD real_acc_sizeA, real_dom_sizeA;
1006     WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
1007     DWORD acc_sizeW, dom_sizeW;
1008     DWORD real_acc_sizeW, real_dom_sizeW;
1009     PSID pUsersSid = NULL;
1010     SID_NAME_USE use;
1011     BOOL ret;
1012     DWORD size;
1013     MAX_SID  max_sid;
1014     CHAR *str_sidA;
1015     int i;
1016
1017     /* native windows crashes if account size, domain size, or name use is NULL */
1018
1019     ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
1020         DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
1021     ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
1022        "AllocateAndInitializeSid failed with error %d\n", GetLastError());
1023
1024     /* not running on NT so give up */
1025     if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1026         return;
1027
1028     real_acc_sizeA = MAX_PATH;
1029     real_dom_sizeA = MAX_PATH;
1030     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
1031     ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1032
1033     /* try NULL account */
1034     acc_sizeA = MAX_PATH;
1035     dom_sizeA = MAX_PATH;
1036     ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1037     ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1038
1039     /* try NULL domain */
1040     acc_sizeA = MAX_PATH;
1041     dom_sizeA = MAX_PATH;
1042     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1043     ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
1044
1045     /* try a small account buffer */
1046     acc_sizeA = 1;
1047     dom_sizeA = MAX_PATH;
1048     accountA[0] = 0;
1049     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1050     ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1051     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1052        "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1053
1054     /* try a 0 sized account buffer */
1055     acc_sizeA = 0;
1056     dom_sizeA = MAX_PATH;
1057     accountA[0] = 0;
1058     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1059     /* this can fail or succeed depending on OS version but the size will always be returned */
1060     ok(acc_sizeA == real_acc_sizeA + 1,
1061        "LookupAccountSidA() Expected acc_size = %u, got %u\n",
1062        real_acc_sizeA + 1, acc_sizeA);
1063
1064     /* try a 0 sized account buffer */
1065     acc_sizeA = 0;
1066     dom_sizeA = MAX_PATH;
1067     ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
1068     /* this can fail or succeed depending on OS version but the size will always be returned */
1069     ok(acc_sizeA == real_acc_sizeA + 1,
1070        "LookupAccountSid() Expected acc_size = %u, got %u\n",
1071        real_acc_sizeA + 1, acc_sizeA);
1072
1073     /* try a small domain buffer */
1074     dom_sizeA = 1;
1075     acc_sizeA = MAX_PATH;
1076     accountA[0] = 0;
1077     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1078     ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
1079     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1080        "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1081
1082     /* try a 0 sized domain buffer */
1083     dom_sizeA = 0;
1084     acc_sizeA = MAX_PATH;
1085     accountA[0] = 0;
1086     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
1087     /* this can fail or succeed depending on OS version but the size will always be returned */
1088     ok(dom_sizeA == real_dom_sizeA + 1,
1089        "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1090        real_dom_sizeA + 1, dom_sizeA);
1091
1092     /* try a 0 sized domain buffer */
1093     dom_sizeA = 0;
1094     acc_sizeA = MAX_PATH;
1095     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
1096     /* this can fail or succeed depending on OS version but the size will always be returned */
1097     ok(dom_sizeA == real_dom_sizeA + 1,
1098        "LookupAccountSidA() Expected dom_size = %u, got %u\n",
1099        real_dom_sizeA + 1, dom_sizeA);
1100
1101     real_acc_sizeW = MAX_PATH;
1102     real_dom_sizeW = MAX_PATH;
1103     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
1104     ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
1105
1106     /* native windows crashes if domainW or accountW is NULL */
1107
1108     /* try a small account buffer */
1109     acc_sizeW = 1;
1110     dom_sizeW = MAX_PATH;
1111     accountW[0] = 0;
1112     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1113     ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1114     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1115        "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1116
1117     /* try a 0 sized account buffer */
1118     acc_sizeW = 0;
1119     dom_sizeW = MAX_PATH;
1120     accountW[0] = 0;
1121     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1122     /* this can fail or succeed depending on OS version but the size will always be returned */
1123     ok(acc_sizeW == real_acc_sizeW + 1,
1124        "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1125        real_acc_sizeW + 1, acc_sizeW);
1126
1127     /* try a 0 sized account buffer */
1128     acc_sizeW = 0;
1129     dom_sizeW = MAX_PATH;
1130     ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1131     /* this can fail or succeed depending on OS version but the size will always be returned */
1132     ok(acc_sizeW == real_acc_sizeW + 1,
1133        "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1134        real_acc_sizeW + 1, acc_sizeW);
1135
1136     /* try a small domain buffer */
1137     dom_sizeW = 1;
1138     acc_sizeW = MAX_PATH;
1139     accountW[0] = 0;
1140     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1141     ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1142     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1143        "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1144
1145     /* try a 0 sized domain buffer */
1146     dom_sizeW = 0;
1147     acc_sizeW = MAX_PATH;
1148     accountW[0] = 0;
1149     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1150     /* this can fail or succeed depending on OS version but the size will always be returned */
1151     ok(dom_sizeW == real_dom_sizeW + 1,
1152        "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1153        real_dom_sizeW + 1, dom_sizeW);
1154
1155     /* try a 0 sized domain buffer */
1156     dom_sizeW = 0;
1157     acc_sizeW = MAX_PATH;
1158     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1159     /* this can fail or succeed depending on OS version but the size will always be returned */
1160     ok(dom_sizeW == real_dom_sizeW + 1,
1161        "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1162        real_dom_sizeW + 1, dom_sizeW);
1163
1164     FreeSid(pUsersSid);
1165
1166     pCreateWellKnownSid = (fnCreateWellKnownSid)GetProcAddress( hmod, "CreateWellKnownSid" );
1167
1168     if (pCreateWellKnownSid && pConvertSidToStringSidA)
1169     {
1170         trace("Well Known SIDs:\n");
1171         for (i = 0; i <= 60; i++)
1172         {
1173             size = SECURITY_MAX_SID_SIZE;
1174             if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
1175             {
1176                 if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1177                 {
1178                     acc_sizeA = MAX_PATH;
1179                     dom_sizeA = MAX_PATH;
1180                     if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
1181                         trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
1182                     LocalFree(str_sidA);
1183                 }
1184             }
1185             else
1186             {
1187                 if (GetLastError() != ERROR_INVALID_PARAMETER)
1188                     trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1189                 else
1190                     trace(" %d: not supported\n", i);
1191             }
1192         }
1193
1194         pLsaQueryInformationPolicy = (fnLsaQueryInformationPolicy)GetProcAddress( hmod, "LsaQueryInformationPolicy");
1195         pLsaOpenPolicy = (fnLsaOpenPolicy)GetProcAddress( hmod, "LsaOpenPolicy");
1196         pLsaFreeMemory = (fnLsaFreeMemory)GetProcAddress( hmod, "LsaFreeMemory");
1197         pLsaClose = (fnLsaClose)GetProcAddress( hmod, "LsaClose");
1198
1199         if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
1200         {
1201             NTSTATUS status;
1202             LSA_HANDLE handle;
1203             LSA_OBJECT_ATTRIBUTES object_attributes;
1204
1205             ZeroMemory(&object_attributes, sizeof(object_attributes));
1206             object_attributes.Length = sizeof(object_attributes);
1207
1208             status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1209             ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1210                "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1211
1212             /* try a more restricted access mask if necessary */
1213             if (status == STATUS_ACCESS_DENIED) {
1214                 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
1215                 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1216                 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
1217             }
1218
1219             if (status == STATUS_SUCCESS)
1220             {
1221                 PPOLICY_ACCOUNT_DOMAIN_INFO info;
1222                 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
1223                 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
1224                 if (status == STATUS_SUCCESS)
1225                 {
1226                     ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
1227                     if (info->DomainSid)
1228                     {
1229                         int count = *GetSidSubAuthorityCount(info->DomainSid);
1230                         CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
1231                         test_sid_str((PSID)&max_sid.sid);
1232                         max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
1233                         max_sid.sid.SubAuthorityCount = count + 1;
1234                         test_sid_str((PSID)&max_sid.sid);
1235                         max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
1236                         test_sid_str((PSID)&max_sid.sid);
1237                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
1238                         test_sid_str((PSID)&max_sid.sid);
1239                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
1240                         test_sid_str((PSID)&max_sid.sid);
1241                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
1242                         test_sid_str((PSID)&max_sid.sid);
1243                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
1244                         test_sid_str((PSID)&max_sid.sid);
1245                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
1246                         test_sid_str((PSID)&max_sid.sid);
1247                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
1248                         test_sid_str((PSID)&max_sid.sid);
1249                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
1250                         test_sid_str((PSID)&max_sid.sid);
1251                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
1252                         test_sid_str((PSID)&max_sid.sid);
1253                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
1254                         test_sid_str((PSID)&max_sid.sid);
1255                         max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
1256                         test_sid_str((PSID)&max_sid.sid);
1257                         max_sid.sid.SubAuthority[count] = 1000; /* first user account */
1258                         test_sid_str((PSID)&max_sid.sid);
1259                     }
1260
1261                     pLsaFreeMemory((LPVOID)info);
1262                 }
1263
1264                 status = pLsaClose(handle);
1265                 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
1266             }
1267         }
1268     }
1269 }
1270
1271 static void get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
1272 {
1273     static CHAR account[UNLEN + 1];
1274     static CHAR domain[UNLEN + 1];
1275     DWORD size, dom_size;
1276     SID_NAME_USE use;
1277
1278     *user = account;
1279     *dom = domain;
1280
1281     size = dom_size = UNLEN + 1;
1282     account[0] = '\0';
1283     domain[0] = '\0';
1284     LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
1285 }
1286
1287 static void test_LookupAccountName(void)
1288 {
1289     DWORD sid_size, domain_size, user_size;
1290     DWORD sid_save, domain_save;
1291     CHAR user_name[UNLEN + 1];
1292     SID_NAME_USE sid_use;
1293     LPSTR domain, account, sid_dom;
1294     PSID psid;
1295     BOOL ret;
1296
1297     /* native crashes if (assuming all other parameters correct):
1298      *  - peUse is NULL
1299      *  - Sid is NULL and cbSid is > 0
1300      *  - cbSid or cchReferencedDomainName are NULL
1301      *  - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
1302      */
1303
1304     user_size = UNLEN + 1;
1305     SetLastError(0xdeadbeef);
1306     ret = GetUserNameA(user_name, &user_size);
1307     if (!ret && (GetLastError() == ERROR_NOT_LOGGED_ON))
1308     {
1309         /* Probably on win9x where the user used 'Cancel' instead of properly logging in */
1310         skip("Cannot get the user name (win9x and not logged in properly)\n");
1311         return;
1312     }
1313     ok(ret, "Failed to get user name : %d\n", GetLastError());
1314
1315     /* get sizes */
1316     sid_size = 0;
1317     domain_size = 0;
1318     sid_use = 0xcafebabe;
1319     SetLastError(0xdeadbeef);
1320     ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
1321     if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1322     {
1323         skip("LookupAccountNameA is not implemented\n");
1324         return;
1325     }
1326     ok(!ret, "Expected 0, got %d\n", ret);
1327     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1328        "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1329     ok(sid_size != 0, "Expected non-zero sid size\n");
1330     ok(domain_size != 0, "Expected non-zero domain size\n");
1331     ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1332
1333     sid_save = sid_size;
1334     domain_save = domain_size;
1335
1336     psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1337     domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1338
1339     /* try valid account name */
1340     ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
1341     get_sid_info(psid, &account, &sid_dom);
1342     ok(ret, "Failed to lookup account name\n");
1343     ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
1344     todo_wine
1345     {
1346         ok(!lstrcmp(account, user_name), "Expected %s, got %s\n", user_name, account);
1347         ok(!lstrcmp(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
1348         ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
1349         ok(lstrlen(domain) == domain_size, "Expected %d\n", lstrlen(domain));
1350         ok(sid_use == SidTypeUser, "Expected SidTypeUser, got %d\n", SidTypeUser);
1351     }
1352     domain_size = domain_save;
1353
1354     /* NULL Sid with zero sid size */
1355     SetLastError(0xdeadbeef);
1356     sid_size = 0;
1357     ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1358     ok(!ret, "Expected 0, got %d\n", ret);
1359     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1360        "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1361     ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1362     ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1363
1364     /* try cchReferencedDomainName - 1 */
1365     SetLastError(0xdeadbeef);
1366     domain_size--;
1367     ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
1368     ok(!ret, "Expected 0, got %d\n", ret);
1369     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1370        "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1371     ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1372     ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1373
1374     /* NULL ReferencedDomainName with zero domain name size */
1375     SetLastError(0xdeadbeef);
1376     domain_size = 0;
1377     ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
1378     ok(!ret, "Expected 0, got %d\n", ret);
1379     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1380        "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1381     ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
1382     ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
1383
1384     HeapFree(GetProcessHeap(), 0, psid);
1385     HeapFree(GetProcessHeap(), 0, domain);
1386
1387     /* get sizes for NULL account name */
1388     sid_size = 0;
1389     domain_size = 0;
1390     sid_use = 0xcafebabe;
1391     SetLastError(0xdeadbeef);
1392     ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
1393     ok(!ret, "Expected 0, got %d\n", ret);
1394     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1395        "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
1396     ok(sid_size != 0, "Expected non-zero sid size\n");
1397     ok(domain_size != 0, "Expected non-zero domain size\n");
1398     ok(sid_use == 0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
1399
1400     psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
1401     domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
1402
1403     /* try NULL account name */
1404     ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
1405     get_sid_info(psid, &account, &sid_dom);
1406     ok(ret, "Failed to lookup account name\n");
1407     todo_wine
1408     {
1409         ok(!lstrcmp(account, "BUILTIN"), "Expected BUILTIN, got %s\n", account);
1410         ok(!lstrcmp(domain, "BUILTIN"), "Expected BUILTIN, got %s\n", domain);
1411         ok(sid_use == SidTypeDomain, "Expected SidTypeDomain, got %d\n", SidTypeDomain);
1412     }
1413
1414     /* try an invalid account name */
1415     SetLastError(0xdeadbeef);
1416     sid_size = 0;
1417     domain_size = 0;
1418     ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
1419     ok(!ret, "Expected 0, got %d\n", ret);
1420     todo_wine
1421     {
1422         ok(GetLastError() == ERROR_NONE_MAPPED,
1423            "Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
1424         ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
1425         ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
1426     }
1427
1428     HeapFree(GetProcessHeap(), 0, psid);
1429     HeapFree(GetProcessHeap(), 0, domain);
1430 }
1431
1432 #define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,__LINE__)
1433 static void test_granted_access(HANDLE handle, ACCESS_MASK access, int line)
1434 {
1435     OBJECT_BASIC_INFORMATION obj_info;
1436     NTSTATUS status;
1437
1438     if (!pNtQueryObject)
1439     {
1440         skip_(__FILE__, line)("Not NT platform - skipping tests\n");
1441         return;
1442     }
1443
1444     status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
1445                              sizeof(obj_info), NULL );
1446     ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
1447     ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
1448         "be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
1449 }
1450
1451 #define CHECK_SET_SECURITY(o,i,e) \
1452     do{ \
1453         BOOL res; \
1454         DWORD err; \
1455         SetLastError( 0xdeadbeef ); \
1456         res = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
1457         err = GetLastError(); \
1458         if (e == ERROR_SUCCESS) \
1459             ok(res, "SetKernelObjectSecurity failed with %d\n", err); \
1460         else \
1461             ok(!res && err == e, "SetKernelObjectSecurity should have failed " \
1462                "with %s, instead of %d\n", #e, err); \
1463     }while(0)
1464
1465 static void test_process_security(void)
1466 {
1467     BOOL res;
1468     char owner[32], group[32];
1469     PSID AdminSid = NULL, UsersSid = NULL;
1470     PACL Acl = NULL;
1471     SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
1472     char buffer[MAX_PATH];
1473     PROCESS_INFORMATION info;
1474     STARTUPINFOA startup;
1475     SECURITY_ATTRIBUTES psa;
1476     HANDLE token, event;
1477     DWORD tmp;
1478
1479     Acl = HeapAlloc(GetProcessHeap(), 0, 256);
1480     res = InitializeAcl(Acl, 256, ACL_REVISION);
1481     if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1482     {
1483         skip("ACLs not implemented - skipping tests\n");
1484         return;
1485     }
1486     ok(res, "InitializeAcl failed with error %d\n", GetLastError());
1487
1488     /* get owner from the token we might be running as a user not admin */
1489     res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
1490     ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
1491     if (!res) return;
1492
1493     res = GetTokenInformation( token, TokenOwner, owner, sizeof(owner), &tmp );
1494     ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
1495     AdminSid = ((TOKEN_OWNER*)owner)->Owner;
1496     res = GetTokenInformation( token, TokenPrimaryGroup, group, sizeof(group), &tmp );
1497     ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
1498     UsersSid = ((TOKEN_PRIMARY_GROUP*)group)->PrimaryGroup;
1499
1500     CloseHandle( token );
1501     if (!res) return;
1502
1503     res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
1504     ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
1505     res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
1506     ok(res, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
1507
1508     SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
1509     res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
1510     ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
1511
1512     event = CreateEvent( NULL, TRUE, TRUE, "test_event" );
1513     ok(event != NULL, "CreateEvent %d\n", GetLastError());
1514
1515     SecurityDescriptor->Revision = 0;
1516     CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
1517     SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
1518
1519     CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
1520     CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
1521     CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
1522     CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
1523     /* NULL DACL is valid and means default DACL from token */
1524     SecurityDescriptor->Control |= SE_DACL_PRESENT;
1525     CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
1526
1527     /* Set owner and group and dacl */
1528     res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
1529     ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
1530     CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
1531     res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
1532     ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
1533     CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
1534     res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
1535     ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
1536     CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
1537
1538     sprintf(buffer, "%s tests/security.c test", myARGV[0]);
1539     memset(&startup, 0, sizeof(startup));
1540     startup.cb = sizeof(startup);
1541     startup.dwFlags = STARTF_USESHOWWINDOW;
1542     startup.wShowWindow = SW_SHOWNORMAL;
1543
1544     psa.nLength = sizeof(psa);
1545     psa.lpSecurityDescriptor = SecurityDescriptor;
1546     psa.bInheritHandle = TRUE;
1547
1548     /* Doesn't matter what ACL say we should get full access for ourselves */
1549     ok(CreateProcessA( NULL, buffer, &psa, NULL, FALSE, 0, NULL, NULL, &startup, &info ),
1550         "CreateProcess with err:%d\n", GetLastError());
1551     TEST_GRANTED_ACCESS( info.hProcess, PROCESS_ALL_ACCESS );
1552     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1553
1554     CloseHandle( event );
1555     HeapFree(GetProcessHeap(), 0, Acl);
1556     HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
1557 }
1558
1559 static void test_process_security_child(void)
1560 {
1561     HANDLE handle, handle1;
1562     BOOL ret;
1563     DWORD err;
1564
1565     handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
1566     ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
1567     TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
1568
1569     ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
1570                         &handle1, 0, TRUE, DUPLICATE_SAME_ACCESS ),
1571        "duplicating handle err:%d\n", GetLastError());
1572     TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
1573
1574     CloseHandle( handle1 );
1575
1576     SetLastError( 0xdeadbeef );
1577     ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
1578                            &handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
1579     err = GetLastError();
1580     todo_wine
1581     ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
1582        "with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
1583
1584     CloseHandle( handle );
1585
1586     /* These two should fail - they are denied by ACL */
1587     handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
1588     todo_wine
1589     ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
1590     handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
1591     todo_wine
1592     ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
1593
1594     /* Documented privilege elevation */
1595     ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
1596                         &handle, 0, TRUE, DUPLICATE_SAME_ACCESS ),
1597        "duplicating handle err:%d\n", GetLastError());
1598     TEST_GRANTED_ACCESS( handle, PROCESS_ALL_ACCESS );
1599
1600     CloseHandle( handle );
1601
1602     /* Same only explicitly asking for all access rights */
1603     ok(DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
1604                         &handle, PROCESS_ALL_ACCESS, TRUE, 0 ),
1605        "duplicating handle err:%d\n", GetLastError());
1606     TEST_GRANTED_ACCESS( handle, PROCESS_ALL_ACCESS );
1607     ok(DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
1608                         &handle1, PROCESS_VM_READ, TRUE, 0 ),
1609        "duplicating handle err:%d\n", GetLastError());
1610     TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
1611     CloseHandle( handle1 );
1612     CloseHandle( handle );
1613 }
1614
1615 static void test_impersonation_level(void)
1616 {
1617     HANDLE Token, ProcessToken;
1618     HANDLE Token2;
1619     DWORD Size;
1620     TOKEN_PRIVILEGES *Privileges;
1621     TOKEN_USER *User;
1622     PRIVILEGE_SET *PrivilegeSet;
1623     BOOL AccessGranted;
1624     BOOL ret;
1625     HKEY hkey;
1626     DWORD error;
1627
1628     pDuplicateTokenEx = (fnDuplicateTokenEx) GetProcAddress(hmod, "DuplicateTokenEx");
1629     if( !pDuplicateTokenEx ) {
1630         skip("DuplicateTokenEx is not available\n");
1631         return;
1632     }
1633     SetLastError(0xdeadbeef);
1634     ret = ImpersonateSelf(SecurityAnonymous);
1635     if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1636     {
1637         skip("ImpersonateSelf is not implemented\n");
1638         return;
1639     }
1640     ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
1641     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
1642     ok(!ret, "OpenThreadToken should have failed\n");
1643     error = GetLastError();
1644     ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
1645     /* can't perform access check when opening object against an anonymous impersonation token */
1646     todo_wine {
1647     error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
1648     ok(error == ERROR_INVALID_HANDLE, "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE instead of %d\n", error);
1649     }
1650     RevertToSelf();
1651
1652     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
1653     ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1654
1655     ret = pDuplicateTokenEx(ProcessToken,
1656         TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
1657         SecurityAnonymous, TokenImpersonation, &Token);
1658     ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
1659     /* can't increase the impersonation level */
1660     ret = DuplicateToken(Token, SecurityIdentification, &Token2);
1661     error = GetLastError();
1662     ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
1663         "Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
1664     /* we can query anything from an anonymous token, including the user */
1665     ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
1666     error = GetLastError();
1667     ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
1668     User = (TOKEN_USER *)HeapAlloc(GetProcessHeap(), 0, Size);
1669     ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
1670     ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
1671     HeapFree(GetProcessHeap(), 0, User);
1672
1673     /* PrivilegeCheck fails with SecurityAnonymous level */
1674     ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
1675     error = GetLastError();
1676     ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
1677     Privileges = (TOKEN_PRIVILEGES *)HeapAlloc(GetProcessHeap(), 0, Size);
1678     ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
1679     ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
1680
1681     PrivilegeSet = (PRIVILEGE_SET *)HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
1682     PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
1683     memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
1684     PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
1685     HeapFree(GetProcessHeap(), 0, Privileges);
1686
1687     ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
1688     error = GetLastError();
1689     ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
1690
1691     CloseHandle(Token);
1692
1693     ret = ImpersonateSelf(SecurityIdentification);
1694     ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
1695     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
1696     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
1697
1698     /* can't perform access check when opening object against an identification impersonation token */
1699     error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
1700     todo_wine {
1701     ok(error == ERROR_INVALID_HANDLE, "RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE instead of %d\n", error);
1702     }
1703     ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
1704     ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
1705     CloseHandle(Token);
1706     RevertToSelf();
1707
1708     ret = ImpersonateSelf(SecurityImpersonation);
1709     ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
1710     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
1711     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
1712     error = RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
1713     ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
1714     RegCloseKey(hkey);
1715     ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
1716     ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
1717     RevertToSelf();
1718
1719     CloseHandle(Token);
1720     CloseHandle(ProcessToken);
1721
1722     HeapFree(GetProcessHeap(), 0, PrivilegeSet);
1723 }
1724
1725 static void test_SetEntriesInAcl(void)
1726 {
1727     ACL *acl = (ACL*)0xdeadbeef;
1728     DWORD res;
1729
1730     if (!pSetEntriesInAclW)
1731     {
1732         skip("SetEntriesInAclW is not available\n");
1733         return;
1734     }
1735
1736     res = pSetEntriesInAclW(0, NULL, NULL, &acl);
1737     if(res == ERROR_CALL_NOT_IMPLEMENTED)
1738     {
1739         skip("SetEntriesInAclW is not implemented\n");
1740         return;
1741     }
1742     ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
1743     ok(acl == NULL, "acl=%p, expected NULL\n", acl);
1744 }
1745
1746 static void test_GetNamedSecurityInfoA(void)
1747 {
1748     PSECURITY_DESCRIPTOR pSecDesc;
1749     DWORD revision;
1750     SECURITY_DESCRIPTOR_CONTROL control;
1751     PSID owner;
1752     PSID group;
1753     BOOL owner_defaulted;
1754     BOOL group_defaulted;
1755     DWORD error;
1756     BOOL ret;
1757     CHAR windows_dir[MAX_PATH];
1758
1759     if (!pGetNamedSecurityInfoA)
1760     {
1761         skip("GetNamedSecurityInfoA is not available\n");
1762         return;
1763     }
1764
1765     ret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
1766     ok(ret, "GetWindowsDirectory failed with error %d\n", GetLastError());
1767
1768     SetLastError(0xdeadbeef);
1769     error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
1770         OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
1771         NULL, NULL, NULL, NULL, &pSecDesc);
1772     if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
1773     {
1774         skip("GetNamedSecurityInfoA is not implemented\n");
1775         return;
1776     }
1777     ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
1778
1779     ret = GetSecurityDescriptorControl(pSecDesc, &control, &revision);
1780     ok(ret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
1781     ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT),
1782         "control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
1783     ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
1784     ret = GetSecurityDescriptorOwner(pSecDesc, &owner, &owner_defaulted);
1785     ok(ret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
1786     ok(owner != NULL, "owner should not be NULL\n");
1787     ret = GetSecurityDescriptorGroup(pSecDesc, &group, &group_defaulted);
1788     ok(ret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
1789     ok(group != NULL, "group should not be NULL\n");
1790 }
1791
1792 static void test_ConvertStringSecurityDescriptor(void)
1793 {
1794     BOOL ret;
1795     PSECURITY_DESCRIPTOR pSD;
1796
1797     if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
1798     {
1799         skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
1800         return;
1801     }
1802
1803     SetLastError(0xdeadbeef);
1804     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1805         "D:(A;;GA;;;WD)", 0xdeadbeef, &pSD, NULL);
1806     ok(!ret && GetLastError() == ERROR_UNKNOWN_REVISION,
1807         "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_UNKNOWN_REVISION instead of %d\n",
1808         GetLastError());
1809
1810     /* test ACE string type */
1811     SetLastError(0xdeadbeef);
1812     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1813         "D:(A;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1814     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1815     LocalFree(pSD);
1816
1817     SetLastError(0xdeadbeef);
1818     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1819         "D:(D;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1820     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1821     LocalFree(pSD);
1822
1823     SetLastError(0xdeadbeef);
1824     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1825         "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1826     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1827         "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
1828         GetLastError());
1829
1830     /* test ACE string access rights */
1831     SetLastError(0xdeadbeef);
1832     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1833         "D:(A;;GA;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1834     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1835     LocalFree(pSD);
1836     SetLastError(0xdeadbeef);
1837     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1838         "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1839     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1840     LocalFree(pSD);
1841     SetLastError(0xdeadbeef);
1842     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1843         "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1844     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1845     LocalFree(pSD);
1846     SetLastError(0xdeadbeef);
1847     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1848         "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1849     todo_wine
1850     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1851     LocalFree(pSD);
1852     SetLastError(0xdeadbeef);
1853     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1854         "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1855     todo_wine
1856     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1857     LocalFree(pSD);
1858     SetLastError(0xdeadbeef);
1859     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1860         "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1861     todo_wine
1862     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1863     LocalFree(pSD);
1864     SetLastError(0xdeadbeef);
1865     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1866         "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1867     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1868     LocalFree(pSD);
1869
1870     /* test ACE string access right error case */
1871     SetLastError(0xdeadbeef);
1872     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1873         "D:(A;;ROB;;;WD)", SDDL_REVISION_1, &pSD, NULL);
1874     todo_wine
1875     ok(!ret && GetLastError() == ERROR_INVALID_ACL,
1876         "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_ACL instead of %d\n",
1877         GetLastError());
1878
1879     /* test ACE string SID */
1880     SetLastError(0xdeadbeef);
1881     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1882         "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, &pSD, NULL);
1883     ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
1884     LocalFree(pSD);
1885
1886     SetLastError(0xdeadbeef);
1887     ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
1888         "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, &pSD, NULL);
1889     todo_wine
1890     ok(!ret && GetLastError() == ERROR_INVALID_ACL,
1891         "ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_ACL instead of %d\n",
1892         GetLastError());
1893 }
1894
1895 START_TEST(security)
1896 {
1897     init();
1898     if (!hmod) return;
1899
1900     if (myARGC >= 3)
1901     {
1902         test_process_security_child();
1903         return;
1904     }
1905     test_sid();
1906     test_trustee();
1907     test_luid();
1908     test_FileSecurity();
1909     test_AccessCheck();
1910     test_token_attr();
1911     test_LookupAccountSid();
1912     test_LookupAccountName();
1913     test_process_security();
1914     test_impersonation_level();
1915     test_SetEntriesInAcl();
1916     test_GetNamedSecurityInfoA();
1917     test_ConvertStringSecurityDescriptor();
1918 }