crypt32: Test decoding a big CRL.
[wine] / dlls / secur32 / secur32.c
1 /* Copyright (C) 2004 Juan Lang
2  *
3  * This file implements loading of SSP DLLs.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19 #include <assert.h>
20 #include <stdarg.h>
21
22 #include "ntstatus.h"
23 #define WIN32_NO_STATUS
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winnls.h"
27 #include "winreg.h"
28 #include "winternl.h"
29 #include "shlwapi.h"
30 #include "sspi.h"
31 #include "secur32_priv.h"
32 #include "secext.h"
33 #include "ntsecapi.h"
34 #include "thunks.h"
35
36 #include "wine/list.h"
37 #include "wine/debug.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
40
41 /**
42  *  Type definitions
43  */
44
45 typedef struct _SecurePackageTable
46 {
47     DWORD numPackages;
48     DWORD numAllocated;
49     struct list table;
50 } SecurePackageTable;
51
52 typedef struct _SecureProviderTable
53 {
54     DWORD numProviders;
55     DWORD numAllocated;
56     struct list table;
57 } SecureProviderTable;
58
59 /**
60  *  Prototypes
61  */
62
63 /* Tries to load moduleName as a provider.  If successful, enumerates what
64  * packages it can and adds them to the package and provider tables.  Resizes
65  * tables as necessary.
66  */
67 static void _tryLoadProvider(PWSTR moduleName);
68
69 /* Initialization: read securityproviders value and attempt to open each dll
70  * there.  For each DLL, call _tryLoadProvider to see if it's really an SSP.
71  * Two undocumented functions, AddSecurityPackage(A/W) and
72  * DeleteSecurityPackage(A/W), seem suspiciously like they'd register or
73  * unregister a dll, but I'm not sure.
74  */
75 static void SECUR32_initializeProviders(void);
76
77 /* Frees all loaded packages and providers */
78 static void SECUR32_freeProviders(void);
79
80 /**
81  *  Globals
82  */
83
84 static CRITICAL_SECTION cs;
85 static SecurePackageTable *packageTable = NULL;
86 static SecureProviderTable *providerTable = NULL;
87
88 static SecurityFunctionTableA securityFunctionTableA = {
89     SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_2,
90     EnumerateSecurityPackagesA,
91     QueryCredentialsAttributesA,
92     AcquireCredentialsHandleA,
93     FreeCredentialsHandle,
94     NULL, /* Reserved2 */
95     InitializeSecurityContextA,
96     AcceptSecurityContext,
97     CompleteAuthToken,
98     DeleteSecurityContext,
99     ApplyControlToken,
100     QueryContextAttributesA,
101     ImpersonateSecurityContext,
102     RevertSecurityContext,
103     MakeSignature,
104     VerifySignature,
105     FreeContextBuffer,
106     QuerySecurityPackageInfoA,
107     NULL, /* Reserved3 */
108     NULL, /* Reserved4 */
109     ExportSecurityContext,
110     ImportSecurityContextA,
111     AddCredentialsA,
112     NULL, /* Reserved8 */
113     QuerySecurityContextToken,
114     EncryptMessage,
115     DecryptMessage,
116     SetContextAttributesA
117 };
118
119 static SecurityFunctionTableW securityFunctionTableW = {
120     SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_2,
121     EnumerateSecurityPackagesW,
122     QueryCredentialsAttributesW,
123     AcquireCredentialsHandleW,
124     FreeCredentialsHandle,
125     NULL, /* Reserved2 */
126     InitializeSecurityContextW,
127     AcceptSecurityContext,
128     CompleteAuthToken,
129     DeleteSecurityContext,
130     ApplyControlToken,
131     QueryContextAttributesW,
132     ImpersonateSecurityContext,
133     RevertSecurityContext,
134     MakeSignature,
135     VerifySignature,
136     FreeContextBuffer,
137     QuerySecurityPackageInfoW,
138     NULL, /* Reserved3 */
139     NULL, /* Reserved4 */
140     ExportSecurityContext,
141     ImportSecurityContextW,
142     AddCredentialsW,
143     NULL, /* Reserved8 */
144     QuerySecurityContextToken,
145     EncryptMessage,
146     DecryptMessage,
147     SetContextAttributesW
148 };
149
150 /***********************************************************************
151  *              InitSecurityInterfaceA (SECUR32.@)
152  */
153 PSecurityFunctionTableA WINAPI InitSecurityInterfaceA(void)
154 {
155     return &securityFunctionTableA;
156 }
157
158 /***********************************************************************
159  *              InitSecurityInterfaceW (SECUR32.@)
160  */
161 PSecurityFunctionTableW WINAPI InitSecurityInterfaceW(void)
162 {
163     return &securityFunctionTableW;
164 }
165
166 PWSTR SECUR32_strdupW(PCWSTR str)
167 {
168     PWSTR ret;
169
170     if (str)
171     {
172         ret = (PWSTR)SECUR32_ALLOC((lstrlenW(str) + 1) * sizeof(WCHAR));
173         if (ret)
174             lstrcpyW(ret, str);
175     }
176     else
177         ret = NULL;
178     return ret;
179 }
180
181 PWSTR SECUR32_AllocWideFromMultiByte(PCSTR str)
182 {
183     PWSTR ret;
184
185     if (str)
186     {
187         int charsNeeded = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
188
189         if (charsNeeded)
190         {
191             ret = (PWSTR)SECUR32_ALLOC(charsNeeded * sizeof(WCHAR));
192             if (ret)
193                 MultiByteToWideChar(CP_ACP, 0, str, -1, ret, charsNeeded);
194         }
195         else
196             ret = NULL;
197     }
198     else
199         ret = NULL;
200     return ret;
201 }
202
203 PSTR SECUR32_AllocMultiByteFromWide(PCWSTR str)
204 {
205     PSTR ret;
206
207     if (str)
208     {
209         int charsNeeded = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0,
210          NULL, NULL);
211
212         if (charsNeeded)
213         {
214             ret = (PSTR)SECUR32_ALLOC(charsNeeded);
215             if (ret)
216                 WideCharToMultiByte(CP_ACP, 0, str, -1, ret, charsNeeded,
217                  NULL, NULL);
218         }
219         else
220             ret = NULL;
221     }
222     else
223         ret = NULL;
224     return ret;
225 }
226
227 static void _makeFnTableA(PSecurityFunctionTableA fnTableA,
228  const SecurityFunctionTableA *inFnTableA,
229  const SecurityFunctionTableW *inFnTableW)
230 {
231     if (fnTableA)
232     {
233         if (inFnTableA)
234         {
235             /* The size of the version 1 table is based on platform sdk's
236              * sspi.h, though the sample ssp also provided with platform sdk
237              * implies only functions through QuerySecurityPackageInfoA are
238              * implemented (yikes)
239              */
240             size_t tableSize = inFnTableA->dwVersion == 1 ?
241              (LPBYTE)&inFnTableA->SetContextAttributesA -
242              (LPBYTE)inFnTableA : sizeof(SecurityFunctionTableA);
243
244             memcpy(fnTableA, inFnTableA, tableSize);
245             /* override this, since we can do it internally anyway */
246             fnTableA->QuerySecurityPackageInfoA =
247              QuerySecurityPackageInfoA;
248         }
249         else if (inFnTableW)
250         {
251             /* functions with thunks */
252             if (inFnTableW->AcquireCredentialsHandleW)
253                 fnTableA->AcquireCredentialsHandleA =
254                  thunk_AcquireCredentialsHandleA;
255             if (inFnTableW->InitializeSecurityContextW)
256                 fnTableA->InitializeSecurityContextA =
257                  thunk_InitializeSecurityContextA;
258             if (inFnTableW->ImportSecurityContextW)
259                 fnTableA->ImportSecurityContextA =
260                  thunk_ImportSecurityContextA;
261             if (inFnTableW->AddCredentialsW)
262                 fnTableA->AddCredentialsA =
263                  thunk_AddCredentialsA;
264             if (inFnTableW->QueryCredentialsAttributesW)
265                 fnTableA->QueryCredentialsAttributesA =
266                  thunk_QueryCredentialsAttributesA;
267             if (inFnTableW->QueryContextAttributesW)
268                 fnTableA->QueryContextAttributesA =
269                  thunk_QueryContextAttributesA;
270             if (inFnTableW->SetContextAttributesW)
271                 fnTableA->SetContextAttributesA =
272                  thunk_SetContextAttributesA;
273             /* this can't be thunked, there's no extra param to know which
274              * package to forward to */
275             fnTableA->EnumerateSecurityPackagesA = NULL;
276             /* functions with no thunks needed */
277             fnTableA->AcceptSecurityContext = inFnTableW->AcceptSecurityContext;
278             fnTableA->CompleteAuthToken = inFnTableW->CompleteAuthToken;
279             fnTableA->DeleteSecurityContext = inFnTableW->DeleteSecurityContext;
280             fnTableA->ImpersonateSecurityContext =
281              inFnTableW->ImpersonateSecurityContext;
282             fnTableA->RevertSecurityContext = inFnTableW->RevertSecurityContext;
283             fnTableA->MakeSignature = inFnTableW->MakeSignature;
284             fnTableA->VerifySignature = inFnTableW->VerifySignature;
285             fnTableA->FreeContextBuffer = inFnTableW->FreeContextBuffer;
286             fnTableA->QuerySecurityPackageInfoA =
287              QuerySecurityPackageInfoA;
288             fnTableA->ExportSecurityContext =
289              inFnTableW->ExportSecurityContext;
290             fnTableA->QuerySecurityContextToken =
291              inFnTableW->QuerySecurityContextToken;
292             fnTableA->EncryptMessage = inFnTableW->EncryptMessage;
293             fnTableA->DecryptMessage = inFnTableW->DecryptMessage;
294         }
295     }
296 }
297
298 static void _makeFnTableW(PSecurityFunctionTableW fnTableW,
299  const SecurityFunctionTableA *inFnTableA,
300  const SecurityFunctionTableW *inFnTableW)
301 {
302     if (fnTableW)
303     {
304         if (inFnTableW)
305         {
306             /* The size of the version 1 table is based on platform sdk's
307              * sspi.h, though the sample ssp also provided with platform sdk
308              * implies only functions through QuerySecurityPackageInfoA are
309              * implemented (yikes)
310              */
311             size_t tableSize = inFnTableW->dwVersion == 1 ?
312              (LPBYTE)&inFnTableW->SetContextAttributesW -
313              (LPBYTE)inFnTableW : sizeof(SecurityFunctionTableW);
314
315             memcpy(fnTableW, inFnTableW, tableSize);
316             /* override this, since we can do it internally anyway */
317             fnTableW->QuerySecurityPackageInfoW =
318              QuerySecurityPackageInfoW;
319         }
320         else if (inFnTableA)
321         {
322             /* functions with thunks */
323             if (inFnTableA->AcquireCredentialsHandleA)
324                 fnTableW->AcquireCredentialsHandleW =
325                  thunk_AcquireCredentialsHandleW;
326             if (inFnTableA->InitializeSecurityContextA)
327                 fnTableW->InitializeSecurityContextW =
328                  thunk_InitializeSecurityContextW;
329             if (inFnTableA->ImportSecurityContextA)
330                 fnTableW->ImportSecurityContextW =
331                  thunk_ImportSecurityContextW;
332             if (inFnTableA->AddCredentialsA)
333                 fnTableW->AddCredentialsW =
334                  thunk_AddCredentialsW;
335             if (inFnTableA->QueryCredentialsAttributesA)
336                 fnTableW->QueryCredentialsAttributesW =
337                  thunk_QueryCredentialsAttributesW;
338             if (inFnTableA->QueryContextAttributesA)
339                 fnTableW->QueryContextAttributesW =
340                  thunk_QueryContextAttributesW;
341             if (inFnTableA->SetContextAttributesA)
342                 fnTableW->SetContextAttributesW =
343                  thunk_SetContextAttributesW;
344             /* this can't be thunked, there's no extra param to know which
345              * package to forward to */
346             fnTableW->EnumerateSecurityPackagesW = NULL;
347             /* functions with no thunks needed */
348             fnTableW->AcceptSecurityContext = inFnTableA->AcceptSecurityContext;
349             fnTableW->CompleteAuthToken = inFnTableA->CompleteAuthToken;
350             fnTableW->DeleteSecurityContext = inFnTableA->DeleteSecurityContext;
351             fnTableW->ImpersonateSecurityContext =
352              inFnTableA->ImpersonateSecurityContext;
353             fnTableW->RevertSecurityContext = inFnTableA->RevertSecurityContext;
354             fnTableW->MakeSignature = inFnTableA->MakeSignature;
355             fnTableW->VerifySignature = inFnTableA->VerifySignature;
356             fnTableW->FreeContextBuffer = inFnTableA->FreeContextBuffer;
357             fnTableW->QuerySecurityPackageInfoW =
358              QuerySecurityPackageInfoW;
359             fnTableW->ExportSecurityContext =
360              inFnTableA->ExportSecurityContext;
361             fnTableW->QuerySecurityContextToken =
362              inFnTableA->QuerySecurityContextToken;
363             fnTableW->EncryptMessage = inFnTableA->EncryptMessage;
364             fnTableW->DecryptMessage = inFnTableA->DecryptMessage;
365         }
366     }
367 }
368
369 static void _copyPackageInfo(PSecPkgInfoW info, const SecPkgInfoA *inInfoA,
370  const SecPkgInfoW *inInfoW)
371 {
372     if (info && (inInfoA || inInfoW))
373     {
374         /* odd, I know, but up until Name and Comment the structures are
375          * identical
376          */
377         memcpy(info, inInfoW ? inInfoW : (PSecPkgInfoW)inInfoA, sizeof(*info));
378         if (inInfoW)
379         {
380             info->Name = SECUR32_strdupW(inInfoW->Name);
381             info->Comment = SECUR32_strdupW(inInfoW->Comment);
382         }
383         else
384         {
385             info->Name = SECUR32_AllocWideFromMultiByte(inInfoA->Name);
386             info->Comment = SECUR32_AllocWideFromMultiByte(inInfoA->Comment);
387         }
388     }
389 }
390
391 SecureProvider *SECUR32_addProvider(const SecurityFunctionTableA *fnTableA,
392  const SecurityFunctionTableW *fnTableW, const PWSTR moduleName)
393 {
394     SecureProvider *ret;
395
396     EnterCriticalSection(&cs);
397
398     if (!providerTable)
399     {
400         providerTable = HeapAlloc(GetProcessHeap(), 0, sizeof(SecureProviderTable));
401         if (!providerTable)
402         {
403             LeaveCriticalSection(&cs);
404             return NULL;
405         }
406
407         list_init(&providerTable->table);
408     }
409
410     ret = HeapAlloc(GetProcessHeap(), 0, sizeof(SecureProvider));
411     if (!ret)
412     {
413         LeaveCriticalSection(&cs);
414         return NULL;
415     }
416
417     list_add_tail(&providerTable->table, &ret->entry);
418     ret->lib = NULL;
419
420     if (fnTableA || fnTableW)
421     {
422         ret->moduleName = NULL;
423         _makeFnTableA(&ret->fnTableA, fnTableA, fnTableW);
424         _makeFnTableW(&ret->fnTableW, fnTableA, fnTableW);
425         ret->loaded = TRUE;
426     }
427     else
428     {
429         ret->moduleName = SECUR32_strdupW(moduleName);
430         ret->loaded = FALSE;
431     }
432     
433     LeaveCriticalSection(&cs);
434     return ret;
435 }
436
437 void SECUR32_addPackages(SecureProvider *provider, ULONG toAdd,
438  const SecPkgInfoA *infoA, const SecPkgInfoW *infoW)
439 {
440     ULONG i;
441
442     assert(provider);
443     assert(infoA || infoW);
444
445     EnterCriticalSection(&cs);
446
447     if (!packageTable)
448     {
449         packageTable = HeapAlloc(GetProcessHeap(), 0, sizeof(SecurePackageTable));
450         if (!packageTable)
451         {
452             LeaveCriticalSection(&cs);
453             return;
454         }
455
456         packageTable->numPackages = 0;
457         list_init(&packageTable->table);
458     }
459         
460     for (i = 0; i < toAdd; i++)
461     {
462         SecurePackage *package = HeapAlloc(GetProcessHeap(), 0, sizeof(SecurePackage));
463         if (!package)
464             continue;
465
466         list_add_tail(&packageTable->table, &package->entry);
467
468         package->provider = provider;
469         _copyPackageInfo(&package->infoW,
470             infoA ? &infoA[i] : NULL,
471             infoW ? &infoW[i] : NULL);
472     }
473     packageTable->numPackages += toAdd;
474
475     LeaveCriticalSection(&cs);
476 }
477
478 static void _tryLoadProvider(PWSTR moduleName)
479 {
480     HMODULE lib = LoadLibraryW(moduleName);
481
482     if (lib)
483     {
484         INIT_SECURITY_INTERFACE_W pInitSecurityInterfaceW =
485          (INIT_SECURITY_INTERFACE_W)GetProcAddress(lib,
486          SECURITY_ENTRYPOINT_ANSIW);
487         INIT_SECURITY_INTERFACE_A pInitSecurityInterfaceA =
488          (INIT_SECURITY_INTERFACE_A)GetProcAddress(lib,
489          SECURITY_ENTRYPOINT_ANSIA);
490
491         TRACE("loaded %s, InitSecurityInterfaceA is %p, InitSecurityInterfaceW is %p\n",
492          debugstr_w(moduleName), pInitSecurityInterfaceA,
493          pInitSecurityInterfaceW);
494         if (pInitSecurityInterfaceW || pInitSecurityInterfaceA)
495         {
496             PSecurityFunctionTableA fnTableA = NULL;
497             PSecurityFunctionTableW fnTableW = NULL;
498             ULONG toAdd = 0;
499             PSecPkgInfoA infoA = NULL;
500             PSecPkgInfoW infoW = NULL;
501             SECURITY_STATUS ret = SEC_E_OK;
502
503             if (pInitSecurityInterfaceA)
504                 fnTableA = pInitSecurityInterfaceA();
505             if (pInitSecurityInterfaceW)
506                 fnTableW = pInitSecurityInterfaceW();
507             if (fnTableW && fnTableW->EnumerateSecurityPackagesW)
508                 ret = fnTableW->EnumerateSecurityPackagesW(&toAdd, &infoW);
509             else if (fnTableA && fnTableA->EnumerateSecurityPackagesA)
510                 ret = fnTableA->EnumerateSecurityPackagesA(&toAdd, &infoA);
511             if (ret == SEC_E_OK && toAdd > 0 && (infoW || infoA))
512             {
513                 SecureProvider *provider = SECUR32_addProvider(NULL, NULL,
514                  moduleName);
515
516                 if (provider)
517                     SECUR32_addPackages(provider, toAdd, infoA, infoW);
518                 if (infoW)
519                     fnTableW->FreeContextBuffer(infoW);
520                 else
521                     fnTableA->FreeContextBuffer(infoA);
522             }
523         }
524         FreeLibrary(lib);
525     }
526     else
527         WARN("failed to load %s\n", debugstr_w(moduleName));
528 }
529
530 static const WCHAR securityProvidersKeyW[] = {
531  'S','Y','S','T','E','M','\\','C','u','r','r','e','n','t','C','o','n','t','r',
532  'o','l','S','e','t','\\','C','o','n','t','r','o','l','\\','S','e','c','u','r',
533  'i','t','y','P','r','o','v','i','d','e','r','s','\0'
534  };
535 static const WCHAR securityProvidersW[] = {
536  'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s',0
537  };
538  
539 static void SECUR32_initializeProviders(void)
540 {
541     HKEY key;
542     long apiRet;
543
544     TRACE("\n");
545     InitializeCriticalSection(&cs);
546     /* First load built-in providers */
547     SECUR32_initSchannelSP();
548     SECUR32_initNegotiateSP();
549     SECUR32_initNTLMSP();
550     /* Now load providers from registry */
551     apiRet = RegOpenKeyExW(HKEY_LOCAL_MACHINE, securityProvidersKeyW, 0,
552      KEY_READ, &key);
553     if (apiRet == ERROR_SUCCESS)
554     {
555         WCHAR securityPkgNames[MAX_PATH]; /* arbitrary len */
556         DWORD size = sizeof(securityPkgNames) / sizeof(WCHAR), type;
557
558         apiRet = RegQueryValueExW(key, securityProvidersW, NULL, &type,
559          (PBYTE)securityPkgNames, &size);
560         if (apiRet == ERROR_SUCCESS && type == REG_SZ)
561         {
562             WCHAR *ptr;
563
564             for (ptr = securityPkgNames;
565              ptr < (PWSTR)((PBYTE)securityPkgNames + size); )
566             {
567                 WCHAR *comma;
568
569                 for (comma = ptr; *comma && *comma != ','; comma++)
570                     ;
571                 if (*comma == ',')
572                     *comma = '\0';
573                 for (; *ptr && isspace(*ptr) && ptr < securityPkgNames + size;
574                  ptr++)
575                     ;
576                 if (*ptr)
577                     _tryLoadProvider(ptr);
578                 ptr += lstrlenW(ptr) + 1;
579             }
580         }
581         RegCloseKey(key);
582     }
583 }
584
585 SecurePackage *SECUR32_findPackageW(PWSTR packageName)
586 {
587     SecurePackage *ret = NULL;
588     BOOL matched = FALSE;
589
590     if (packageTable && packageName)
591     {
592         LIST_FOR_EACH_ENTRY(ret, &packageTable->table, SecurePackage, entry)
593         {
594             matched = !lstrcmpiW(ret->infoW.Name, packageName);
595             if (matched)
596                 break;
597         }
598         
599         if (!matched)
600                 return NULL;
601
602         if (ret->provider && !ret->provider->loaded)
603         {
604             ret->provider->lib = LoadLibraryW(ret->provider->moduleName);
605             if (ret->provider->lib)
606             {
607                 INIT_SECURITY_INTERFACE_W pInitSecurityInterfaceW =
608                  (INIT_SECURITY_INTERFACE_W)GetProcAddress(ret->provider->lib,
609                  SECURITY_ENTRYPOINT_ANSIW);
610                 INIT_SECURITY_INTERFACE_A pInitSecurityInterfaceA =
611                  (INIT_SECURITY_INTERFACE_A)GetProcAddress(ret->provider->lib,
612                  SECURITY_ENTRYPOINT_ANSIA);
613                 PSecurityFunctionTableA fnTableA = NULL;
614                 PSecurityFunctionTableW fnTableW = NULL;
615
616                 if (pInitSecurityInterfaceA)
617                     fnTableA = pInitSecurityInterfaceA();
618                 if (pInitSecurityInterfaceW)
619                     fnTableW = pInitSecurityInterfaceW();
620                 _makeFnTableA(&ret->provider->fnTableA, fnTableA, fnTableW);
621                 _makeFnTableW(&ret->provider->fnTableW, fnTableA, fnTableW);
622                 ret->provider->loaded = TRUE;
623             }
624             else
625                 ret = NULL;
626         }
627     }
628     return ret;
629 }
630
631 SecurePackage *SECUR32_findPackageA(PSTR packageName)
632 {
633     SecurePackage *ret;
634
635     if (packageTable && packageName)
636     {
637         UNICODE_STRING package;
638
639         RtlCreateUnicodeStringFromAsciiz(&package, packageName);
640         ret = SECUR32_findPackageW(package.Buffer);
641         RtlFreeUnicodeString(&package);
642     }
643     else
644         ret = NULL;
645     return ret;
646 }
647
648 static void SECUR32_freeProviders(void)
649 {
650     SecurePackage *package;
651     SecureProvider *provider;
652
653     TRACE("\n");
654     EnterCriticalSection(&cs);
655
656     if (packageTable)
657     {
658         LIST_FOR_EACH_ENTRY(package, &packageTable->table, SecurePackage, entry)
659         {
660             SECUR32_FREE(package->infoW.Name);
661             SECUR32_FREE(package->infoW.Comment);
662         }
663
664         HeapFree(GetProcessHeap(), 0, packageTable);
665         packageTable = NULL;
666     }
667
668     if (providerTable)
669     {
670         LIST_FOR_EACH_ENTRY(provider, &providerTable->table, SecureProvider, entry)
671         {
672             SECUR32_FREE(provider->moduleName);
673             if (provider->lib)
674                 FreeLibrary(provider->lib);
675         }
676
677         HeapFree(GetProcessHeap(), 0, providerTable);
678         providerTable = NULL;
679     }
680
681     LeaveCriticalSection(&cs);
682     DeleteCriticalSection(&cs);
683 }
684
685 /***********************************************************************
686  *              FreeContextBuffer (SECUR32.@)
687  *
688  * Doh--if pv was allocated by a crypto package, this may not be correct.
689  * The sample ssp seems to use LocalAlloc/LocalFee, but there doesn't seem to
690  * be any guarantee, nor is there an alloc function in secur32.
691  */
692 SECURITY_STATUS WINAPI FreeContextBuffer(PVOID pv)
693 {
694     SECUR32_FREE(pv);
695
696     return SEC_E_OK;
697 }
698
699 /***********************************************************************
700  *              EnumerateSecurityPackagesW (SECUR32.@)
701  */
702 SECURITY_STATUS WINAPI EnumerateSecurityPackagesW(PULONG pcPackages,
703  PSecPkgInfoW *ppPackageInfo)
704 {
705     SECURITY_STATUS ret = SEC_E_OK;
706
707     TRACE("(%p, %p)\n", pcPackages, ppPackageInfo);
708
709     /* windows just crashes if pcPackages or ppPackageInfo is NULL, so will I */
710     *pcPackages = 0;
711     EnterCriticalSection(&cs);
712     if (packageTable)
713     {
714         SecurePackage *package;
715         size_t bytesNeeded;
716
717         bytesNeeded = packageTable->numPackages * sizeof(SecPkgInfoW);
718         LIST_FOR_EACH_ENTRY(package, &packageTable->table, SecurePackage, entry)
719         {
720             if (package->infoW.Name)
721                 bytesNeeded += (lstrlenW(package->infoW.Name) + 1) * sizeof(WCHAR);
722             if (package->infoW.Comment)
723                 bytesNeeded += (lstrlenW(package->infoW.Comment) + 1) * sizeof(WCHAR);
724         }
725         if (bytesNeeded)
726         {
727             *ppPackageInfo = (PSecPkgInfoW)SECUR32_ALLOC(bytesNeeded);
728             if (*ppPackageInfo)
729             {
730                 ULONG i = 0;
731                 PWSTR nextString;
732
733                 *pcPackages = packageTable->numPackages;
734                 nextString = (PWSTR)((PBYTE)*ppPackageInfo +
735                  packageTable->numPackages * sizeof(SecPkgInfoW));
736                 LIST_FOR_EACH_ENTRY(package, &packageTable->table, SecurePackage, entry)
737                 {
738                     PSecPkgInfoW pkgInfo = *ppPackageInfo + i++;
739
740                     memcpy(pkgInfo, &package->infoW, sizeof(SecPkgInfoW));
741                     if (package->infoW.Name)
742                     {
743                         TRACE("Name[%ld] = %s\n", i - 1, debugstr_w(package->infoW.Name));
744                         pkgInfo->Name = nextString;
745                         lstrcpyW(nextString, package->infoW.Name);
746                         nextString += lstrlenW(nextString) + 1;
747                     }
748                     else
749                         pkgInfo->Name = NULL;
750                     if (package->infoW.Comment)
751                     {
752                         TRACE("Comment[%ld] = %s\n", i - 1, debugstr_w(package->infoW.Comment));
753                         pkgInfo->Comment = nextString;
754                         lstrcpyW(nextString, package->infoW.Comment);
755                         nextString += lstrlenW(nextString) + 1;
756                     }
757                     else
758                         pkgInfo->Comment = NULL;
759                 }
760             }
761             else
762                 ret = SEC_E_INSUFFICIENT_MEMORY;
763         }
764     }
765     LeaveCriticalSection(&cs);
766     TRACE("<-- 0x%08lx\n", ret);
767     return ret;
768 }
769
770 /* Converts info (which is assumed to be an array of cPackages SecPkgInfoW
771  * structures) into an array of SecPkgInfoA structures, which it returns.
772  */
773 static PSecPkgInfoA thunk_PSecPkgInfoWToA(ULONG cPackages,
774  const PSecPkgInfoW info)
775 {
776     PSecPkgInfoA ret;
777
778     if (info)
779     {
780         size_t bytesNeeded = cPackages * sizeof(SecPkgInfoA);
781         ULONG i;
782
783         for (i = 0; i < cPackages; i++)
784         {
785             if (info[i].Name)
786                 bytesNeeded += WideCharToMultiByte(CP_ACP, 0, info[i].Name,
787                  -1, NULL, 0, NULL, NULL);
788             if (info[i].Comment)
789                 bytesNeeded += WideCharToMultiByte(CP_ACP, 0, info[i].Comment,
790                  -1, NULL, 0, NULL, NULL);
791         }
792         ret = (PSecPkgInfoA)SECUR32_ALLOC(bytesNeeded);
793         if (ret)
794         {
795             PSTR nextString;
796
797             nextString = (PSTR)((PBYTE)ret + cPackages * sizeof(SecPkgInfoA));
798             for (i = 0; i < cPackages; i++)
799             {
800                 PSecPkgInfoA pkgInfo = ret + i;
801                 int bytes;
802
803                 memcpy(pkgInfo, &info[i], sizeof(SecPkgInfoA));
804                 if (info[i].Name)
805                 {
806                     pkgInfo->Name = nextString;
807                     /* just repeat back to WideCharToMultiByte how many bytes
808                      * it requires, since we asked it earlier
809                      */
810                     bytes = WideCharToMultiByte(CP_ACP, 0, info[i].Name, -1,
811                      NULL, 0, NULL, NULL);
812                     WideCharToMultiByte(CP_ACP, 0, info[i].Name, -1,
813                      pkgInfo->Name, bytes, NULL, NULL);
814                     nextString += lstrlenA(nextString) + 1;
815                 }
816                 else
817                     pkgInfo->Name = NULL;
818                 if (info[i].Comment)
819                 {
820                     pkgInfo->Comment = nextString;
821                     /* just repeat back to WideCharToMultiByte how many bytes
822                      * it requires, since we asked it earlier
823                      */
824                     bytes = WideCharToMultiByte(CP_ACP, 0, info[i].Comment, -1,
825                      NULL, 0, NULL, NULL);
826                     WideCharToMultiByte(CP_ACP, 0, info[i].Comment, -1,
827                      pkgInfo->Comment, bytes, NULL, NULL);
828                     nextString += lstrlenA(nextString) + 1;
829                 }
830                 else
831                     pkgInfo->Comment = NULL;
832             }
833         }
834     }
835     else
836         ret = NULL;
837     return ret;
838 }
839
840 /***********************************************************************
841  *              EnumerateSecurityPackagesA (SECUR32.@)
842  */
843 SECURITY_STATUS WINAPI EnumerateSecurityPackagesA(PULONG pcPackages,
844  PSecPkgInfoA *ppPackageInfo)
845 {
846     SECURITY_STATUS ret;
847     PSecPkgInfoW info;
848
849     ret = EnumerateSecurityPackagesW(pcPackages, &info);
850     if (ret == SEC_E_OK && *pcPackages && info)
851     {
852         *ppPackageInfo = thunk_PSecPkgInfoWToA(*pcPackages, info);
853         if (*pcPackages && !*ppPackageInfo)
854         {
855             *pcPackages = 0;
856             ret = SEC_E_INSUFFICIENT_MEMORY;
857         }
858         FreeContextBuffer(info);
859     }
860     return ret;
861 }
862
863 /***********************************************************************
864  *              GetComputerObjectNameA (SECUR32.@)
865  *
866  * Get the local computer's name using the format specified.
867  *
868  * PARAMS
869  *  NameFormat   [I] The format for the name.
870  *  lpNameBuffer [O] Pointer to buffer to receive the name.
871  *  nSize        [I/O] Size in characters of buffer.
872  *
873  * RETURNS
874  *  TRUE  If the name was written to lpNameBuffer.
875  *  FALSE If the name couldn't be written.
876  *
877  * NOTES
878  *  If lpNameBuffer is NULL, then the size of the buffer needed to hold the
879  *  name will be returned in *nSize.
880  *
881  *  nSize returns the number of characters written when lpNameBuffer is not
882  *  NULL or the size of the buffer needed to hold the name when the buffer
883  *  is too short or lpNameBuffer is NULL.
884  * 
885  *  It the buffer is too short, ERROR_INSUFFICIENT_BUFFER error will be set.
886  */
887 BOOLEAN WINAPI GetComputerObjectNameA(
888   EXTENDED_NAME_FORMAT NameFormat, LPSTR lpNameBuffer, PULONG nSize)
889 {
890     BOOLEAN rc;
891     LPWSTR bufferW = NULL;
892     ULONG sizeW = *nSize;
893     TRACE("(%d %p %p)\n", NameFormat, lpNameBuffer, nSize);
894     if (lpNameBuffer) {
895         bufferW = HeapAlloc(GetProcessHeap(), 0, sizeW * sizeof(WCHAR));
896         if (bufferW == NULL) {
897             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
898             return FALSE;
899         }
900     }
901     rc = GetComputerObjectNameW(NameFormat, bufferW, &sizeW);
902     if (rc && bufferW) {
903         ULONG len = WideCharToMultiByte(CP_ACP, 0, bufferW, -1, NULL, 0, NULL, NULL);
904         WideCharToMultiByte(CP_ACP, 0, bufferW, -1, lpNameBuffer, *nSize, NULL, NULL);
905         *nSize = len;
906     }
907     else
908         *nSize = sizeW;
909     HeapFree(GetProcessHeap(), 0, bufferW);
910     return rc;
911 }
912
913 /***********************************************************************
914  *              GetComputerObjectNameW (SECUR32.@)
915  */
916 BOOLEAN WINAPI GetComputerObjectNameW(
917   EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer, PULONG nSize)
918 {
919     LSA_HANDLE policyHandle;
920     LSA_OBJECT_ATTRIBUTES objectAttributes;
921     PPOLICY_DNS_DOMAIN_INFO domainInfo;
922     NTSTATUS ntStatus;
923     BOOLEAN status;
924     TRACE("(%d %p %p)\n", NameFormat, lpNameBuffer, nSize);
925
926     if (NameFormat == NameUnknown)
927     {
928         SetLastError(ERROR_INVALID_PARAMETER);
929         return FALSE;
930     }
931
932     ZeroMemory(&objectAttributes, sizeof(objectAttributes));
933     objectAttributes.Length = sizeof(objectAttributes);
934
935     ntStatus = LsaOpenPolicy(NULL, &objectAttributes,
936                              POLICY_VIEW_LOCAL_INFORMATION,
937                              &policyHandle);
938     if (ntStatus != STATUS_SUCCESS)
939     {
940         SetLastError(LsaNtStatusToWinError(ntStatus));
941         WARN("LsaOpenPolicy failed with NT status %lx\n", GetLastError());
942         return FALSE;
943     }
944
945     ntStatus = LsaQueryInformationPolicy(policyHandle,
946                                          PolicyDnsDomainInformation,
947                                          (PVOID *)&domainInfo);
948     if (ntStatus != STATUS_SUCCESS)
949     {
950         SetLastError(LsaNtStatusToWinError(ntStatus));
951         WARN("LsaQueryInformationPolicy failed with NT status %lx\n",
952              GetLastError());
953         LsaClose(policyHandle);
954         return FALSE;
955     }
956
957     if (domainInfo->Sid)
958     {
959         switch (NameFormat)
960         {
961         case NameSamCompatible:
962             {
963                 WCHAR name[MAX_COMPUTERNAME_LENGTH + 1];
964                 DWORD size = sizeof(name);
965                 if (GetComputerNameW(name, &size))
966                 {
967                     int len = domainInfo->Name.Length + size + 3;
968                     if (lpNameBuffer)
969                     {
970                         if (*nSize < len)
971                         {
972                             *nSize = len;
973                             SetLastError(ERROR_INSUFFICIENT_BUFFER);
974                             status = FALSE;
975                         }
976                         else
977                         {
978                             WCHAR bs[] = { '\\', 0 };
979                             WCHAR ds[] = { '$', 0 };
980                             lstrcpyW(lpNameBuffer, domainInfo->Name.Buffer);
981                             lstrcatW(lpNameBuffer, bs);
982                             lstrcatW(lpNameBuffer, name);
983                             lstrcatW(lpNameBuffer, ds);
984                             status = TRUE;
985                         }
986                     }
987                     else        /* just requesting length required */
988                     {
989                         *nSize = len;
990                         status = TRUE;
991                     }
992                 }
993                 else
994                 {
995                     SetLastError(ERROR_INTERNAL_ERROR);
996                     status = FALSE;
997                 }
998             }
999             break;
1000         case NameFullyQualifiedDN:
1001         case NameDisplay:
1002         case NameUniqueId:
1003         case NameCanonical:
1004         case NameUserPrincipal:
1005         case NameCanonicalEx:
1006         case NameServicePrincipal:
1007         case NameDnsDomain:
1008             FIXME("NameFormat %d not implemented\n", NameFormat);
1009             SetLastError(ERROR_CANT_ACCESS_DOMAIN_INFO);
1010             status = FALSE;
1011             break;
1012         default:
1013             SetLastError(ERROR_INVALID_PARAMETER);
1014             status = FALSE;
1015         }
1016     }
1017     else
1018     {
1019         SetLastError(ERROR_CANT_ACCESS_DOMAIN_INFO);
1020         status = FALSE;
1021     }
1022
1023     LsaFreeMemory(domainInfo);
1024     LsaClose(policyHandle);
1025
1026     return status;
1027 }
1028
1029 BOOLEAN WINAPI GetUserNameExA(
1030   EXTENDED_NAME_FORMAT NameFormat, LPSTR lpNameBuffer, PULONG nSize)
1031 {
1032     FIXME("%d %p %p\n", NameFormat, lpNameBuffer, nSize);
1033     return FALSE;
1034 }
1035
1036 BOOLEAN WINAPI GetUserNameExW(
1037   EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer, PULONG nSize)
1038 {
1039     FIXME("%d %p %p\n", NameFormat, lpNameBuffer, nSize);
1040     return FALSE;
1041 }
1042
1043 NTSTATUS WINAPI LsaCallAuthenticationPackage(
1044   HANDLE LsaHandle, ULONG AuthenticationPackage, PVOID ProtocolSubmitBuffer,
1045   ULONG SubmitBufferLength, PVOID* ProtocolReturnBuffer, PULONG ReturnBufferLength,
1046   PNTSTATUS ProtocolStatus)
1047 {
1048     FIXME("%p %ld %p %ld %p %p %p\n", LsaHandle, AuthenticationPackage,
1049           ProtocolSubmitBuffer, SubmitBufferLength, ProtocolReturnBuffer,
1050           ReturnBufferLength, ProtocolStatus);
1051     return 0;
1052 }
1053
1054 NTSTATUS WINAPI LsaConnectUntrusted(PHANDLE LsaHandle)
1055 {
1056     FIXME("%p\n", LsaHandle);
1057     return 0;
1058 }
1059
1060 NTSTATUS WINAPI LsaDeregisterLogonProcess(HANDLE LsaHandle)
1061 {
1062     FIXME("%p\n", LsaHandle);
1063     return 0;
1064 }
1065
1066 BOOLEAN WINAPI TranslateNameA(
1067   LPCSTR lpAccountName, EXTENDED_NAME_FORMAT AccountNameFormat,
1068   EXTENDED_NAME_FORMAT DesiredNameFormat, LPSTR lpTranslatedName,
1069   PULONG nSize)
1070 {
1071     FIXME("%p %d %d %p %p\n", lpAccountName, AccountNameFormat,
1072           DesiredNameFormat, lpTranslatedName, nSize);
1073     return FALSE;
1074 }
1075
1076 BOOLEAN WINAPI TranslateNameW(
1077   LPCWSTR lpAccountName, EXTENDED_NAME_FORMAT AccountNameFormat,
1078   EXTENDED_NAME_FORMAT DesiredNameFormat, LPWSTR lpTranslatedName,
1079   PULONG nSize)
1080 {
1081     FIXME("%p %d %d %p %p\n", lpAccountName, AccountNameFormat,
1082           DesiredNameFormat, lpTranslatedName, nSize);
1083     return FALSE;
1084 }
1085
1086 /***********************************************************************
1087  *              DllMain (SECUR32.0)
1088  */
1089 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1090 {
1091     if (fdwReason == DLL_PROCESS_ATTACH)
1092     {
1093         DisableThreadLibraryCalls(hinstDLL);
1094         SECUR32_initializeProviders();
1095     }
1096     else if (fdwReason == DLL_PROCESS_DETACH)
1097     {
1098         SECUR32_freeProviders();
1099     }
1100
1101     return TRUE;
1102 }