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