crypt32: Implement file stores.
[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 <stdio.h>
22
23 #include "wine/test.h"
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winerror.h"
27 #include "aclapi.h"
28 #include "winnt.h"
29 #include "sddl.h"
30
31 typedef VOID (WINAPI *fnBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
32 typedef VOID (WINAPI *fnBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
33 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
34                                                           POBJECTS_AND_NAME_A pObjName,
35                                                           SE_OBJECT_TYPE ObjectType,
36                                                           LPSTR ObjectTypeName,
37                                                           LPSTR InheritedObjectTypeName,
38                                                           LPSTR Name );
39 typedef VOID (WINAPI *fnBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
40                                                          POBJECTS_AND_SID pObjSid,
41                                                          GUID* pObjectGuid,
42                                                          GUID* pInheritedObjectGuid,
43                                                          PSID pSid );
44 typedef LPSTR (WINAPI *fnGetTrusteeNameA)( PTRUSTEEA pTrustee );
45 typedef BOOL (WINAPI *fnConvertSidToStringSidA)( PSID pSid, LPSTR *str );
46 typedef BOOL (WINAPI *fnConvertStringSidToSidA)( LPCSTR str, PSID pSid );
47 typedef BOOL (WINAPI *fnGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
48                                           PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
49 typedef DWORD (WINAPI *fnRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
50 typedef BOOL (WINAPI *fnCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
51
52 static HMODULE hmod;
53
54 fnBuildTrusteeWithSidA   pBuildTrusteeWithSidA;
55 fnBuildTrusteeWithNameA  pBuildTrusteeWithNameA;
56 fnBuildTrusteeWithObjectsAndNameA pBuildTrusteeWithObjectsAndNameA;
57 fnBuildTrusteeWithObjectsAndSidA pBuildTrusteeWithObjectsAndSidA;
58 fnGetTrusteeNameA pGetTrusteeNameA;
59 fnConvertSidToStringSidA pConvertSidToStringSidA;
60 fnConvertStringSidToSidA pConvertStringSidToSidA;
61 fnGetFileSecurityA pGetFileSecurityA;
62 fnRtlAdjustPrivilege pRtlAdjustPrivilege;
63 fnCreateWellKnownSid pCreateWellKnownSid;
64
65 struct sidRef
66 {
67     SID_IDENTIFIER_AUTHORITY auth;
68     const char *refStr;
69 };
70
71 static void init(void)
72 {
73     hmod = GetModuleHandle("advapi32.dll");
74 }
75
76 static void test_sid(void)
77 {
78     struct sidRef refs[] = {
79      { { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
80      { { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1"  },
81      { { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1"     },
82      { { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1"       },
83      { { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1"         },
84      { { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1"        },
85     };
86     const char noSubAuthStr[] = "S-1-5";
87     unsigned int i;
88     PSID psid = NULL;
89     BOOL r;
90     LPSTR str = NULL;
91
92     pConvertSidToStringSidA = (fnConvertSidToStringSidA)
93                     GetProcAddress( hmod, "ConvertSidToStringSidA" );
94     if( !pConvertSidToStringSidA )
95         return;
96     pConvertStringSidToSidA = (fnConvertStringSidToSidA)
97                     GetProcAddress( hmod, "ConvertStringSidToSidA" );
98     if( !pConvertStringSidToSidA )
99         return;
100
101     r = pConvertStringSidToSidA( NULL, NULL );
102     ok( !r, "expected failure with NULL parameters\n" );
103     if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
104         return;
105     ok( GetLastError() == ERROR_INVALID_PARAMETER,
106      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %ld\n",
107      GetLastError() );
108
109     r = pConvertStringSidToSidA( refs[0].refStr, NULL );
110     ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
111      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %ld\n",
112      GetLastError() );
113
114     r = pConvertStringSidToSidA( NULL, &str );
115     ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
116      "expected GetLastError() is ERROR_INVALID_PARAMETER, got %ld\n",
117      GetLastError() );
118
119     r = pConvertStringSidToSidA( noSubAuthStr, &psid );
120     ok( !r,
121      "expected failure with no sub authorities\n" );
122     ok( GetLastError() == ERROR_INVALID_SID,
123      "expected GetLastError() is ERROR_INVALID_SID, got %ld\n",
124      GetLastError() );
125
126     for( i = 0; i < sizeof(refs) / sizeof(refs[0]); i++ )
127     {
128         PISID pisid;
129
130         r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
131          &psid );
132         ok( r, "failed to allocate sid\n" );
133         r = pConvertSidToStringSidA( psid, &str );
134         ok( r, "failed to convert sid\n" );
135         if (r)
136         {
137             ok( !strcmp( str, refs[i].refStr ),
138                 "incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
139             LocalFree( str );
140         }
141         if( psid )
142             FreeSid( psid );
143
144         r = pConvertStringSidToSidA( refs[i].refStr, &psid );
145         ok( r, "failed to parse sid string\n" );
146         pisid = (PISID)psid;
147         ok( pisid &&
148          !memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
149          sizeof(refs[i].auth) ),
150          "string sid %s didn't parse to expected value\n"
151          "(got 0x%04x%08lx, expected 0x%04x%08lx)\n",
152          refs[i].refStr,
153          MAKEWORD( pisid->IdentifierAuthority.Value[1],
154          pisid->IdentifierAuthority.Value[0] ),
155          MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
156          pisid->IdentifierAuthority.Value[4] ),
157          MAKEWORD( pisid->IdentifierAuthority.Value[3],
158          pisid->IdentifierAuthority.Value[2] ) ),
159          MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
160          MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
161          MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
162         if( psid )
163             LocalFree( psid );
164     }
165 }
166
167 static void test_trustee(void)
168 {
169     GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
170     GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
171     GUID ZeroGuid;
172     OBJECTS_AND_NAME_ oan;
173     OBJECTS_AND_SID oas;
174     TRUSTEE trustee;
175     PSID psid;
176     char szObjectTypeName[] = "ObjectTypeName";
177     char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
178     char szTrusteeName[] = "szTrusteeName";
179     SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
180
181     memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
182
183     pBuildTrusteeWithSidA = (fnBuildTrusteeWithSidA)
184                     GetProcAddress( hmod, "BuildTrusteeWithSidA" );
185     pBuildTrusteeWithNameA = (fnBuildTrusteeWithNameA)
186                     GetProcAddress( hmod, "BuildTrusteeWithNameA" );
187     pBuildTrusteeWithObjectsAndNameA = (fnBuildTrusteeWithObjectsAndNameA)
188                     GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
189     pBuildTrusteeWithObjectsAndSidA = (fnBuildTrusteeWithObjectsAndSidA)
190                     GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
191     pGetTrusteeNameA = (fnGetTrusteeNameA)
192                     GetProcAddress (hmod, "GetTrusteeNameA" );
193     if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
194         !pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
195         !pGetTrusteeNameA )
196         return;
197
198     if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
199     {
200         trace( "failed to init SID\n" );
201        return;
202     }
203
204     /* test BuildTrusteeWithSidA */
205     memset( &trustee, 0xff, sizeof trustee );
206     pBuildTrusteeWithSidA( &trustee, psid );
207
208     ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
209     ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
210         "MultipleTrusteeOperation wrong\n");
211     ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
212     ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
213     ok( trustee.ptstrName == (LPSTR) psid, "ptstrName wrong\n" );
214
215     /* test BuildTrusteeWithObjectsAndSidA (test 1) */
216     memset( &trustee, 0xff, sizeof trustee );
217     memset( &oas, 0xff, sizeof(oas) );
218     pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
219                                     &InheritedObjectType, psid);
220
221     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
222     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
223     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
224     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
225     ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
226  
227     ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
228     ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
229     ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
230     ok(oas.pSid == psid, "pSid wrong\n");
231
232     /* test GetTrusteeNameA */
233     ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
234
235     /* test BuildTrusteeWithObjectsAndSidA (test 2) */
236     memset( &trustee, 0xff, sizeof trustee );
237     memset( &oas, 0xff, sizeof(oas) );
238     pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
239                                     &InheritedObjectType, psid);
240
241     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
242     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
243     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
244     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
245     ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
246  
247     ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
248     ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
249     ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
250     ok(oas.pSid == psid, "pSid wrong\n");
251
252     FreeSid( psid );
253
254     /* test BuildTrusteeWithNameA */
255     memset( &trustee, 0xff, sizeof trustee );
256     pBuildTrusteeWithNameA( &trustee, szTrusteeName );
257
258     ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
259     ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, 
260         "MultipleTrusteeOperation wrong\n");
261     ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
262     ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
263     ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
264
265     /* test BuildTrusteeWithObjectsAndNameA (test 1) */
266     memset( &trustee, 0xff, sizeof trustee );
267     memset( &oan, 0xff, sizeof(oan) );
268     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
269                                      szInheritedObjectTypeName, szTrusteeName);
270
271     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
272     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
273     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
274     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
275     ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
276  
277     ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
278     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
279     ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
280     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
281
282     /* test GetTrusteeNameA */
283     ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
284
285     /* test BuildTrusteeWithObjectsAndNameA (test 2) */
286     memset( &trustee, 0xff, sizeof trustee );
287     memset( &oan, 0xff, sizeof(oan) );
288     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
289                                      szInheritedObjectTypeName, szTrusteeName);
290
291     ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
292     ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
293     ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
294     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
295     ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
296  
297     ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
298     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
299     ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
300     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
301
302     /* test BuildTrusteeWithObjectsAndNameA (test 3) */
303     memset( &trustee, 0xff, sizeof trustee );
304     memset( &oan, 0xff, sizeof(oan) );
305     pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
306                                      NULL, szTrusteeName);
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_NAME, "TrusteeForm wrong\n");
311     ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
312     ok(trustee.ptstrName == (LPTSTR)&oan, "ptstrName wrong\n");
313  
314     ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
315     ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
316     ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
317     ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
318 }
319  
320 /* If the first isn't defined, assume none is */
321 #ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
322 #define SE_MIN_WELL_KNOWN_PRIVILEGE       2L
323 #define SE_CREATE_TOKEN_PRIVILEGE         2L
324 #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE   3L
325 #define SE_LOCK_MEMORY_PRIVILEGE          4L
326 #define SE_INCREASE_QUOTA_PRIVILEGE       5L
327 #define SE_MACHINE_ACCOUNT_PRIVILEGE      6L
328 #define SE_TCB_PRIVILEGE                  7L
329 #define SE_SECURITY_PRIVILEGE             8L
330 #define SE_TAKE_OWNERSHIP_PRIVILEGE       9L
331 #define SE_LOAD_DRIVER_PRIVILEGE         10L
332 #define SE_SYSTEM_PROFILE_PRIVILEGE      11L
333 #define SE_SYSTEMTIME_PRIVILEGE          12L
334 #define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
335 #define SE_INC_BASE_PRIORITY_PRIVILEGE   14L
336 #define SE_CREATE_PAGEFILE_PRIVILEGE     15L
337 #define SE_CREATE_PERMANENT_PRIVILEGE    16L
338 #define SE_BACKUP_PRIVILEGE              17L
339 #define SE_RESTORE_PRIVILEGE             18L
340 #define SE_SHUTDOWN_PRIVILEGE            19L
341 #define SE_DEBUG_PRIVILEGE               20L
342 #define SE_AUDIT_PRIVILEGE               21L
343 #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE  22L
344 #define SE_CHANGE_NOTIFY_PRIVILLEGE      23L
345 #define SE_REMOTE_SHUTDOWN_PRIVILEGE     24L
346 #define SE_UNDOCK_PRIVILEGE              25L
347 #define SE_SYNC_AGENT_PRIVILEGE          26L
348 #define SE_ENABLE_DELEGATION_PRIVILEGE   27L
349 #define SE_MANAGE_VOLUME_PRIVILEGE       28L
350 #define SE_IMPERSONATE_PRIVILEGE         29L
351 #define SE_CREATE_GLOBAL_PRIVILEGE       30L
352 #define SE_MAX_WELL_KNOWN_PRIVILEGE      SE_CREATE_GLOBAL_PRIVILEGE
353 #endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
354
355 static void test_allocateLuid(void)
356 {
357     BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
358     LUID luid1, luid2;
359     BOOL ret;
360
361     pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
362     if (!pAllocateLocallyUniqueId) return;
363
364     ret = pAllocateLocallyUniqueId(&luid1);
365     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
366         return;
367
368     ok(ret,
369      "AllocateLocallyUniqueId failed: %ld\n", GetLastError());
370     ret = pAllocateLocallyUniqueId(&luid2);
371     ok( ret,
372      "AllocateLocallyUniqueId failed: %ld\n", GetLastError());
373     ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
374      "AllocateLocallyUniqueId returned a well-known LUID\n");
375     ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
376      "AllocateLocallyUniqueId returned non-unique LUIDs\n");
377     ret = pAllocateLocallyUniqueId(NULL);
378     ok( !ret && GetLastError() == ERROR_NOACCESS,
379      "AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %ld\n",
380      GetLastError());
381 }
382
383 static void test_lookupPrivilegeName(void)
384 {
385     BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
386     char buf[MAX_PATH]; /* arbitrary, seems long enough */
387     DWORD cchName = sizeof(buf);
388     LUID luid = { 0, 0 };
389     LONG i;
390     BOOL ret;
391
392     /* check whether it's available first */
393     pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
394     if (!pLookupPrivilegeNameA) return;
395     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
396     ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
397     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
398         return;
399
400     /* check with a short buffer */
401     cchName = 0;
402     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
403     ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
404     ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
405      "LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %ld\n",
406      GetLastError());
407     ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
408      "LookupPrivilegeNameA returned an incorrect required length for\n"
409      "SeCreateTokenPrivilege (got %ld, expected %d)\n", cchName,
410      lstrlenA("SeCreateTokenPrivilege") + 1);
411     /* check a known value and its returned length on success */
412     cchName = sizeof(buf);
413     ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
414      cchName == strlen("SeCreateTokenPrivilege"),
415      "LookupPrivilegeNameA returned an incorrect output length for\n"
416      "SeCreateTokenPrivilege (got %ld, expected %d)\n", cchName,
417      (int)strlen("SeCreateTokenPrivilege"));
418     /* check known values */
419     for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i < SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
420     {
421         luid.LowPart = i;
422         cchName = sizeof(buf);
423         ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
424         ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
425          "LookupPrivilegeNameA(0.%ld) failed: %ld\n", i, GetLastError());
426     }
427     /* check a bogus LUID */
428     luid.LowPart = 0xdeadbeef;
429     cchName = sizeof(buf);
430     ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
431     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
432      "LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %ld\n",
433      GetLastError());
434     /* check on a bogus system */
435     luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
436     cchName = sizeof(buf);
437     ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
438     ok( !ret && GetLastError() == RPC_S_SERVER_UNAVAILABLE,
439      "LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE: %ld\n",
440      GetLastError());
441 }
442
443 struct NameToLUID
444 {
445     const char *name;
446     DWORD lowPart;
447 };
448
449 static void test_lookupPrivilegeValue(void)
450 {
451     static const struct NameToLUID privs[] = {
452      { "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
453      { "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
454      { "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
455      { "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
456      { "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
457      { "SeTcbPrivilege", SE_TCB_PRIVILEGE },
458      { "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
459      { "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
460      { "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
461      { "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
462      { "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
463      { "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
464      { "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
465      { "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
466      { "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
467      { "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
468      { "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
469      { "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
470      { "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
471      { "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
472      { "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
473      { "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILLEGE },
474      { "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
475      { "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
476      { "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
477      { "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
478      { "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
479      { "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
480      { "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
481     };
482     BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
483     int i;
484     LUID luid;
485     BOOL ret;
486
487     /* check whether it's available first */
488     pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
489     if (!pLookupPrivilegeValueA) return;
490     ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
491     if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
492         return;
493
494     /* check a bogus system name */
495     ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
496     ok( !ret && GetLastError() == RPC_S_SERVER_UNAVAILABLE,
497      "LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE: %ld\n",
498      GetLastError());
499     /* check a NULL string */
500     ret = pLookupPrivilegeValueA(NULL, 0, &luid);
501     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
502      "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %ld\n",
503      GetLastError());
504     /* check a bogus privilege name */
505     ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
506     ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
507      "LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %ld\n",
508      GetLastError());
509     /* check case insensitive */
510     ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
511     ok( ret,
512      "LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %ld\n",
513      GetLastError());
514     for (i = 0; i < sizeof(privs) / sizeof(privs[0]); i++)
515     {
516         /* Not all privileges are implemented on all Windows versions, so
517          * don't worry if the call fails
518          */
519         if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
520         {
521             ok(luid.LowPart == privs[i].lowPart,
522              "LookupPrivilegeValueA returned an invalid LUID for %s\n",
523              privs[i].name);
524         }
525     }
526 }
527
528 static void test_luid(void)
529 {
530     test_allocateLuid();
531     test_lookupPrivilegeName();
532     test_lookupPrivilegeValue();
533 }
534
535 static void test_FileSecurity(void)
536 {
537     char directory[MAX_PATH];
538     DWORD retval, outSize;
539     BOOL result;
540     BYTE buffer[0x40];
541
542     pGetFileSecurityA = (fnGetFileSecurityA)
543                     GetProcAddress( hmod, "GetFileSecurityA" );
544     if( !pGetFileSecurityA )
545         return;
546
547     retval = GetTempPathA(sizeof(directory), directory);
548     if (!retval) {
549         trace("GetTempPathA failed\n");
550         return;
551     }
552
553     strcpy(directory, "\\Should not exist");
554
555     SetLastError(NO_ERROR);
556     result = pGetFileSecurityA( directory,OWNER_SECURITY_INFORMATION,buffer,0x40,&outSize);
557     ok(!result, "GetFileSecurityA should fail for not existing directories/files\n"); 
558     ok( (GetLastError() == ERROR_FILE_NOT_FOUND ) ||
559         (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) , 
560         "last error ERROR_FILE_NOT_FOUND / ERROR_CALL_NOT_IMPLEMENTED (98) "
561         "expected, got %ld\n", GetLastError());
562 }
563
564 static void test_AccessCheck(void)
565 {
566     PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
567     PACL Acl = NULL;
568     SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
569     SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
570     SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
571     GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
572     ACCESS_MASK Access;
573     BOOL AccessStatus;
574     HANDLE Token;
575     BOOL ret;
576     DWORD PrivSetLen;
577     PRIVILEGE_SET *PrivSet;
578     BOOL res;
579     HMODULE NtDllModule;
580     BOOLEAN Enabled;
581
582     NtDllModule = GetModuleHandle("ntdll.dll");
583
584     if (!NtDllModule)
585     {
586         trace("not running on NT, skipping test\n");
587         return;
588     }
589     pRtlAdjustPrivilege = (fnRtlAdjustPrivilege)
590                           GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
591     if (!pRtlAdjustPrivilege) return;
592
593     Acl = HeapAlloc(GetProcessHeap(), 0, 256);
594     res = InitializeAcl(Acl, 256, ACL_REVISION);
595     if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
596     {
597         trace("ACLs not implemented - skipping tests\n");
598         return;
599     }
600     ok(res, "InitializeAcl failed with error %ld\n", GetLastError());
601
602     res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
603     ok(res, "AllocateAndInitializeSid failed with error %ld\n", GetLastError());
604
605     res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
606         DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
607     ok(res, "AllocateAndInitializeSid failed with error %ld\n", GetLastError());
608
609     res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
610         DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
611     ok(res, "AllocateAndInitializeSid failed with error %ld\n", GetLastError());
612
613     res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
614     ok(res, "AddAccessAllowedAceEx failed with error %ld\n", GetLastError());
615
616     res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_ALL_ACCESS, AdminSid);
617     ok(res, "AddAccessAllowedAceEx failed with error %ld\n", GetLastError());
618
619     SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
620
621     res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
622     ok(res, "InitializeSecurityDescriptor failed with error %ld\n", GetLastError());
623
624     res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
625     ok(res, "SetSecurityDescriptorDacl failed with error %ld\n", GetLastError());
626
627     res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
628     ok(res, "SetSecurityDescriptorOwner failed with error %ld\n", GetLastError());
629
630     res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
631     ok(res, "SetSecurityDescriptorGroup failed with error %ld\n", GetLastError());
632
633     PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
634     PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
635     PrivSet->PrivilegeCount = 16;
636
637     ImpersonateSelf(SecurityImpersonation);
638
639     pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
640
641     ret = OpenThreadToken(GetCurrentThread(),
642                           TOKEN_QUERY, TRUE, &Token);
643     ok(ret, "OpenThreadToken failed with error %ld\n", GetLastError());
644
645     ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
646                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
647     ok(ret, "AccessCheck failed with error %ld\n", GetLastError());
648     ok(AccessStatus && (Access == KEY_READ),
649         "AccessCheck failed to grant access with error %ld\n",
650         GetLastError());
651
652     ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
653                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
654     ok(ret, "AccessCheck failed with error %ld\n", GetLastError());
655     ok(AccessStatus,
656         "AccessCheck failed to grant any access with error %ld\n",
657         GetLastError());
658     trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08lx\n", Access);
659
660     SetLastError(0);
661     PrivSet->PrivilegeCount = 16;
662     ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
663                       PrivSet, &PrivSetLen, &Access, &AccessStatus);
664     ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
665         "AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %ld\n",
666         GetLastError());
667
668     ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
669     if (!ret)
670     {
671         SetLastError(0);
672         PrivSet->PrivilegeCount = 16;
673         ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
674                           PrivSet, &PrivSetLen, &Access, &AccessStatus);
675         ok(ret && AccessStatus && GetLastError() == 0,
676             "AccessCheck should have succeeded, error %ld\n",
677             GetLastError());
678         ok(Access == ACCESS_SYSTEM_SECURITY,
679             "Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08lx\n",
680             Access);
681     }
682     else
683         trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
684             ret);
685
686     RevertToSelf();
687
688     if (EveryoneSid)
689         FreeSid(EveryoneSid);
690     if (AdminSid)
691         FreeSid(AdminSid);
692     if (UsersSid)
693         FreeSid(UsersSid);
694     HeapFree(GetProcessHeap(), 0, Acl);
695     HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
696     HeapFree(GetProcessHeap(), 0, PrivSet);
697 }
698
699 /* test GetTokenInformation for the various attributes */
700 static void test_token_attr(void)
701 {
702     HANDLE Token;
703     DWORD Size;
704     TOKEN_PRIVILEGES *Privileges;
705     TOKEN_GROUPS *Groups;
706     TOKEN_USER *User;
707     BOOL ret;
708     DWORD i, GLE;
709     LPSTR SidString;
710
711     if(!pConvertSidToStringSidA)
712         return;
713
714     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token);
715     GLE = GetLastError();
716     ok(ret || (GLE == ERROR_CALL_NOT_IMPLEMENTED), 
717         "OpenProcessToken failed with error %ld\n", GLE);
718     if(!ret && (GLE == ERROR_CALL_NOT_IMPLEMENTED))
719     {
720         trace("OpenProcessToken() not implemented, skipping test_token_attr()\n");
721         return;
722     }
723
724     /* groups */
725     ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
726     Groups = HeapAlloc(GetProcessHeap(), 0, Size);
727     ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
728     ok(ret, "GetTokenInformation(TokenGroups) failed with error %ld\n", GetLastError());
729     trace("TokenGroups:\n");
730     for (i = 0; i < Groups->GroupCount; i++)
731     {
732         DWORD NameLength = 255;
733         TCHAR Name[255];
734         DWORD DomainLength = 255;
735         TCHAR Domain[255];
736         SID_NAME_USE SidNameUse;
737         pConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
738         Name[0] = '\0';
739         Domain[0] = '\0';
740         ret = LookupAccountSid(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
741         ok(ret, "LookupAccountSid failed with error %ld\n", GetLastError());
742         trace("\t%s, %s\\%s use: %d attr: 0x%08lx\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
743         LocalFree(SidString);
744     }
745
746     /* user */
747     ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
748     ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
749         "GetTokenInformation(TokenUser) failed with error %ld\n", GetLastError());
750     User = HeapAlloc(GetProcessHeap(), 0, Size);
751     ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
752     ok(ret,
753         "GetTokenInformation(TokenUser) failed with error %ld\n", GetLastError());
754
755     pConvertSidToStringSidA(User->User.Sid, &SidString);
756     trace("TokenUser: %s attr: 0x%08lx\n", SidString, User->User.Attributes);
757     LocalFree(SidString);
758
759     /* privileges */
760     ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
761     ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
762         "GetTokenInformation(TokenPrivileges) failed with error %ld\n", GetLastError());
763     Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
764     ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
765     ok(ret,
766         "GetTokenInformation(TokenPrivileges) failed with error %ld\n", GetLastError());
767     trace("TokenPrivileges:\n");
768     for (i = 0; i < Privileges->PrivilegeCount; i++)
769     {
770         TCHAR Name[256];
771         DWORD NameLen = sizeof(Name)/sizeof(Name[0]);
772         LookupPrivilegeName(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
773         trace("\t%s, 0x%lx\n", Name, Privileges->Privileges[i].Attributes);
774     }
775 }
776
777 static void test_LookupAccountSid(void)
778 {
779     SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
780     char account[MAX_PATH], domain[MAX_PATH];
781     DWORD acc_size, dom_size;
782     PSID pUsersSid = NULL;
783     SID_NAME_USE use;
784     BOOL ret;
785     DWORD size;
786     union u
787     {
788         SID sid;
789         char max[SECURITY_MAX_SID_SIZE];
790     } max_sid;
791     char *str_sid;
792     int i;
793
794     /* native windows crashes if account size, domain size, or name use is NULL */
795
796     ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
797         DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
798     ok(ret, "AllocateAndInitializeSid failed with error %ld\n", GetLastError());    
799
800     /* try NULL account */
801     acc_size = MAX_PATH;
802     dom_size = MAX_PATH;
803     ret = LookupAccountSid(NULL, pUsersSid, NULL, &acc_size, domain, &dom_size, &use);
804     ok(ret, "Expected TRUE, got FALSE\n");
805
806     /* try NULL domain */
807     acc_size = MAX_PATH;
808     dom_size = MAX_PATH;
809     ret = LookupAccountSid(NULL, pUsersSid, account, &acc_size, NULL, &dom_size, &use);
810     ok(ret, "Expected TRUE, got FALSE\n");
811
812     pCreateWellKnownSid = (fnCreateWellKnownSid)GetProcAddress( hmod, "CreateWellKnownSid" );
813
814     if (pCreateWellKnownSid && pConvertSidToStringSidA)
815     {
816         trace("Well Known SIDs:\n");
817         for (i = 0; i <= 60; i++)
818         {
819             size = SECURITY_MAX_SID_SIZE;
820             if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
821             {
822                 if (pConvertSidToStringSidA(&max_sid.sid, &str_sid))
823                 {
824                     acc_size = MAX_PATH;
825                     dom_size = MAX_PATH;
826                     if (LookupAccountSid(NULL, &max_sid.sid, account, &acc_size, domain, &dom_size, &use))
827                         trace(" %d: %s %s\\%s %d\n", i, str_sid, domain, account, use);
828                     LocalFree(str_sid); 
829                 }
830             }
831             else
832                 trace(" CreateWellKnownSid(%d) failed: %ld\n", i, GetLastError()); 
833         }
834     }
835 }
836
837 START_TEST(security)
838 {
839     init();
840     if (!hmod) return;
841     test_sid();
842     test_trustee();
843     test_luid();
844     test_FileSecurity();
845     test_AccessCheck();
846     test_token_attr();
847     test_LookupAccountSid();
848 }