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