janitorial: Remove remaining NULL checks before free() (found by Smatch).
[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 "winternl.h"
32 #include "sddl.h"
33 #include "ntsecapi.h"
34
35 #include "wine/test.h"
36
37 typedef VOID (WINAPI *fnBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
38 typedef VOID (WINAPI *fnBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
39 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
40                                                           POBJECTS_AND_NAME_A pObjName,
41                                                           SE_OBJECT_TYPE ObjectType,
42                                                           LPSTR ObjectTypeName,
43                                                           LPSTR InheritedObjectTypeName,
44                                                           LPSTR Name );
45 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
46                                                          POBJECTS_AND_SID pObjSid,
47                                                          GUID* pObjectGuid,
48                                                          GUID* pInheritedObjectGuid,
49                                                          PSID pSid );
50 typedef LPSTR (WINAPI *fnGetTrusteeNameA)( PTRUSTEEA pTrustee );
51 typedef BOOL (WINAPI *fnConvertSidToStringSidA)( PSID pSid, LPSTR *str );
52 typedef BOOL (WINAPI *fnConvertStringSidToSidA)( LPCSTR str, PSID pSid );
53 typedef BOOL (WINAPI *fnGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
54                                           PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
55 typedef DWORD (WINAPI *fnRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
56 typedef BOOL (WINAPI *fnCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
57
58 typedef NTSTATUS (WINAPI *fnLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
59 typedef NTSTATUS (WINAPI *fnLsaClose)(LSA_HANDLE);
60 typedef NTSTATUS (WINAPI *fnLsaFreeMemory)(PVOID);
61 typedef NTSTATUS (WINAPI *fnLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
62
63 static HMODULE hmod;
64
65 fnBuildTrusteeWithSidA   pBuildTrusteeWithSidA;
66 fnBuildTrusteeWithNameA  pBuildTrusteeWithNameA;
67 fnBuildTrusteeWithObjectsAndNameA pBuildTrusteeWithObjectsAndNameA;
68 fnBuildTrusteeWithObjectsAndSidA pBuildTrusteeWithObjectsAndSidA;
69 fnGetTrusteeNameA pGetTrusteeNameA;
70 fnConvertSidToStringSidA pConvertSidToStringSidA;
71 fnConvertStringSidToSidA pConvertStringSidToSidA;
72 fnGetFileSecurityA pGetFileSecurityA;
73 fnRtlAdjustPrivilege pRtlAdjustPrivilege;
74 fnCreateWellKnownSid pCreateWellKnownSid;
75 fnLsaQueryInformationPolicy pLsaQueryInformationPolicy;
76 fnLsaClose pLsaClose;
77 fnLsaFreeMemory pLsaFreeMemory;
78 fnLsaOpenPolicy pLsaOpenPolicy;
79
80 struct sidRef
81 {
82     SID_IDENTIFIER_AUTHORITY auth;
83     const char *refStr;
84 };
85
86 static void init(void)
87 {
88     hmod = GetModuleHandle("advapi32.dll");
89 }
90
91 static void test_str_sid(const char *str_sid)
92 {
93     PSID psid;
94     char *temp;
95
96     if (pConvertStringSidToSidA(str_sid, &psid))
97     {
98         if (pConvertSidToStringSidA(psid, &temp))
99         {
100             trace(" %s: %s\n", str_sid, temp);
101             LocalFree(temp);
102         }
103     }
104     else
105     {
106         if (GetLastError() != ERROR_INVALID_SID)
107             trace(" %s: couldn't be converted, returned %d\n", str_sid, GetLastError());
108         else
109             trace(" %s: couldn't be converted\n", str_sid);
110     }
111 }
112
113 static void test_sid(void)
114 {
115     struct sidRef refs[] = {
116      { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
117      { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1"  },
118      { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1"     },
119      { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1"       },
120      { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1"         },
121      { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1"        },
122     };
123     const char noSubAuthStr[] = "S-1-5";
124     unsigned int i;
125     PSID psid = NULL;
126     BOOL r;
127     LPSTR str = NULL;
128
129     pConvertSidToStringSidA = (fnConvertSidToStringSidA)
130                     GetProcAddress( hmod, "ConvertSidToStringSidA" );
131     if( !pConvertSidToStringSidA )
132         return;
133     pConvertStringSidToSidA = (fnConvertStringSidToSidA)
134                     GetProcAddress( hmod, "ConvertStringSidToSidA" );
135     if( !pConvertStringSidToSidA )
136         return;
137
138     r = pConvertStringSidToSidA( NULL, NULL );
139     ok( !r, "expected failure with NULL parameters\n" );
140     if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
141         return;
142     ok( GetLastError() == ERROR_INVALID_PARAMETER,
143      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
144      GetLastError() );
145
146     r = pConvertStringSidToSidA( refs[0].refStr, NULL );
147     ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
148      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
149      GetLastError() );
150
151     r = pConvertStringSidToSidA( NULL, &str );
152     ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
153      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
154      GetLastError() );
155
156     r = pConvertStringSidToSidA( noSubAuthStr, &psid );
157     ok( !r,
158      "expected failure with no sub authorities\n" );
159     ok( GetLastError() == ERROR_INVALID_SID,
160      "expected GetLastError() is ERROR_INVALID_SID, got %d\n",
161      GetLastError() );
162
163     for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
164     {
165         PISID pisid;
166
167         r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
168          &psid );
169         ok( r, "failed to allocate sid\n" );
170         r = pConvertSidToStringSidA( psid, &str );
171         ok( r, "failed to convert sid\n" );
172         if (r)
173         {
174             ok( !strcmp( str, refs[i].refStr ),
175                 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
176             LocalFree( str );
177         }
178         if( psid )
179             FreeSid( psid );
180
181         r = pConvertStringSidToSidA( refs[i].refStr, &psid );
182         ok( r, "failed to parse sid string\n" );
183         pisid = (PISID)psid;
184         ok( pisid &&
185          !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
186          sizeof(refs[i].auth) ),
187          "string sid %s didn't parse to expected value\n"
188          "(got 0x%04x%08x, expected 0x%04x%08x)\n",
189          refs[i].refStr,
190          MAKEWORD( pisid->IdentifierAuthority.Value[1],
191          pisid->IdentifierAuthority.Value[0] ),
192          MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
193          pisid->IdentifierAuthority.Value[4] ),
194          MAKEWORD( pisid->IdentifierAuthority.Value[3],
195          pisid->IdentifierAuthority.Value[2] ) ),
196          MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
197          MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
198          MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
199         if( psid )
200             LocalFree( psid );
201     }
202
203     trace("String SIDs:\n");
204     test_str_sid("AO");
205     test_str_sid("RU");
206     test_str_sid("AN");
207     test_str_sid("AU");
208     test_str_sid("BA");
209     test_str_sid("BG");
210     test_str_sid("BO");
211     test_str_sid("BU");
212     test_str_sid("CA");
213     test_str_sid("CG");
214     test_str_sid("CO");
215     test_str_sid("DA");
216     test_str_sid("DC");
217     test_str_sid("DD");
218     test_str_sid("DG");
219     test_str_sid("DU");
220     test_str_sid("EA");
221     test_str_sid("ED");
222     test_str_sid("WD");
223     test_str_sid("PA");
224     test_str_sid("IU");
225     test_str_sid("LA");
226     test_str_sid("LG");
227     test_str_sid("LS");
228     test_str_sid("SY");
229     test_str_sid("NU");
230     test_str_sid("NO");
231     test_str_sid("NS");
232     test_str_sid("PO");
233     test_str_sid("PS");
234     test_str_sid("PU");
235     test_str_sid("RS");
236     test_str_sid("RD");
237     test_str_sid("RE");
238     test_str_sid("RC");
239     test_str_sid("SA");
240     test_str_sid("SO");
241     test_str_sid("SU");
242 }
243
244 static void test_trustee(void)
245 {
246     GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
247     GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
248     GUID ZeroGuid;
249     OBJECTS_AND_NAME_ oan;
250     OBJECTS_AND_SID oas;
251     TRUSTEE trustee;
252     PSID psid;
253     char szObjectTypeName[] = "ObjectTypeName";
254     char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
255     char szTrusteeName[] = "szTrusteeName";
256     SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
257
258     memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
259
260     pBuildTrusteeWithSidA = (fnBuildTrusteeWithSidA)
261                     GetProcAddress( hmod, "BuildTrusteeWithSidA" );
262     pBuildTrusteeWithNameA = (fnBuildTrusteeWithNameA)
263                     GetProcAddress( hmod, "BuildTrusteeWithNameA" );
264     pBuildTrusteeWithObjectsAndNameA = (fnBuildTrusteeWithObjectsAndNameA)
265                     GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
266     pBuildTrusteeWithObjectsAndSidA = (fnBuildTrusteeWithObjectsAndSidA)
267                     GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
268     pGetTrusteeNameA = (fnGetTrusteeNameA)
269                     GetProcAddress (hmod, "GetTrusteeNameA" );
270     if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
271         !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
272         !pGetTrusteeNameA )
273         return;
274
275     if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
276     {
277         trace( "failed to init SID\n" );
278        return;
279     }
280
281     /* test BuildTrusteeWithSidA */
282     memset( &trustee, 0xff, sizeof trustee );
283     pBuildTrusteeWithSidA( &trustee, psid );
284
285     ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
286     ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
287         "MultipleTrusteeOperation wrong\n");
288     ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
289     ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
290     ok( trustee.ptstrName == (LPSTR) psid, "ptstrName wrong\n" );
291
292     /* test BuildTrusteeWithObjectsAndSidA (test 1) */
293     memset( &trustee, 0xff, sizeof trustee );
294     memset( &oas, 0xff, sizeof(oas) );
295     pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
296                                     &InheritedObjectType, psid);
297
298     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
299     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
300     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
301     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
302     ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
303  
304     ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
305     ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
306     ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
307     ok(oas.pSid == psid, "pSid wrong\n");
308
309     /* test GetTrusteeNameA */
310     ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
311
312     /* test BuildTrusteeWithObjectsAndSidA (test 2) */
313     memset( &trustee, 0xff, sizeof trustee );
314     memset( &oas, 0xff, sizeof(oas) );
315     pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
316                                     &InheritedObjectType, psid);
317
318     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
319     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
320     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
321     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
322     ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
323  
324     ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
325     ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
326     ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
327     ok(oas.pSid == psid, "pSid wrong\n");
328
329     FreeSid( psid );
330
331     /* test BuildTrusteeWithNameA */
332     memset( &trustee, 0xff, sizeof trustee );
333     pBuildTrusteeWithNameA( &trustee, szTrusteeName );
334
335     ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
336     ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
337         "MultipleTrusteeOperation wrong\n");
338     ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
339     ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
340     ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
341
342     /* test BuildTrusteeWithObjectsAndNameA (test 1) */
343     memset( &trustee, 0xff, sizeof trustee );
344     memset( &oan, 0xff, sizeof(oan) );
345     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
346                                      szInheritedObjectTypeName, szTrusteeName);
347
348     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
349     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
350     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
351     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
352     ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
353  
354     ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
355     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
356     ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
357     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
358
359     /* test GetTrusteeNameA */
360     ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
361
362     /* test BuildTrusteeWithObjectsAndNameA (test 2) */
363     memset( &trustee, 0xff, sizeof trustee );
364     memset( &oan, 0xff, sizeof(oan) );
365     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
366                                      szInheritedObjectTypeName, szTrusteeName);
367
368     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
369     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
370     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
371     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
372     ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
373  
374     ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
375     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
376     ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
377     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
378
379     /* test BuildTrusteeWithObjectsAndNameA (test 3) */
380     memset( &trustee, 0xff, sizeof trustee );
381     memset( &oan, 0xff, sizeof(oan) );
382     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
383                                      NULL, szTrusteeName);
384
385     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
386     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
387     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
388     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
389     ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
390  
391     ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
392     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
393     ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
394     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
395 }
396  
397 /* If the first isn't defined, assume none is */
398 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
399 #define SE_MIN_WELL_KNOWN_PRIVILEGE       2L
400 #define SE_CREATE_TOKEN_PRIVILEGE         2L
401 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE   3L
402 #define SE_LOCK_MEMORY_PRIVILEGE          4L
403 #define SE_INCREASE_QUOTA_PRIVILEGE       5L
404 #define SE_MACHINE_ACCOUNT_PRIVILEGE      6L
405 #define SE_TCB_PRIVILEGE                  7L
406 #define SE_SECURITY_PRIVILEGE             8L
407 #define SE_TAKE_OWNERSHIP_PRIVILEGE       9L
408 #define SE_LOAD_DRIVER_PRIVILEGE         10L
409 #define SE_SYSTEM_PROFILE_PRIVILEGE      11L
410 #define SE_SYSTEMTIME_PRIVILEGE          12L
411 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
412 #define SE_INC_BASE_PRIORITY_PRIVILEGE   14L
413 #define SE_CREATE_PAGEFILE_PRIVILEGE     15L
414 #define SE_CREATE_PERMANENT_PRIVILEGE    16L
415 #define SE_BACKUP_PRIVILEGE              17L
416 #define SE_RESTORE_PRIVILEGE             18L
417 #define SE_SHUTDOWN_PRIVILEGE            19L
418 #define SE_DEBUG_PRIVILEGE               20L
419 #define SE_AUDIT_PRIVILEGE               21L
420 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE  22L
421 #define SE_CHANGE_NOTIFY_PRIVILLEGE      23L
422 #define SE_REMOTE_SHUTDOWN_PRIVILEGE     24L
423 #define SE_UNDOCK_PRIVILEGE              25L
424 #define SE_SYNC_AGENT_PRIVILEGE          26L
425 #define SE_ENABLE_DELEGATION_PRIVILEGE   27L
426 #define SE_MANAGE_VOLUME_PRIVILEGE       28L
427 #define SE_IMPERSONATE_PRIVILEGE         29L
428 #define SE_CREATE_GLOBAL_PRIVILEGE       30L
429 #define SE_MAX_WELL_KNOWN_PRIVILEGE      SE_CREATE_GLOBAL_PRIVILEGE
430 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
431
432 static void test_allocateLuid(void)
433 {
434     BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
435     LUID luid1, luid2;
436     BOOL ret;
437
438     pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
439     if (!pAllocateLocallyUniqueId) return;
440
441     ret = pAllocateLocallyUniqueId(&luid1);
442     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
443         return;
444
445     ok(ret,
446      "AllocateLocallyUniqueId failed: %d\n", GetLastError());
447     ret = pAllocateLocallyUniqueId(&luid2);
448     ok( ret,
449      "AllocateLocallyUniqueId failed: %d\n", GetLastError());
450     ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
451      "AllocateLocallyUniqueId returned a well-known LUID\n");
452     ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
453      "AllocateLocallyUniqueId returned non-unique LUIDs\n");
454     ret = pAllocateLocallyUniqueId(NULL);
455     ok( !ret && GetLastError() == ERROR_NOACCESS,
456      "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
457      GetLastError());
458 }
459
460 static void test_lookupPrivilegeName(void)
461 {
462     BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
463     char buf[MAX_PATH]; /* arbitrary, seems long enough */
464     DWORD cchName = sizeof(buf);
465     LUID luid = { 0, 0 };
466     LONG i;
467     BOOL ret;
468
469     /* check whether it's available first */
470     pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
471     if (!pLookupPrivilegeNameA) return;
472     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
473     ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
474     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
475         return;
476
477     /* check with a short buffer */
478     cchName = 0;
479     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
480     ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
481     ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
482      "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
483      GetLastError());
484     ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
485      "LookupPrivilegeNameA returned an incorrect required length for\n"
486      "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
487      lstrlenA("SeCreateTokenPrivilege") + 1);
488     /* check a known value and its returned length on success */
489     cchName = sizeof(buf);
490     ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
491      cchName == strlen("SeCreateTokenPrivilege"),
492      "LookupPrivilegeNameA returned an incorrect output length for\n"
493      "SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
494      (int)strlen("SeCreateTokenPrivilege"));
495     /* check known values */
496     for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i < SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
497     {
498         luid.LowPart = i;
499         cchName = sizeof(buf);
500         ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
501         ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
502          "LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
503     }
504     /* check a bogus LUID */
505     luid.LowPart = 0xdeadbeef;
506     cchName = sizeof(buf);
507     ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
508     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
509      "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
510      GetLastError());
511     /* check on a bogus system */
512     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
513     cchName = sizeof(buf);
514     ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
515     ok( !ret && GetLastError() == RPC_S_SERVER_UNAVAILABLE,
516      "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE: %d\n",
517      GetLastError());
518 }
519
520 struct NameToLUID
521 {
522     const char *name;
523     DWORD lowPart;
524 };
525
526 static void test_lookupPrivilegeValue(void)
527 {
528     static const struct NameToLUID privs[] = {
529      { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
530      { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
531      { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
532      { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
533      { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
534      { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
535      { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
536      { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
537      { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
538      { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
539      { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
540      { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
541      { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
542      { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
543      { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
544      { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
545      { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
546      { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
547      { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
548      { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
549      { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
550      { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILLEGE },
551      { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
552      { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
553      { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
554      { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
555      { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
556      { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
557      { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
558     };
559     BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
560     int i;
561     LUID luid;
562     BOOL ret;
563
564     /* check whether it's available first */
565     pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
566     if (!pLookupPrivilegeValueA) return;
567     ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
568     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
569         return;
570
571     /* check a bogus system name */
572     ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
573     ok( !ret && GetLastError() == RPC_S_SERVER_UNAVAILABLE,
574      "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE: %d\n",
575      GetLastError());
576     /* check a NULL string */
577     ret = pLookupPrivilegeValueA(NULL, 0, &luid);
578     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
579      "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
580      GetLastError());
581     /* check a bogus privilege name */
582     ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
583     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
584      "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
585      GetLastError());
586     /* check case insensitive */
587     ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
588     ok( ret,
589      "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
590      GetLastError());
591     for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
592     {
593         /* Not all privileges are implemented on all Windows versions, so
594          * don't worry if the call fails
595          */
596         if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
597         {
598             ok(luid.LowPart == privs[i].lowPart,
599              "LookupPrivilegeValueA returned an invalid LUID for %s\n",
600              privs[i].name);
601         }
602     }
603 }
604
605 static void test_luid(void)
606 {
607     test_allocateLuid();
608     test_lookupPrivilegeName();
609     test_lookupPrivilegeValue();
610 }
611
612 static void test_FileSecurity(void)
613 {
614     char directory[MAX_PATH];
615     DWORD retval, outSize;
616     BOOL result;
617     BYTE buffer[0x40];
618
619     pGetFileSecurityA = (fnGetFileSecurityA)
620                     GetProcAddress( hmod, "GetFileSecurityA" );
621     if( !pGetFileSecurityA )
622         return;
623
624     retval = GetTempPathA(sizeof(directory), directory);
625     if (!retval) {
626         trace("GetTempPathA failed\n");
627         return;
628     }
629
630     strcpy(directory, "\\Should not exist");
631
632     SetLastError(NO_ERROR);
633     result = pGetFileSecurityA( directory,OWNER_SECURITY_INFORMATION,buffer,0x40,&outSize);
634     ok(!result, "GetFileSecurityA should fail for not existing directories/files\n"); 
635     ok( (GetLastError() == ERROR_FILE_NOT_FOUND ) ||
636         (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) , 
637         "last error ERROR_FILE_NOT_FOUND / ERROR_CALL_NOT_IMPLEMENTED (98) "
638         "expected, got %d\n", GetLastError());
639 }
640
641 static void test_AccessCheck(void)
642 {
643     PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
644     PACL Acl = NULL;
645     SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
646     SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
647     SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
648     GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
649     ACCESS_MASK Access;
650     BOOL AccessStatus;
651     HANDLE Token;
652     BOOL ret;
653     DWORD PrivSetLen;
654     PRIVILEGE_SET *PrivSet;
655     BOOL res;
656     HMODULE NtDllModule;
657     BOOLEAN Enabled;
658
659     NtDllModule = GetModuleHandle("ntdll.dll");
660
661     if (!NtDllModule)
662     {
663         trace("not running on NT, skipping test\n");
664         return;
665     }
666     pRtlAdjustPrivilege = (fnRtlAdjustPrivilege)
667                           GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
668     if (!pRtlAdjustPrivilege) return;
669
670     Acl = HeapAlloc(GetProcessHeap(), 0, 256);
671     res = InitializeAcl(Acl, 256, ACL_REVISION);
672     if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
673     {
674         trace("ACLs not implemented - skipping tests\n");
675         return;
676     }
677     ok(res, "InitializeAcl failed with error %d\n", GetLastError());
678
679     res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
680     ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
681
682     res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
683         DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
684     ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
685
686     res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
687         DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
688     ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
689
690     res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
691     ok(res, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
692
693     res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_ALL_ACCESS, AdminSid);
694     ok(res, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
695
696     SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
697
698     res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
699     ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
700
701     res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
702     ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
703
704     res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
705     ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
706
707     res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
708     ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
709
710     PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
711     PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
712     PrivSet->PrivilegeCount = 16;
713
714     ImpersonateSelf(SecurityImpersonation);
715
716     pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
717
718     ret = OpenThreadToken(GetCurrentThread(),
719                           TOKEN_QUERY, TRUE, &Token);
720     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
721
722     ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
723                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
724     ok(ret, "AccessCheck failed with error %d\n", GetLastError());
725     ok(AccessStatus && (Access == KEY_READ),
726         "AccessCheck failed to grant access with error %d\n",
727         GetLastError());
728
729     ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
730                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
731     ok(ret, "AccessCheck failed with error %d\n", GetLastError());
732     ok(AccessStatus,
733         "AccessCheck failed to grant any access with error %d\n",
734         GetLastError());
735     trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
736
737     SetLastError(0);
738     PrivSet->PrivilegeCount = 16;
739     ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
740                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
741     ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
742         "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
743         GetLastError());
744
745     ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
746     if (!ret)
747     {
748         SetLastError(0);
749         PrivSet->PrivilegeCount = 16;
750         ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
751                           PrivSet, &PrivSetLen, &Access, &AccessStatus);
752         ok(ret && AccessStatus && GetLastError() == 0,
753             "AccessCheck should have succeeded, error %d\n",
754             GetLastError());
755         ok(Access == ACCESS_SYSTEM_SECURITY,
756             "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
757             Access);
758     }
759     else
760         trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
761             ret);
762
763     RevertToSelf();
764
765     if (EveryoneSid)
766         FreeSid(EveryoneSid);
767     if (AdminSid)
768         FreeSid(AdminSid);
769     if (UsersSid)
770         FreeSid(UsersSid);
771     HeapFree(GetProcessHeap(), 0, Acl);
772     HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
773     HeapFree(GetProcessHeap(), 0, PrivSet);
774 }
775
776 /* test GetTokenInformation for the various attributes */
777 static void test_token_attr(void)
778 {
779     HANDLE Token;
780     DWORD Size;
781     TOKEN_PRIVILEGES *Privileges;
782     TOKEN_GROUPS *Groups;
783     TOKEN_USER *User;
784     BOOL ret;
785     DWORD i, GLE;
786     LPSTR SidString;
787
788     if(!pConvertSidToStringSidA)
789         return;
790
791     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token);
792     GLE = GetLastError();
793     ok(ret || (GLE == ERROR_CALL_NOT_IMPLEMENTED), 
794         "OpenProcessToken failed with error %d\n", GLE);
795     if(!ret && (GLE == ERROR_CALL_NOT_IMPLEMENTED))
796     {
797         trace("OpenProcessToken() not implemented, skipping test_token_attr()\n");
798         return;
799     }
800
801     /* groups */
802     ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
803     Groups = HeapAlloc(GetProcessHeap(), 0, Size);
804     ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
805     ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
806     trace("TokenGroups:\n");
807     for (i = 0; i < Groups->GroupCount; i++)
808     {
809         DWORD NameLength = 255;
810         TCHAR Name[255];
811         DWORD DomainLength = 255;
812         TCHAR Domain[255];
813         SID_NAME_USE SidNameUse;
814         pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
815         Name[0] = '\0';
816         Domain[0] = '\0';
817         ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
818         ok(ret, "LookupAccountSid(%s) failed with error %d\n", SidString, GetLastError());
819         trace("\t%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
820         LocalFree(SidString);
821     }
822     HeapFree(GetProcessHeap(), 0, Groups);
823
824     /* user */
825     ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
826     ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
827         "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
828     User = HeapAlloc(GetProcessHeap(), 0, Size);
829     ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
830     ok(ret,
831         "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
832
833     pConvertSidToStringSidA(User->User.Sid, &SidString);
834     trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
835     LocalFree(SidString);
836
837     /* privileges */
838     ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
839     ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
840         "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
841     Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
842     ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
843     ok(ret,
844         "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
845     trace("TokenPrivileges:\n");
846     for (i = 0; i < Privileges->PrivilegeCount; i++)
847     {
848         TCHAR Name[256];
849         DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
850         LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
851         trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
852     }
853 }
854
855 typedef union _MAX_SID
856 {
857     SID sid;
858     char max[SECURITY_MAX_SID_SIZE];
859 } MAX_SID;
860
861 static void test_sid_str(PSID * sid)
862 {
863     char *str_sid;
864     BOOL ret = pConvertSidToStringSidA(sid, &str_sid);
865     ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
866     if (ret)
867     {
868         char account[MAX_PATH], domain[MAX_PATH];
869         SID_NAME_USE use;
870         DWORD acc_size = MAX_PATH;
871         DWORD dom_size = MAX_PATH;
872         ret = LookupAccountSid(NULL, sid, account, &acc_size, domain, &dom_size, &use);
873         ok(ret || (!ret && (GetLastError() == ERROR_NONE_MAPPED)),
874            "LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
875         if (ret)
876             trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
877         else if (GetLastError() == ERROR_NONE_MAPPED)
878             trace(" %s couldn't be mapped\n", str_sid);
879         LocalFree(str_sid);
880     }
881 }
882
883 static void test_LookupAccountSid(void)
884 {
885     SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
886     CHAR accountA[MAX_PATH], domainA[MAX_PATH];
887     DWORD acc_sizeA, dom_sizeA;
888     DWORD real_acc_sizeA, real_dom_sizeA;
889     WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
890     DWORD acc_sizeW, dom_sizeW;
891     DWORD real_acc_sizeW, real_dom_sizeW;
892     PSID pUsersSid = NULL;
893     SID_NAME_USE use;
894     BOOL ret;
895     DWORD size;
896     MAX_SID  max_sid;
897     CHAR *str_sidA;
898     int i;
899
900     /* native windows crashes if account size, domain size, or name use is NULL */
901
902     ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
903         DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
904     ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
905        "AllocateAndInitializeSid failed with error %d\n", GetLastError());
906
907     /* not running on NT so give up */
908     if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
909         return;
910
911     real_acc_sizeA = MAX_PATH;
912     real_dom_sizeA = MAX_PATH;
913     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
914     ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
915
916     /* try NULL account */
917     acc_sizeA = MAX_PATH;
918     dom_sizeA = MAX_PATH;
919     ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
920     ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
921
922     /* try NULL domain */
923     acc_sizeA = MAX_PATH;
924     dom_sizeA = MAX_PATH;
925     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
926     ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
927
928     /* try a small account buffer */
929     acc_sizeA = 1;
930     dom_sizeA = MAX_PATH;
931     accountA[0] = 0;
932     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
933     ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
934     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
935        "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
936
937     /* try a 0 sized account buffer */
938     acc_sizeA = 0;
939     dom_sizeA = MAX_PATH;
940     accountA[0] = 0;
941     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
942     /* this can fail or succeed depending on OS version but the size will always be returned */
943     ok(acc_sizeA == real_acc_sizeA + 1,
944        "LookupAccountSidA() Expected acc_size = %u, got %u\n",
945        real_acc_sizeA + 1, acc_sizeA);
946
947     /* try a 0 sized account buffer */
948     acc_sizeA = 0;
949     dom_sizeA = MAX_PATH;
950     ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
951     /* this can fail or succeed depending on OS version but the size will always be returned */
952     ok(acc_sizeA == real_acc_sizeA + 1,
953        "LookupAccountSid() Expected acc_size = %u, got %u\n",
954        real_acc_sizeA + 1, acc_sizeA);
955
956     /* try a small domain buffer */
957     dom_sizeA = 1;
958     acc_sizeA = MAX_PATH;
959     accountA[0] = 0;
960     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
961     ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
962     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
963        "LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
964
965     /* try a 0 sized domain buffer */
966     dom_sizeA = 0;
967     acc_sizeA = MAX_PATH;
968     accountA[0] = 0;
969     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
970     /* this can fail or succeed depending on OS version but the size will always be returned */
971     ok(dom_sizeA == real_dom_sizeA + 1,
972        "LookupAccountSidA() Expected dom_size = %u, got %u\n",
973        real_dom_sizeA + 1, dom_sizeA);
974
975     /* try a 0 sized domain buffer */
976     dom_sizeA = 0;
977     acc_sizeA = MAX_PATH;
978     ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
979     /* this can fail or succeed depending on OS version but the size will always be returned */
980     ok(dom_sizeA == real_dom_sizeA + 1,
981        "LookupAccountSidA() Expected dom_size = %u, got %u\n",
982        real_dom_sizeA + 1, dom_sizeA);
983
984     real_acc_sizeW = MAX_PATH;
985     real_dom_sizeW = MAX_PATH;
986     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
987     ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
988
989     /* native windows crashes if domainW or accountW is NULL */
990
991     /* try a small account buffer */
992     acc_sizeW = 1;
993     dom_sizeW = MAX_PATH;
994     accountW[0] = 0;
995     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
996     ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
997     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
998        "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
999
1000     /* try a 0 sized account buffer */
1001     acc_sizeW = 0;
1002     dom_sizeW = MAX_PATH;
1003     accountW[0] = 0;
1004     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1005     /* this can fail or succeed depending on OS version but the size will always be returned */
1006     ok(acc_sizeW == real_acc_sizeW + 1,
1007        "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1008        real_acc_sizeW + 1, acc_sizeW);
1009
1010     /* try a 0 sized account buffer */
1011     acc_sizeW = 0;
1012     dom_sizeW = MAX_PATH;
1013     ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
1014     /* this can fail or succeed depending on OS version but the size will always be returned */
1015     ok(acc_sizeW == real_acc_sizeW + 1,
1016        "LookupAccountSidW() Expected acc_size = %u, got %u\n",
1017        real_acc_sizeW + 1, acc_sizeW);
1018
1019     /* try a small domain buffer */
1020     dom_sizeW = 1;
1021     acc_sizeW = MAX_PATH;
1022     accountW[0] = 0;
1023     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1024     ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
1025     ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1026        "LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
1027
1028     /* try a 0 sized domain buffer */
1029     dom_sizeW = 0;
1030     acc_sizeW = MAX_PATH;
1031     accountW[0] = 0;
1032     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
1033     /* this can fail or succeed depending on OS version but the size will always be returned */
1034     ok(dom_sizeW == real_dom_sizeW + 1,
1035        "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1036        real_dom_sizeW + 1, dom_sizeW);
1037
1038     /* try a 0 sized domain buffer */
1039     dom_sizeW = 0;
1040     acc_sizeW = MAX_PATH;
1041     ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
1042     /* this can fail or succeed depending on OS version but the size will always be returned */
1043     ok(dom_sizeW == real_dom_sizeW + 1,
1044        "LookupAccountSidW() Expected dom_size = %u, got %u\n",
1045        real_dom_sizeW + 1, dom_sizeW);
1046
1047     pCreateWellKnownSid = (fnCreateWellKnownSid)GetProcAddress( hmod, "CreateWellKnownSid" );
1048
1049     if (pCreateWellKnownSid && pConvertSidToStringSidA)
1050     {
1051         trace("Well Known SIDs:\n");
1052         for (i = 0; i <= 60; i++)
1053         {
1054             size = SECURITY_MAX_SID_SIZE;
1055             if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
1056             {
1057                 if (pConvertSidToStringSidA(&max_sid.sid, &str_sidA))
1058                 {
1059                     acc_sizeA = MAX_PATH;
1060                     dom_sizeA = MAX_PATH;
1061                     if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
1062                         trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
1063                     LocalFree(str_sidA);
1064                 }
1065             }
1066             else
1067             {
1068                 if (GetLastError() != ERROR_INVALID_PARAMETER)
1069                     trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
1070                 else
1071                     trace(" %d: not supported\n", i);
1072             }
1073         }
1074
1075         pLsaQueryInformationPolicy = (fnLsaQueryInformationPolicy)GetProcAddress( hmod, "LsaQueryInformationPolicy");
1076         pLsaOpenPolicy = (fnLsaOpenPolicy)GetProcAddress( hmod, "LsaOpenPolicy");
1077         pLsaFreeMemory = (fnLsaFreeMemory)GetProcAddress( hmod, "LsaFreeMemory");
1078         pLsaClose = (fnLsaClose)GetProcAddress( hmod, "LsaClose");
1079
1080         if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
1081         {
1082             NTSTATUS status;
1083             LSA_HANDLE handle;
1084             LSA_OBJECT_ATTRIBUTES object_attributes;
1085
1086             ZeroMemory(&object_attributes, sizeof(object_attributes));
1087             object_attributes.Length = sizeof(object_attributes);
1088
1089             status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
1090             ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
1091                "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
1092
1093             /* try a more restricted access mask if necessary */
1094             if (status == STATUS_ACCESS_DENIED) {
1095                 trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
1096                 status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
1097                 ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
1098             }
1099
1100             if (status == STATUS_SUCCESS)
1101             {
1102                 PPOLICY_ACCOUNT_DOMAIN_INFO info;
1103                 status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
1104                 ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
1105                 if (status == STATUS_SUCCESS)
1106                 {
1107                     ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
1108                     if (info->DomainSid)
1109                     {
1110                         int count = *GetSidSubAuthorityCount(info->DomainSid);
1111                         CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
1112                         test_sid_str((PSID)&max_sid.sid);
1113                         max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
1114                         max_sid.sid.SubAuthorityCount = count + 1;
1115                         test_sid_str((PSID)&max_sid.sid);
1116                         max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
1117                         test_sid_str((PSID)&max_sid.sid);
1118                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
1119                         test_sid_str((PSID)&max_sid.sid);
1120                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
1121                         test_sid_str((PSID)&max_sid.sid);
1122                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
1123                         test_sid_str((PSID)&max_sid.sid);
1124                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
1125                         test_sid_str((PSID)&max_sid.sid);
1126                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
1127                         test_sid_str((PSID)&max_sid.sid);
1128                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
1129                         test_sid_str((PSID)&max_sid.sid);
1130                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
1131                         test_sid_str((PSID)&max_sid.sid);
1132                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
1133                         test_sid_str((PSID)&max_sid.sid);
1134                         max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
1135                         test_sid_str((PSID)&max_sid.sid);
1136                         max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
1137                         test_sid_str((PSID)&max_sid.sid);
1138                         max_sid.sid.SubAuthority[count] = 1000; /* first user account */
1139                         test_sid_str((PSID)&max_sid.sid);
1140                     }
1141
1142                     pLsaFreeMemory((LPVOID)info);
1143                 }
1144
1145                 status = pLsaClose(handle);
1146                 ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
1147             }
1148         }
1149     }
1150 }
1151
1152 START_TEST(security)
1153 {
1154     init();
1155     if (!hmod) return;
1156     test_sid();
1157     test_trustee();
1158     test_luid();
1159     test_FileSecurity();
1160     test_AccessCheck();
1161     test_token_attr();
1162     test_LookupAccountSid();
1163 }