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