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