wined3d: Use GL_DEPTH24_STENCIL8_EXT for depth stencil formats.
[wine] / dlls / crypt32 / cert.c
1 /*
2  * Copyright 2004-2006 Juan Lang
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  */
19
20 #include <assert.h>
21 #include <stdarg.h>
22
23 #define NONAMELESSUNION
24 #include "windef.h"
25 #include "winbase.h"
26 #include "wincrypt.h"
27 #include "winnls.h"
28 #include "rpc.h"
29 #include "wine/debug.h"
30 #include "wine/unicode.h"
31 #include "crypt32_private.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
34
35 /* Internal version of CertGetCertificateContextProperty that gets properties
36  * directly from the context (or the context it's linked to, depending on its
37  * type.) Doesn't handle special-case properties, since they are handled by
38  * CertGetCertificateContextProperty, and are particular to the store in which
39  * the property exists (which is separate from the context.)
40  */
41 static BOOL CertContext_GetProperty(void *context, DWORD dwPropId,
42  void *pvData, DWORD *pcbData);
43
44 /* Internal version of CertSetCertificateContextProperty that sets properties
45  * directly on the context (or the context it's linked to, depending on its
46  * type.) Doesn't handle special cases, since they're handled by
47  * CertSetCertificateContextProperty anyway.
48  */
49 static BOOL CertContext_SetProperty(void *context, DWORD dwPropId,
50  DWORD dwFlags, const void *pvData);
51
52 BOOL WINAPI CertAddEncodedCertificateToStore(HCERTSTORE hCertStore,
53  DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded,
54  DWORD dwAddDisposition, PCCERT_CONTEXT *ppCertContext)
55 {
56     PCCERT_CONTEXT cert = CertCreateCertificateContext(dwCertEncodingType,
57      pbCertEncoded, cbCertEncoded);
58     BOOL ret;
59
60     TRACE("(%p, %08x, %p, %d, %08x, %p)\n", hCertStore, dwCertEncodingType,
61      pbCertEncoded, cbCertEncoded, dwAddDisposition, ppCertContext);
62
63     if (cert)
64     {
65         ret = CertAddCertificateContextToStore(hCertStore, cert,
66          dwAddDisposition, ppCertContext);
67         CertFreeCertificateContext(cert);
68     }
69     else
70         ret = FALSE;
71     return ret;
72 }
73
74 PCCERT_CONTEXT WINAPI CertCreateCertificateContext(DWORD dwCertEncodingType,
75  const BYTE *pbCertEncoded, DWORD cbCertEncoded)
76 {
77     PCERT_CONTEXT cert = NULL;
78     BOOL ret;
79     PCERT_INFO certInfo = NULL;
80     DWORD size = 0;
81
82     TRACE("(%08x, %p, %d)\n", dwCertEncodingType, pbCertEncoded,
83      cbCertEncoded);
84
85     ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
86      pbCertEncoded, cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
87      &certInfo, &size);
88     if (ret)
89     {
90         BYTE *data = NULL;
91
92         cert = Context_CreateDataContext(sizeof(CERT_CONTEXT));
93         if (!cert)
94             goto end;
95         data = CryptMemAlloc(cbCertEncoded);
96         if (!data)
97         {
98             CryptMemFree(cert);
99             cert = NULL;
100             goto end;
101         }
102         memcpy(data, pbCertEncoded, cbCertEncoded);
103         cert->dwCertEncodingType = dwCertEncodingType;
104         cert->pbCertEncoded      = data;
105         cert->cbCertEncoded      = cbCertEncoded;
106         cert->pCertInfo          = certInfo;
107         cert->hCertStore         = 0;
108     }
109
110 end:
111     return cert;
112 }
113
114 PCCERT_CONTEXT WINAPI CertDuplicateCertificateContext(
115  PCCERT_CONTEXT pCertContext)
116 {
117     TRACE("(%p)\n", pCertContext);
118
119     if (!pCertContext)
120         return NULL;
121
122     Context_AddRef((void *)pCertContext, sizeof(CERT_CONTEXT));
123     return pCertContext;
124 }
125
126 static void CertDataContext_Free(void *context)
127 {
128     PCERT_CONTEXT certContext = context;
129
130     CryptMemFree(certContext->pbCertEncoded);
131     LocalFree(certContext->pCertInfo);
132 }
133
134 BOOL WINAPI CertFreeCertificateContext(PCCERT_CONTEXT pCertContext)
135 {
136     TRACE("(%p)\n", pCertContext);
137
138     if (pCertContext)
139         Context_Release((void *)pCertContext, sizeof(CERT_CONTEXT),
140          CertDataContext_Free);
141     return TRUE;
142 }
143
144 DWORD WINAPI CertEnumCertificateContextProperties(PCCERT_CONTEXT pCertContext,
145  DWORD dwPropId)
146 {
147     PCONTEXT_PROPERTY_LIST properties = Context_GetProperties(
148      pCertContext, sizeof(CERT_CONTEXT));
149     DWORD ret;
150
151     TRACE("(%p, %d)\n", pCertContext, dwPropId);
152
153     if (properties)
154         ret = ContextPropertyList_EnumPropIDs(properties, dwPropId);
155     else
156         ret = 0;
157     return ret;
158 }
159
160 static BOOL CertContext_GetHashProp(void *context, DWORD dwPropId,
161  ALG_ID algID, const BYTE *toHash, DWORD toHashLen, void *pvData,
162  DWORD *pcbData)
163 {
164     BOOL ret = CryptHashCertificate(0, algID, 0, toHash, toHashLen, pvData,
165      pcbData);
166     if (ret && pvData)
167     {
168         CRYPT_DATA_BLOB blob = { *pcbData, pvData };
169
170         ret = CertContext_SetProperty(context, dwPropId, 0, &blob);
171     }
172     return ret;
173 }
174
175 static BOOL CertContext_CopyParam(void *pvData, DWORD *pcbData, const void *pb,
176  DWORD cb)
177 {
178     BOOL ret = TRUE;
179
180     if (!pvData)
181         *pcbData = cb;
182     else if (*pcbData < cb)
183     {
184         SetLastError(ERROR_MORE_DATA);
185         *pcbData = cb;
186         ret = FALSE;
187     }
188     else
189     {
190         memcpy(pvData, pb, cb);
191         *pcbData = cb;
192     }
193     return ret;
194 }
195
196 static BOOL CertContext_GetProperty(void *context, DWORD dwPropId,
197  void *pvData, DWORD *pcbData)
198 {
199     PCCERT_CONTEXT pCertContext = context;
200     PCONTEXT_PROPERTY_LIST properties =
201      Context_GetProperties(context, sizeof(CERT_CONTEXT));
202     BOOL ret;
203     CRYPT_DATA_BLOB blob;
204
205     TRACE("(%p, %d, %p, %p)\n", context, dwPropId, pvData, pcbData);
206
207     if (properties)
208         ret = ContextPropertyList_FindProperty(properties, dwPropId, &blob);
209     else
210         ret = FALSE;
211     if (ret)
212         ret = CertContext_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
213     else
214     {
215         /* Implicit properties */
216         switch (dwPropId)
217         {
218         case CERT_SHA1_HASH_PROP_ID:
219             ret = CertContext_GetHashProp(context, dwPropId, CALG_SHA1,
220              pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
221              pcbData);
222             break;
223         case CERT_MD5_HASH_PROP_ID:
224             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
225              pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
226              pcbData);
227             break;
228         case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
229             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
230              pCertContext->pCertInfo->Subject.pbData,
231              pCertContext->pCertInfo->Subject.cbData,
232              pvData, pcbData);
233             break;
234         case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
235             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
236              pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
237              pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData,
238              pvData, pcbData);
239             break;
240         case CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID:
241             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
242              pCertContext->pCertInfo->SerialNumber.pbData,
243              pCertContext->pCertInfo->SerialNumber.cbData,
244              pvData, pcbData);
245             break;
246         case CERT_SIGNATURE_HASH_PROP_ID:
247             ret = CryptHashToBeSigned(0, pCertContext->dwCertEncodingType,
248              pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
249              pcbData);
250             if (ret && pvData)
251             {
252                 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
253
254                 ret = CertContext_SetProperty(context, dwPropId, 0, &blob);
255             }
256             break;
257         case CERT_KEY_IDENTIFIER_PROP_ID:
258         {
259             PCERT_EXTENSION ext = CertFindExtension(
260              szOID_SUBJECT_KEY_IDENTIFIER, pCertContext->pCertInfo->cExtension,
261              pCertContext->pCertInfo->rgExtension);
262
263             if (ext)
264             {
265                 CRYPT_DATA_BLOB value;
266                 DWORD size = sizeof(value);
267
268                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
269                  szOID_SUBJECT_KEY_IDENTIFIER, ext->Value.pbData,
270                  ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &value,
271                  &size);
272                 if (ret)
273                 {
274                     ret = CertContext_CopyParam(pvData, pcbData, value.pbData,
275                      value.cbData);
276                     CertContext_SetProperty(context, dwPropId, 0, &value);
277                 }
278             }
279             else
280                 SetLastError(ERROR_INVALID_DATA);
281             break;
282         }
283         default:
284             SetLastError(CRYPT_E_NOT_FOUND);
285         }
286     }
287     TRACE("returning %d\n", ret);
288     return ret;
289 }
290
291 void CRYPT_FixKeyProvInfoPointers(PCRYPT_KEY_PROV_INFO info)
292 {
293     DWORD i, containerLen, provNameLen;
294     LPBYTE data = (LPBYTE)info + sizeof(CRYPT_KEY_PROV_INFO);
295
296     info->pwszContainerName = (LPWSTR)data;
297     containerLen = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
298     data += containerLen;
299
300     info->pwszProvName = (LPWSTR)data;
301     provNameLen = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
302     data += provNameLen;
303
304     info->rgProvParam = (PCRYPT_KEY_PROV_PARAM)data;
305     data += info->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
306
307     for (i = 0; i < info->cProvParam; i++)
308     {
309         info->rgProvParam[i].pbData = data;
310         data += info->rgProvParam[i].cbData;
311     }
312 }
313
314 BOOL WINAPI CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
315  DWORD dwPropId, void *pvData, DWORD *pcbData)
316 {
317     BOOL ret;
318
319     TRACE("(%p, %d, %p, %p)\n", pCertContext, dwPropId, pvData, pcbData);
320
321     switch (dwPropId)
322     {
323     case 0:
324     case CERT_CERT_PROP_ID:
325     case CERT_CRL_PROP_ID:
326     case CERT_CTL_PROP_ID:
327         SetLastError(E_INVALIDARG);
328         ret = FALSE;
329         break;
330     case CERT_ACCESS_STATE_PROP_ID:
331         if (pCertContext->hCertStore)
332             ret = CertGetStoreProperty(pCertContext->hCertStore, dwPropId,
333              pvData, pcbData);
334         else
335         {
336             DWORD state = 0;
337
338             ret = CertContext_CopyParam(pvData, pcbData, &state, sizeof(state));
339         }
340         break;
341     case CERT_KEY_PROV_HANDLE_PROP_ID:
342     {
343         CERT_KEY_CONTEXT keyContext;
344         DWORD size = sizeof(keyContext);
345
346         ret = CertContext_GetProperty((void *)pCertContext,
347          CERT_KEY_CONTEXT_PROP_ID, &keyContext, &size);
348         if (ret)
349             ret = CertContext_CopyParam(pvData, pcbData, &keyContext.hCryptProv,
350              sizeof(keyContext.hCryptProv));
351         break;
352     }
353     case CERT_KEY_PROV_INFO_PROP_ID:
354         ret = CertContext_GetProperty((void *)pCertContext, dwPropId, pvData,
355          pcbData);
356         if (ret && pvData)
357             CRYPT_FixKeyProvInfoPointers(pvData);
358         break;
359     default:
360         ret = CertContext_GetProperty((void *)pCertContext, dwPropId, pvData,
361          pcbData);
362     }
363
364     TRACE("returning %d\n", ret);
365     return ret;
366 }
367
368 /* Copies key provider info from from into to, where to is assumed to be a
369  * contiguous buffer of memory large enough for from and all its associated
370  * data, but whose pointers are uninitialized.
371  * Upon return, to contains a contiguous copy of from, packed in the following
372  * order:
373  * - CRYPT_KEY_PROV_INFO
374  * - pwszContainerName
375  * - pwszProvName
376  * - rgProvParam[0]...
377  */
378 static void CRYPT_CopyKeyProvInfo(PCRYPT_KEY_PROV_INFO to,
379  const CRYPT_KEY_PROV_INFO *from)
380 {
381     DWORD i;
382     LPBYTE nextData = (LPBYTE)to + sizeof(CRYPT_KEY_PROV_INFO);
383
384     if (from->pwszContainerName)
385     {
386         to->pwszContainerName = (LPWSTR)nextData;
387         lstrcpyW(to->pwszContainerName, from->pwszContainerName);
388         nextData += (lstrlenW(from->pwszContainerName) + 1) * sizeof(WCHAR);
389     }
390     else
391         to->pwszContainerName = NULL;
392     if (from->pwszProvName)
393     {
394         to->pwszProvName = (LPWSTR)nextData;
395         lstrcpyW(to->pwszProvName, from->pwszProvName);
396         nextData += (lstrlenW(from->pwszProvName) + 1) * sizeof(WCHAR);
397     }
398     else
399         to->pwszProvName = NULL;
400     to->dwProvType = from->dwProvType;
401     to->dwFlags = from->dwFlags;
402     to->cProvParam = from->cProvParam;
403     to->rgProvParam = (PCRYPT_KEY_PROV_PARAM)nextData;
404     nextData += to->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
405     to->dwKeySpec = from->dwKeySpec;
406     for (i = 0; i < to->cProvParam; i++)
407     {
408         memcpy(&to->rgProvParam[i], &from->rgProvParam[i],
409          sizeof(CRYPT_KEY_PROV_PARAM));
410         to->rgProvParam[i].pbData = nextData;
411         memcpy(to->rgProvParam[i].pbData, from->rgProvParam[i].pbData,
412          from->rgProvParam[i].cbData);
413         nextData += from->rgProvParam[i].cbData;
414     }
415 }
416
417 static BOOL CertContext_SetKeyProvInfoProperty(PCONTEXT_PROPERTY_LIST properties,
418  const CRYPT_KEY_PROV_INFO *info)
419 {
420     BOOL ret;
421     LPBYTE buf = NULL;
422     DWORD size = sizeof(CRYPT_KEY_PROV_INFO), i, containerSize, provNameSize;
423
424     if (info->pwszContainerName)
425         containerSize = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
426     else
427         containerSize = 0;
428     if (info->pwszProvName)
429         provNameSize = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
430     else
431         provNameSize = 0;
432     size += containerSize + provNameSize;
433     for (i = 0; i < info->cProvParam; i++)
434         size += sizeof(CRYPT_KEY_PROV_PARAM) + info->rgProvParam[i].cbData;
435     buf = CryptMemAlloc(size);
436     if (buf)
437     {
438         CRYPT_CopyKeyProvInfo((PCRYPT_KEY_PROV_INFO)buf, info);
439         ret = ContextPropertyList_SetProperty(properties,
440          CERT_KEY_PROV_INFO_PROP_ID, buf, size);
441         CryptMemFree(buf);
442     }
443     else
444         ret = FALSE;
445     return ret;
446 }
447
448 static BOOL CertContext_SetProperty(void *context, DWORD dwPropId,
449  DWORD dwFlags, const void *pvData)
450 {
451     PCONTEXT_PROPERTY_LIST properties =
452      Context_GetProperties(context, sizeof(CERT_CONTEXT));
453     BOOL ret;
454
455     TRACE("(%p, %d, %08x, %p)\n", context, dwPropId, dwFlags, pvData);
456
457     if (!properties)
458         ret = FALSE;
459     else
460     {
461         switch (dwPropId)
462         {
463         case CERT_AUTO_ENROLL_PROP_ID:
464         case CERT_CTL_USAGE_PROP_ID: /* same as CERT_ENHKEY_USAGE_PROP_ID */
465         case CERT_DESCRIPTION_PROP_ID:
466         case CERT_FRIENDLY_NAME_PROP_ID:
467         case CERT_HASH_PROP_ID:
468         case CERT_KEY_IDENTIFIER_PROP_ID:
469         case CERT_MD5_HASH_PROP_ID:
470         case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
471         case CERT_PUBKEY_ALG_PARA_PROP_ID:
472         case CERT_PVK_FILE_PROP_ID:
473         case CERT_SIGNATURE_HASH_PROP_ID:
474         case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
475         case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
476         case CERT_EXTENDED_ERROR_INFO_PROP_ID:
477         case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
478         case CERT_ENROLLMENT_PROP_ID:
479         case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
480         case CERT_RENEWAL_PROP_ID:
481         {
482             if (pvData)
483             {
484                 const CRYPT_DATA_BLOB *blob = pvData;
485
486                 ret = ContextPropertyList_SetProperty(properties, dwPropId,
487                  blob->pbData, blob->cbData);
488             }
489             else
490             {
491                 ContextPropertyList_RemoveProperty(properties, dwPropId);
492                 ret = TRUE;
493             }
494             break;
495         }
496         case CERT_DATE_STAMP_PROP_ID:
497             if (pvData)
498                 ret = ContextPropertyList_SetProperty(properties, dwPropId,
499                  pvData, sizeof(FILETIME));
500             else
501             {
502                 ContextPropertyList_RemoveProperty(properties, dwPropId);
503                 ret = TRUE;
504             }
505             break;
506         case CERT_KEY_CONTEXT_PROP_ID:
507         {
508             if (pvData)
509             {
510                 const CERT_KEY_CONTEXT *keyContext = pvData;
511
512                 if (keyContext->cbSize != sizeof(CERT_KEY_CONTEXT))
513                 {
514                     SetLastError(E_INVALIDARG);
515                     ret = FALSE;
516                 }
517                 else
518                     ret = ContextPropertyList_SetProperty(properties, dwPropId,
519                      (const BYTE *)keyContext, keyContext->cbSize);
520             }
521             else
522             {
523                 ContextPropertyList_RemoveProperty(properties, dwPropId);
524                 ret = TRUE;
525             }
526             break;
527         }
528         case CERT_KEY_PROV_INFO_PROP_ID:
529             if (pvData)
530                 ret = CertContext_SetKeyProvInfoProperty(properties, pvData);
531             else
532             {
533                 ContextPropertyList_RemoveProperty(properties, dwPropId);
534                 ret = TRUE;
535             }
536             break;
537         case CERT_KEY_PROV_HANDLE_PROP_ID:
538         {
539             CERT_KEY_CONTEXT keyContext;
540             DWORD size = sizeof(keyContext);
541
542             ret = CertContext_GetProperty(context, CERT_KEY_CONTEXT_PROP_ID,
543              &keyContext, &size);
544             if (ret)
545             {
546                 if (!(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG))
547                     CryptReleaseContext(keyContext.hCryptProv, 0);
548             }
549             keyContext.cbSize = sizeof(keyContext);
550             if (pvData)
551                 keyContext.hCryptProv = *(const HCRYPTPROV *)pvData;
552             else
553             {
554                 keyContext.hCryptProv = 0;
555                 keyContext.dwKeySpec = AT_SIGNATURE;
556             }
557             ret = CertContext_SetProperty(context, CERT_KEY_CONTEXT_PROP_ID,
558              0, &keyContext);
559             break;
560         }
561         default:
562             FIXME("%d: stub\n", dwPropId);
563             ret = FALSE;
564         }
565     }
566     TRACE("returning %d\n", ret);
567     return ret;
568 }
569
570 BOOL WINAPI CertSetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
571  DWORD dwPropId, DWORD dwFlags, const void *pvData)
572 {
573     BOOL ret;
574
575     TRACE("(%p, %d, %08x, %p)\n", pCertContext, dwPropId, dwFlags, pvData);
576
577     /* Handle special cases for "read-only"/invalid prop IDs.  Windows just
578      * crashes on most of these, I'll be safer.
579      */
580     switch (dwPropId)
581     {
582     case 0:
583     case CERT_ACCESS_STATE_PROP_ID:
584     case CERT_CERT_PROP_ID:
585     case CERT_CRL_PROP_ID:
586     case CERT_CTL_PROP_ID:
587         SetLastError(E_INVALIDARG);
588         return FALSE;
589     }
590     ret = CertContext_SetProperty((void *)pCertContext, dwPropId, dwFlags,
591      pvData);
592     TRACE("returning %d\n", ret);
593     return ret;
594 }
595
596 /* Acquires the private key using the key provider info, retrieving info from
597  * the certificate if info is NULL.  The acquired provider is returned in
598  * *phCryptProv, and the key spec for the provider is returned in *pdwKeySpec.
599  */
600 static BOOL CRYPT_AcquirePrivateKeyFromProvInfo(PCCERT_CONTEXT pCert,
601  PCRYPT_KEY_PROV_INFO info, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec)
602 {
603     DWORD size = 0;
604     BOOL allocated = FALSE, ret = TRUE;
605
606     if (!info)
607     {
608         ret = CertGetCertificateContextProperty(pCert,
609          CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
610         if (ret)
611         {
612             info = HeapAlloc(GetProcessHeap(), 0, size);
613             if (info)
614             {
615                 ret = CertGetCertificateContextProperty(pCert,
616                  CERT_KEY_PROV_INFO_PROP_ID, info, &size);
617                 allocated = TRUE;
618             }
619             else
620             {
621                 SetLastError(ERROR_OUTOFMEMORY);
622                 ret = FALSE;
623             }
624         }
625         else
626             SetLastError(CRYPT_E_NO_KEY_PROPERTY);
627     }
628     if (ret)
629     {
630         ret = CryptAcquireContextW(phCryptProv, info->pwszContainerName,
631          info->pwszProvName, info->dwProvType, 0);
632         if (ret)
633         {
634             DWORD i;
635
636             for (i = 0; i < info->cProvParam; i++)
637             {
638                 CryptSetProvParam(*phCryptProv,
639                  info->rgProvParam[i].dwParam, info->rgProvParam[i].pbData,
640                  info->rgProvParam[i].dwFlags);
641             }
642             *pdwKeySpec = info->dwKeySpec;
643         }
644         else
645             SetLastError(CRYPT_E_NO_KEY_PROPERTY);
646     }
647     if (allocated)
648         HeapFree(GetProcessHeap(), 0, info);
649     return ret;
650 }
651
652 BOOL WINAPI CryptAcquireCertificatePrivateKey(PCCERT_CONTEXT pCert,
653  DWORD dwFlags, void *pvReserved, HCRYPTPROV_OR_NCRYPT_KEY_HANDLE *phCryptProv,
654  DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
655 {
656     BOOL ret = FALSE, cache = FALSE;
657     PCRYPT_KEY_PROV_INFO info = NULL;
658     CERT_KEY_CONTEXT keyContext;
659     DWORD size;
660
661     TRACE("(%p, %08x, %p, %p, %p, %p)\n", pCert, dwFlags, pvReserved,
662      phCryptProv, pdwKeySpec, pfCallerFreeProv);
663
664     if (dwFlags & CRYPT_ACQUIRE_USE_PROV_INFO_FLAG)
665     {
666         DWORD size = 0;
667
668         ret = CertGetCertificateContextProperty(pCert,
669          CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
670         if (ret)
671         {
672             info = HeapAlloc(GetProcessHeap(), 0, size);
673             ret = CertGetCertificateContextProperty(pCert,
674              CERT_KEY_PROV_INFO_PROP_ID, info, &size);
675             if (ret)
676                 cache = info->dwFlags & CERT_SET_KEY_CONTEXT_PROP_ID;
677         }
678     }
679     else if (dwFlags & CRYPT_ACQUIRE_CACHE_FLAG)
680         cache = TRUE;
681     *phCryptProv = 0;
682     if (cache)
683     {
684         size = sizeof(keyContext);
685         ret = CertGetCertificateContextProperty(pCert, CERT_KEY_CONTEXT_PROP_ID,
686          &keyContext, &size);
687         if (ret)
688         {
689             *phCryptProv = keyContext.hCryptProv;
690             if (pdwKeySpec)
691                 *pdwKeySpec = keyContext.dwKeySpec;
692             if (pfCallerFreeProv)
693                 *pfCallerFreeProv = !cache;
694         }
695     }
696     if (!*phCryptProv)
697     {
698         ret = CRYPT_AcquirePrivateKeyFromProvInfo(pCert, info,
699          &keyContext.hCryptProv, &keyContext.dwKeySpec);
700         if (ret)
701         {
702             *phCryptProv = keyContext.hCryptProv;
703             if (pdwKeySpec)
704                 *pdwKeySpec = keyContext.dwKeySpec;
705             if (cache)
706             {
707                 keyContext.cbSize = sizeof(keyContext);
708                 if (CertSetCertificateContextProperty(pCert,
709                  CERT_KEY_CONTEXT_PROP_ID, 0, &keyContext))
710                 {
711                     if (pfCallerFreeProv)
712                         *pfCallerFreeProv = FALSE;
713                 }
714             }
715             else
716             {
717                 if (pfCallerFreeProv)
718                     *pfCallerFreeProv = TRUE;
719             }
720         }
721     }
722     HeapFree(GetProcessHeap(), 0, info);
723     return ret;
724 }
725
726 static BOOL key_prov_info_matches_cert(PCCERT_CONTEXT pCert,
727  const CRYPT_KEY_PROV_INFO *keyProvInfo)
728 {
729     HCRYPTPROV csp;
730     BOOL matches = FALSE;
731
732     if (CryptAcquireContextW(&csp, keyProvInfo->pwszContainerName,
733      keyProvInfo->pwszProvName, keyProvInfo->dwProvType, keyProvInfo->dwFlags))
734     {
735         DWORD size;
736
737         /* Need to sign something to verify the sig.  What to sign?  Why not
738          * the certificate itself?
739          */
740         if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
741          pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED, pCert->pCertInfo,
742          &pCert->pCertInfo->SignatureAlgorithm, NULL, NULL, &size))
743         {
744             BYTE *certEncoded = CryptMemAlloc(size);
745
746             if (certEncoded)
747             {
748                 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
749                  pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
750                  pCert->pCertInfo, &pCert->pCertInfo->SignatureAlgorithm,
751                  NULL, certEncoded, &size))
752                 {
753                     if (size == pCert->cbCertEncoded &&
754                      !memcmp(certEncoded, pCert->pbCertEncoded, size))
755                         matches = TRUE;
756                 }
757                 CryptMemFree(certEncoded);
758             }
759         }
760         CryptReleaseContext(csp, 0);
761     }
762     return matches;
763 }
764
765 static BOOL container_matches_cert(PCCERT_CONTEXT pCert, LPCSTR container,
766  CRYPT_KEY_PROV_INFO *keyProvInfo)
767 {
768     CRYPT_KEY_PROV_INFO copy;
769     WCHAR containerW[MAX_PATH];
770     BOOL matches = FALSE;
771
772     MultiByteToWideChar(CP_ACP, 0, container, -1,
773      containerW, sizeof(containerW) / sizeof(containerW[0]));
774     /* We make a copy of the CRYPT_KEY_PROV_INFO because the caller expects
775      * keyProvInfo->pwszContainerName to be NULL or a heap-allocated container
776      * name.
777      */
778     memcpy(&copy, keyProvInfo, sizeof(copy));
779     copy.pwszContainerName = containerW;
780     matches = key_prov_info_matches_cert(pCert, &copy);
781     if (matches)
782     {
783         keyProvInfo->pwszContainerName =
784          CryptMemAlloc((strlenW(containerW) + 1) * sizeof(WCHAR));
785         if (keyProvInfo->pwszContainerName)
786         {
787             strcpyW(keyProvInfo->pwszContainerName, containerW);
788             keyProvInfo->dwKeySpec = AT_SIGNATURE;
789         }
790         else
791             matches = FALSE;
792     }
793     return matches;
794 }
795
796 /* Searches the provider named keyProvInfo.pwszProvName for a container whose
797  * private key matches pCert's public key.  Upon success, updates keyProvInfo
798  * with the matching container's info (free keyProvInfo.pwszContainerName upon
799  * success.)
800  * Returns TRUE if found, FALSE if not.
801  */
802 static BOOL find_key_prov_info_in_provider(PCCERT_CONTEXT pCert,
803  CRYPT_KEY_PROV_INFO *keyProvInfo)
804 {
805     HCRYPTPROV defProvider;
806     BOOL ret, found = FALSE;
807     char containerA[MAX_PATH];
808
809     assert(keyProvInfo->pwszContainerName == NULL);
810     if ((ret = CryptAcquireContextW(&defProvider, NULL,
811      keyProvInfo->pwszProvName, keyProvInfo->dwProvType,
812      keyProvInfo->dwFlags | CRYPT_VERIFYCONTEXT)))
813     {
814         DWORD enumFlags = keyProvInfo->dwFlags | CRYPT_FIRST;
815
816         while (ret && !found)
817         {
818             DWORD size = sizeof(containerA);
819
820             ret = CryptGetProvParam(defProvider, PP_ENUMCONTAINERS,
821              (BYTE *)containerA, &size, enumFlags);
822             if (ret)
823                 found = container_matches_cert(pCert, containerA, keyProvInfo);
824             if (enumFlags & CRYPT_FIRST)
825             {
826                 enumFlags &= ~CRYPT_FIRST;
827                 enumFlags |= CRYPT_NEXT;
828             }
829         }
830         CryptReleaseContext(defProvider, 0);
831     }
832     return found;
833 }
834
835 static BOOL find_matching_provider(PCCERT_CONTEXT pCert, DWORD dwFlags)
836 {
837     BOOL found = FALSE, ret = TRUE;
838     DWORD index = 0, cbProvName = 0;
839     CRYPT_KEY_PROV_INFO keyProvInfo;
840
841     TRACE("(%p, %08x)\n", pCert, dwFlags);
842
843     memset(&keyProvInfo, 0, sizeof(keyProvInfo));
844     while (ret && !found)
845     {
846         DWORD size = 0;
847
848         ret = CryptEnumProvidersW(index, NULL, 0, &keyProvInfo.dwProvType,
849          NULL, &size);
850         if (ret)
851         {
852             if (size <= cbProvName)
853                 ret = CryptEnumProvidersW(index, NULL, 0,
854                  &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
855             else
856             {
857                 CryptMemFree(keyProvInfo.pwszProvName);
858                 keyProvInfo.pwszProvName = CryptMemAlloc(size);
859                 if (keyProvInfo.pwszProvName)
860                 {
861                     cbProvName = size;
862                     ret = CryptEnumProvidersW(index, NULL, 0,
863                      &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
864                     if (ret)
865                     {
866                         if (dwFlags & CRYPT_FIND_SILENT_KEYSET_FLAG)
867                             keyProvInfo.dwFlags |= CRYPT_SILENT;
868                         if (dwFlags & CRYPT_FIND_USER_KEYSET_FLAG ||
869                          !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
870                          CRYPT_FIND_MACHINE_KEYSET_FLAG)))
871                         {
872                             keyProvInfo.dwFlags |= CRYPT_USER_KEYSET;
873                             found = find_key_prov_info_in_provider(pCert,
874                              &keyProvInfo);
875                         }
876                         if (!found)
877                         {
878                             if (dwFlags & CRYPT_FIND_MACHINE_KEYSET_FLAG ||
879                              !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
880                              CRYPT_FIND_MACHINE_KEYSET_FLAG)))
881                             {
882                                 keyProvInfo.dwFlags &= ~CRYPT_USER_KEYSET;
883                                 keyProvInfo.dwFlags |= CRYPT_MACHINE_KEYSET;
884                                 found = find_key_prov_info_in_provider(pCert,
885                                  &keyProvInfo);
886                             }
887                         }
888                     }
889                 }
890                 else
891                     ret = FALSE;
892             }
893             index++;
894         }
895     }
896     if (found)
897         CertSetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
898          0, &keyProvInfo);
899     CryptMemFree(keyProvInfo.pwszProvName);
900     CryptMemFree(keyProvInfo.pwszContainerName);
901     return found;
902 }
903
904 static BOOL cert_prov_info_matches_cert(PCCERT_CONTEXT pCert)
905 {
906     BOOL matches = FALSE;
907     DWORD size;
908
909     if (CertGetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
910      NULL, &size))
911     {
912         CRYPT_KEY_PROV_INFO *keyProvInfo = CryptMemAlloc(size);
913
914         if (keyProvInfo)
915         {
916             if (CertGetCertificateContextProperty(pCert,
917              CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size))
918                 matches = key_prov_info_matches_cert(pCert, keyProvInfo);
919             CryptMemFree(keyProvInfo);
920         }
921     }
922     return matches;
923 }
924
925 BOOL WINAPI CryptFindCertificateKeyProvInfo(PCCERT_CONTEXT pCert,
926  DWORD dwFlags, void *pvReserved)
927 {
928     BOOL matches = FALSE;
929
930     TRACE("(%p, %08x, %p)\n", pCert, dwFlags, pvReserved);
931
932     matches = cert_prov_info_matches_cert(pCert);
933     if (!matches)
934         matches = find_matching_provider(pCert, dwFlags);
935     return matches;
936 }
937
938 BOOL WINAPI CertCompareCertificate(DWORD dwCertEncodingType,
939  PCERT_INFO pCertId1, PCERT_INFO pCertId2)
940 {
941     BOOL ret;
942
943     TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pCertId1, pCertId2);
944
945     ret = CertCompareCertificateName(dwCertEncodingType, &pCertId1->Issuer,
946      &pCertId2->Issuer) && CertCompareIntegerBlob(&pCertId1->SerialNumber,
947      &pCertId2->SerialNumber);
948     TRACE("returning %d\n", ret);
949     return ret;
950 }
951
952 BOOL WINAPI CertCompareCertificateName(DWORD dwCertEncodingType,
953  PCERT_NAME_BLOB pCertName1, PCERT_NAME_BLOB pCertName2)
954 {
955     BOOL ret;
956
957     TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pCertName1, pCertName2);
958
959     if (pCertName1->cbData == pCertName2->cbData)
960     {
961         if (pCertName1->cbData)
962             ret = !memcmp(pCertName1->pbData, pCertName2->pbData,
963              pCertName1->cbData);
964         else
965             ret = TRUE;
966     }
967     else
968         ret = FALSE;
969     TRACE("returning %d\n", ret);
970     return ret;
971 }
972
973 /* Returns the number of significant bytes in pInt, where a byte is
974  * insignificant if it's a leading 0 for positive numbers or a leading 0xff
975  * for negative numbers.  pInt is assumed to be little-endian.
976  */
977 static DWORD CRYPT_significantBytes(const CRYPT_INTEGER_BLOB *pInt)
978 {
979     DWORD ret = pInt->cbData;
980
981     while (ret > 1)
982     {
983         if (pInt->pbData[ret - 2] <= 0x7f && pInt->pbData[ret - 1] == 0)
984             ret--;
985         else if (pInt->pbData[ret - 2] >= 0x80 && pInt->pbData[ret - 1] == 0xff)
986             ret--;
987         else
988             break;
989     }
990     return ret;
991 }
992
993 BOOL WINAPI CertCompareIntegerBlob(PCRYPT_INTEGER_BLOB pInt1,
994  PCRYPT_INTEGER_BLOB pInt2)
995 {
996     BOOL ret;
997     DWORD cb1, cb2;
998
999     TRACE("(%p, %p)\n", pInt1, pInt2);
1000
1001     cb1 = CRYPT_significantBytes(pInt1);
1002     cb2 = CRYPT_significantBytes(pInt2);
1003     if (cb1 == cb2)
1004     {
1005         if (cb1)
1006             ret = !memcmp(pInt1->pbData, pInt2->pbData, cb1);
1007         else
1008             ret = TRUE;
1009     }
1010     else
1011         ret = FALSE;
1012     TRACE("returning %d\n", ret);
1013     return ret;
1014 }
1015
1016 BOOL WINAPI CertComparePublicKeyInfo(DWORD dwCertEncodingType,
1017  PCERT_PUBLIC_KEY_INFO pPublicKey1, PCERT_PUBLIC_KEY_INFO pPublicKey2)
1018 {
1019     BOOL ret;
1020
1021     TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pPublicKey1, pPublicKey2);
1022
1023     switch (GET_CERT_ENCODING_TYPE(dwCertEncodingType))
1024     {
1025     case 0:     /* Seems to mean "raw binary bits" */
1026         if (pPublicKey1->PublicKey.cbData == pPublicKey2->PublicKey.cbData &&
1027          pPublicKey1->PublicKey.cUnusedBits == pPublicKey2->PublicKey.cUnusedBits)
1028         {
1029           if (pPublicKey2->PublicKey.cbData)
1030               ret = !memcmp(pPublicKey1->PublicKey.pbData,
1031                pPublicKey2->PublicKey.pbData, pPublicKey1->PublicKey.cbData);
1032           else
1033               ret = TRUE;
1034         }
1035         else
1036             ret = FALSE;
1037         break;
1038     default:
1039         WARN("Unknown encoding type %08x\n", dwCertEncodingType);
1040         /* FALLTHROUGH */
1041     case X509_ASN_ENCODING:
1042     {
1043         BLOBHEADER *pblob1, *pblob2;
1044         DWORD length;
1045         ret = FALSE;
1046         if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1047                     pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1048                     0, NULL, &length))
1049         {
1050             pblob1 = CryptMemAlloc(length);
1051             if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1052                     pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1053                     0, pblob1, &length))
1054             {
1055                 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1056                             pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1057                             0, NULL, &length))
1058                 {
1059                     pblob2 = CryptMemAlloc(length);
1060                     if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1061                             pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1062                             0, pblob2, &length))
1063                     {
1064                         /* The RSAPUBKEY structure directly follows the BLOBHEADER */
1065                         RSAPUBKEY *pk1 = (LPVOID)(pblob1 + 1),
1066                                   *pk2 = (LPVOID)(pblob2 + 1);
1067                         ret = (pk1->bitlen == pk2->bitlen) && (pk1->pubexp == pk2->pubexp)
1068                                  && !memcmp(pk1 + 1, pk2 + 1, pk1->bitlen/8);
1069                     }
1070                     CryptMemFree(pblob2);
1071                 }
1072             }
1073             CryptMemFree(pblob1);
1074         }
1075
1076         break;
1077     }
1078     }
1079     return ret;
1080 }
1081
1082 DWORD WINAPI CertGetPublicKeyLength(DWORD dwCertEncodingType,
1083  PCERT_PUBLIC_KEY_INFO pPublicKey)
1084 {
1085     DWORD len = 0;
1086
1087     TRACE("(%08x, %p)\n", dwCertEncodingType, pPublicKey);
1088
1089     if (GET_CERT_ENCODING_TYPE(dwCertEncodingType) != X509_ASN_ENCODING)
1090     {
1091         SetLastError(ERROR_FILE_NOT_FOUND);
1092         return 0;
1093     }
1094     if (pPublicKey->Algorithm.pszObjId &&
1095      !strcmp(pPublicKey->Algorithm.pszObjId, szOID_RSA_DH))
1096     {
1097         FIXME("unimplemented for DH public keys\n");
1098         SetLastError(CRYPT_E_ASN1_BADTAG);
1099     }
1100     else
1101     {
1102         DWORD size;
1103         PBYTE buf;
1104         BOOL ret = CryptDecodeObjectEx(dwCertEncodingType,
1105          RSA_CSP_PUBLICKEYBLOB, pPublicKey->PublicKey.pbData,
1106          pPublicKey->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &buf,
1107          &size);
1108
1109         if (ret)
1110         {
1111             RSAPUBKEY *rsaPubKey = (RSAPUBKEY *)(buf + sizeof(BLOBHEADER));
1112
1113             len = rsaPubKey->bitlen;
1114             LocalFree(buf);
1115         }
1116     }
1117     return len;
1118 }
1119
1120 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
1121  DWORD dwFlags, const void *pvPara);
1122
1123 static BOOL compare_cert_any(PCCERT_CONTEXT pCertContext, DWORD dwType,
1124  DWORD dwFlags, const void *pvPara)
1125 {
1126     return TRUE;
1127 }
1128
1129 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1130  DWORD dwFlags, const void *pvPara)
1131 {
1132     BOOL ret;
1133     BYTE hash[16];
1134     DWORD size = sizeof(hash);
1135
1136     ret = CertGetCertificateContextProperty(pCertContext,
1137      CERT_MD5_HASH_PROP_ID, hash, &size);
1138     if (ret)
1139     {
1140         const CRYPT_HASH_BLOB *pHash = pvPara;
1141
1142         if (size == pHash->cbData)
1143             ret = !memcmp(pHash->pbData, hash, size);
1144         else
1145             ret = FALSE;
1146     }
1147     return ret;
1148 }
1149
1150 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1151  DWORD dwFlags, const void *pvPara)
1152 {
1153     BOOL ret;
1154     BYTE hash[20];
1155     DWORD size = sizeof(hash);
1156
1157     ret = CertGetCertificateContextProperty(pCertContext,
1158      CERT_SHA1_HASH_PROP_ID, hash, &size);
1159     if (ret)
1160     {
1161         const CRYPT_HASH_BLOB *pHash = pvPara;
1162
1163         if (size == pHash->cbData)
1164             ret = !memcmp(pHash->pbData, hash, size);
1165         else
1166             ret = FALSE;
1167     }
1168     return ret;
1169 }
1170
1171 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
1172  DWORD dwFlags, const void *pvPara)
1173 {
1174     CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
1175     BOOL ret;
1176
1177     if (dwType & CERT_INFO_SUBJECT_FLAG)
1178         toCompare = &pCertContext->pCertInfo->Subject;
1179     else
1180         toCompare = &pCertContext->pCertInfo->Issuer;
1181     ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1182      toCompare, blob);
1183     return ret;
1184 }
1185
1186 static BOOL compare_cert_by_public_key(PCCERT_CONTEXT pCertContext,
1187  DWORD dwType, DWORD dwFlags, const void *pvPara)
1188 {
1189     CERT_PUBLIC_KEY_INFO *publicKey = (CERT_PUBLIC_KEY_INFO *)pvPara;
1190     BOOL ret;
1191
1192     ret = CertComparePublicKeyInfo(pCertContext->dwCertEncodingType,
1193      &pCertContext->pCertInfo->SubjectPublicKeyInfo, publicKey);
1194     return ret;
1195 }
1196
1197 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
1198  DWORD dwType, DWORD dwFlags, const void *pvPara)
1199 {
1200     CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
1201     BOOL ret;
1202
1203     /* Matching serial number and subject match.. */
1204     ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1205      &pCertInfo->Issuer, &pCertContext->pCertInfo->Subject);
1206     if (ret)
1207         ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1208          &pCertInfo->SerialNumber);
1209     else
1210     {
1211         /* failing that, if the serial number and issuer match, we match */
1212         ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1213          &pCertInfo->SerialNumber);
1214         if (ret)
1215             ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1216              &pCertInfo->Issuer, &pCertContext->pCertInfo->Issuer);
1217     }
1218     TRACE("returning %d\n", ret);
1219     return ret;
1220 }
1221
1222 static BOOL compare_cert_by_cert_id(PCCERT_CONTEXT pCertContext, DWORD dwType,
1223  DWORD dwFlags, const void *pvPara)
1224 {
1225     CERT_ID *id = (CERT_ID *)pvPara;
1226     BOOL ret;
1227
1228     switch (id->dwIdChoice)
1229     {
1230     case CERT_ID_ISSUER_SERIAL_NUMBER:
1231         ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1232          &pCertContext->pCertInfo->Issuer, &id->u.IssuerSerialNumber.Issuer);
1233         if (ret)
1234             ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1235              &id->u.IssuerSerialNumber.SerialNumber);
1236         break;
1237     case CERT_ID_SHA1_HASH:
1238         ret = compare_cert_by_sha1_hash(pCertContext, dwType, dwFlags,
1239          &id->u.HashId);
1240         break;
1241     case CERT_ID_KEY_IDENTIFIER:
1242     {
1243         DWORD size = 0;
1244
1245         ret = CertGetCertificateContextProperty(pCertContext,
1246          CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
1247         if (ret && size == id->u.KeyId.cbData)
1248         {
1249             LPBYTE buf = CryptMemAlloc(size);
1250
1251             if (buf)
1252             {
1253                 CertGetCertificateContextProperty(pCertContext,
1254                  CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
1255                 ret = !memcmp(buf, id->u.KeyId.pbData, size);
1256                 CryptMemFree(buf);
1257             }
1258         }
1259         else
1260             ret = FALSE;
1261         break;
1262     }
1263     default:
1264         ret = FALSE;
1265         break;
1266     }
1267     return ret;
1268 }
1269
1270 static BOOL compare_cert_by_issuer(PCCERT_CONTEXT pCertContext, DWORD dwType,
1271  DWORD dwFlags, const void *pvPara)
1272 {
1273     BOOL ret = FALSE;
1274     PCCERT_CONTEXT subject = pvPara;
1275     PCERT_EXTENSION ext;
1276     DWORD size;
1277
1278     if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1279      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1280     {
1281         CERT_AUTHORITY_KEY_ID_INFO *info;
1282
1283         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1284          X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1285          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1286          &info, &size);
1287         if (ret)
1288         {
1289             CERT_ID id;
1290
1291             if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1292             {
1293                 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1294                 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1295                  sizeof(CERT_NAME_BLOB));
1296                 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1297                  &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1298                 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1299                  &id);
1300             }
1301             else if (info->KeyId.cbData)
1302             {
1303                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1304                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1305                 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1306                  &id);
1307             }
1308             else
1309                 ret = FALSE;
1310             LocalFree(info);
1311         }
1312     }
1313     else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1314      subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1315     {
1316         CERT_AUTHORITY_KEY_ID2_INFO *info;
1317
1318         ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1319          X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1320          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1321          &info, &size);
1322         if (ret)
1323         {
1324             CERT_ID id;
1325
1326             if (info->AuthorityCertIssuer.cAltEntry &&
1327              info->AuthorityCertSerialNumber.cbData)
1328             {
1329                 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1330                 DWORD i;
1331
1332                 for (i = 0; !directoryName &&
1333                  i < info->AuthorityCertIssuer.cAltEntry; i++)
1334                     if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1335                      == CERT_ALT_NAME_DIRECTORY_NAME)
1336                         directoryName =
1337                          &info->AuthorityCertIssuer.rgAltEntry[i];
1338                 if (directoryName)
1339                 {
1340                     id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1341                     memcpy(&id.u.IssuerSerialNumber.Issuer,
1342                      &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1343                     memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1344                      &info->AuthorityCertSerialNumber,
1345                      sizeof(CRYPT_INTEGER_BLOB));
1346                     ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1347                      &id);
1348                 }
1349                 else
1350                 {
1351                     FIXME("no supported name type in authority key id2\n");
1352                     ret = FALSE;
1353                 }
1354             }
1355             else if (info->KeyId.cbData)
1356             {
1357                 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1358                 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1359                 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1360                  &id);
1361             }
1362             else
1363                 ret = FALSE;
1364             LocalFree(info);
1365         }
1366     }
1367     else
1368        ret = compare_cert_by_name(pCertContext,
1369         CERT_COMPARE_NAME | CERT_COMPARE_SUBJECT_CERT, dwFlags,
1370         &subject->pCertInfo->Issuer);
1371     return ret;
1372 }
1373
1374 static BOOL compare_existing_cert(PCCERT_CONTEXT pCertContext, DWORD dwType,
1375  DWORD dwFlags, const void *pvPara)
1376 {
1377     PCCERT_CONTEXT toCompare = pvPara;
1378     return CertCompareCertificate(pCertContext->dwCertEncodingType,
1379      pCertContext->pCertInfo, toCompare->pCertInfo);
1380 }
1381
1382 static BOOL compare_cert_by_signature_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1383  DWORD dwFlags, const void *pvPara)
1384 {
1385     const CRYPT_HASH_BLOB *hash = pvPara;
1386     DWORD size = 0;
1387     BOOL ret;
1388
1389     ret = CertGetCertificateContextProperty(pCertContext,
1390      CERT_SIGNATURE_HASH_PROP_ID, NULL, &size);
1391     if (ret && size == hash->cbData)
1392     {
1393         LPBYTE buf = CryptMemAlloc(size);
1394
1395         if (buf)
1396         {
1397             CertGetCertificateContextProperty(pCertContext,
1398              CERT_SIGNATURE_HASH_PROP_ID, buf, &size);
1399             ret = !memcmp(buf, hash->pbData, size);
1400             CryptMemFree(buf);
1401         }
1402     }
1403     else
1404         ret = FALSE;
1405     return ret;
1406 }
1407
1408 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
1409  DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
1410  PCCERT_CONTEXT pPrevCertContext)
1411 {
1412     PCCERT_CONTEXT ret;
1413     CertCompareFunc compare;
1414
1415     TRACE("(%p, %08x, %08x, %08x, %p, %p)\n", hCertStore, dwCertEncodingType,
1416          dwFlags, dwType, pvPara, pPrevCertContext);
1417
1418     switch (dwType >> CERT_COMPARE_SHIFT)
1419     {
1420     case CERT_COMPARE_ANY:
1421         compare = compare_cert_any;
1422         break;
1423     case CERT_COMPARE_MD5_HASH:
1424         compare = compare_cert_by_md5_hash;
1425         break;
1426     case CERT_COMPARE_SHA1_HASH:
1427         compare = compare_cert_by_sha1_hash;
1428         break;
1429     case CERT_COMPARE_NAME:
1430         compare = compare_cert_by_name;
1431         break;
1432     case CERT_COMPARE_PUBLIC_KEY:
1433         compare = compare_cert_by_public_key;
1434         break;
1435     case CERT_COMPARE_SUBJECT_CERT:
1436         compare = compare_cert_by_subject_cert;
1437         break;
1438     case CERT_COMPARE_CERT_ID:
1439         compare = compare_cert_by_cert_id;
1440         break;
1441     case CERT_COMPARE_ISSUER_OF:
1442         compare = compare_cert_by_issuer;
1443         break;
1444     case CERT_COMPARE_EXISTING:
1445         compare = compare_existing_cert;
1446         break;
1447     case CERT_COMPARE_SIGNATURE_HASH:
1448         compare = compare_cert_by_signature_hash;
1449         break;
1450     default:
1451         FIXME("find type %08x unimplemented\n", dwType);
1452         compare = NULL;
1453     }
1454
1455     if (compare)
1456     {
1457         BOOL matches = FALSE;
1458
1459         ret = pPrevCertContext;
1460         do {
1461             ret = CertEnumCertificatesInStore(hCertStore, ret);
1462             if (ret)
1463                 matches = compare(ret, dwType, dwFlags, pvPara);
1464         } while (ret != NULL && !matches);
1465         if (!ret)
1466             SetLastError(CRYPT_E_NOT_FOUND);
1467     }
1468     else
1469     {
1470         SetLastError(CRYPT_E_NOT_FOUND);
1471         ret = NULL;
1472     }
1473     TRACE("returning %p\n", ret);
1474     return ret;
1475 }
1476
1477 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
1478  DWORD dwCertEncodingType, PCERT_INFO pCertId)
1479 {
1480     TRACE("(%p, %08x, %p)\n", hCertStore, dwCertEncodingType, pCertId);
1481
1482     if (!pCertId)
1483     {
1484         SetLastError(E_INVALIDARG);
1485         return NULL;
1486     }
1487     return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
1488      CERT_FIND_SUBJECT_CERT, pCertId, NULL);
1489 }
1490
1491 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
1492  PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
1493 {
1494     static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
1495      CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
1496
1497     if (*pdwFlags & ~supportedFlags)
1498     {
1499         SetLastError(E_INVALIDARG);
1500         return FALSE;
1501     }
1502     if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
1503     {
1504         DWORD flags = 0;
1505         PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
1506          NULL, &flags);
1507
1508         /* FIXME: what if the CRL has expired? */
1509         if (crl)
1510         {
1511             if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
1512              pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
1513                 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
1514         }
1515         else
1516             *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
1517     }
1518     if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
1519     {
1520         if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
1521             *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
1522     }
1523     if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
1524     {
1525         if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
1526          CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
1527          CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
1528             *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
1529     }
1530     return TRUE;
1531 }
1532
1533 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
1534  PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
1535  DWORD *pdwFlags)
1536 {
1537     PCCERT_CONTEXT ret;
1538
1539     TRACE("(%p, %p, %p, %08x)\n", hCertStore, pSubjectContext,
1540      pPrevIssuerContext, *pdwFlags);
1541
1542     if (!pSubjectContext)
1543     {
1544         SetLastError(E_INVALIDARG);
1545         return NULL;
1546     }
1547
1548     ret = CertFindCertificateInStore(hCertStore,
1549      pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
1550      pSubjectContext, pPrevIssuerContext);
1551     if (ret)
1552     {
1553         if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
1554          pdwFlags))
1555         {
1556             CertFreeCertificateContext(ret);
1557             ret = NULL;
1558         }
1559     }
1560     TRACE("returning %p\n", ret);
1561     return ret;
1562 }
1563
1564 typedef struct _OLD_CERT_REVOCATION_STATUS {
1565     DWORD cbSize;
1566     DWORD dwIndex;
1567     DWORD dwError;
1568     DWORD dwReason;
1569 } OLD_CERT_REVOCATION_STATUS, *POLD_CERT_REVOCATION_STATUS;
1570
1571 typedef BOOL (WINAPI *CertVerifyRevocationFunc)(DWORD, DWORD, DWORD,
1572  void **, DWORD, PCERT_REVOCATION_PARA, PCERT_REVOCATION_STATUS);
1573
1574 BOOL WINAPI CertVerifyRevocation(DWORD dwEncodingType, DWORD dwRevType,
1575  DWORD cContext, PVOID rgpvContext[], DWORD dwFlags,
1576  PCERT_REVOCATION_PARA pRevPara, PCERT_REVOCATION_STATUS pRevStatus)
1577 {
1578     BOOL ret;
1579
1580     TRACE("(%08x, %d, %d, %p, %08x, %p, %p)\n", dwEncodingType, dwRevType,
1581      cContext, rgpvContext, dwFlags, pRevPara, pRevStatus);
1582
1583     if (pRevStatus->cbSize != sizeof(OLD_CERT_REVOCATION_STATUS) &&
1584      pRevStatus->cbSize != sizeof(CERT_REVOCATION_STATUS))
1585     {
1586         SetLastError(E_INVALIDARG);
1587         return FALSE;
1588     }
1589     if (cContext)
1590     {
1591         static HCRYPTOIDFUNCSET set = NULL;
1592         DWORD size;
1593
1594         if (!set)
1595             set = CryptInitOIDFunctionSet(CRYPT_OID_VERIFY_REVOCATION_FUNC, 0);
1596         ret = CryptGetDefaultOIDDllList(set, dwEncodingType, NULL, &size);
1597         if (ret)
1598         {
1599             if (size == 1)
1600             {
1601                 /* empty list */
1602                 SetLastError(CRYPT_E_NO_REVOCATION_DLL);
1603                 ret = FALSE;
1604             }
1605             else
1606             {
1607                 LPWSTR dllList = CryptMemAlloc(size * sizeof(WCHAR)), ptr;
1608
1609                 if (dllList)
1610                 {
1611                     ret = CryptGetDefaultOIDDllList(set, dwEncodingType,
1612                      dllList, &size);
1613                     if (ret)
1614                     {
1615                         for (ptr = dllList; ret && *ptr;
1616                          ptr += lstrlenW(ptr) + 1)
1617                         {
1618                             CertVerifyRevocationFunc func;
1619                             HCRYPTOIDFUNCADDR hFunc;
1620
1621                             ret = CryptGetDefaultOIDFunctionAddress(set,
1622                              dwEncodingType, ptr, 0, (void **)&func, &hFunc);
1623                             if (ret)
1624                             {
1625                                 ret = func(dwEncodingType, dwRevType, cContext,
1626                                  rgpvContext, dwFlags, pRevPara, pRevStatus);
1627                                 CryptFreeOIDFunctionAddress(hFunc, 0);
1628                             }
1629                         }
1630                     }
1631                     CryptMemFree(dllList);
1632                 }
1633                 else
1634                 {
1635                     SetLastError(ERROR_OUTOFMEMORY);
1636                     ret = FALSE;
1637                 }
1638             }
1639         }
1640     }
1641     else
1642         ret = TRUE;
1643     return ret;
1644 }
1645
1646 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
1647  CRYPT_ATTRIBUTE rgAttr[])
1648 {
1649     PCRYPT_ATTRIBUTE ret = NULL;
1650     DWORD i;
1651
1652     TRACE("%s %d %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
1653
1654     if (!cAttr)
1655         return NULL;
1656     if (!pszObjId)
1657     {
1658         SetLastError(ERROR_INVALID_PARAMETER);
1659         return NULL;
1660     }
1661
1662     for (i = 0; !ret && i < cAttr; i++)
1663         if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
1664             ret = &rgAttr[i];
1665     return ret;
1666 }
1667
1668 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
1669  CERT_EXTENSION rgExtensions[])
1670 {
1671     PCERT_EXTENSION ret = NULL;
1672     DWORD i;
1673
1674     TRACE("%s %d %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
1675
1676     if (!cExtensions)
1677         return NULL;
1678     if (!pszObjId)
1679     {
1680         SetLastError(ERROR_INVALID_PARAMETER);
1681         return NULL;
1682     }
1683
1684     for (i = 0; !ret && i < cExtensions; i++)
1685         if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
1686          rgExtensions[i].pszObjId))
1687             ret = &rgExtensions[i];
1688     return ret;
1689 }
1690
1691 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
1692 {
1693     PCERT_RDN_ATTR ret = NULL;
1694     DWORD i, j;
1695
1696     TRACE("%s %p\n", debugstr_a(pszObjId), pName);
1697
1698     if (!pszObjId)
1699     {
1700         SetLastError(ERROR_INVALID_PARAMETER);
1701         return NULL;
1702     }
1703
1704     for (i = 0; !ret && i < pName->cRDN; i++)
1705         for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
1706             if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
1707              pName->rgRDN[i].rgRDNAttr[j].pszObjId))
1708                 ret = &pName->rgRDN[i].rgRDNAttr[j];
1709     return ret;
1710 }
1711
1712 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
1713  PCERT_INFO pCertInfo)
1714 {
1715     FILETIME fileTime;
1716     LONG ret;
1717
1718     if (!pTimeToVerify)
1719     {
1720         GetSystemTimeAsFileTime(&fileTime);
1721         pTimeToVerify = &fileTime;
1722     }
1723     if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
1724     {
1725         ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
1726         if (ret < 0)
1727             ret = 0;
1728     }
1729     return ret;
1730 }
1731
1732 BOOL WINAPI CertVerifyValidityNesting(PCERT_INFO pSubjectInfo,
1733  PCERT_INFO pIssuerInfo)
1734 {
1735     TRACE("(%p, %p)\n", pSubjectInfo, pIssuerInfo);
1736
1737     return CertVerifyTimeValidity(&pSubjectInfo->NotBefore, pIssuerInfo) == 0
1738      && CertVerifyTimeValidity(&pSubjectInfo->NotAfter, pIssuerInfo) == 0;
1739 }
1740
1741 BOOL WINAPI CryptHashCertificate(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
1742  DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
1743  DWORD *pcbComputedHash)
1744 {
1745     BOOL ret = TRUE;
1746     HCRYPTHASH hHash = 0;
1747
1748     TRACE("(%08lx, %d, %08x, %p, %d, %p, %p)\n", hCryptProv, Algid, dwFlags,
1749      pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
1750
1751     if (!hCryptProv)
1752         hCryptProv = CRYPT_GetDefaultProvider();
1753     if (!Algid)
1754         Algid = CALG_SHA1;
1755     if (ret)
1756     {
1757         ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1758         if (ret)
1759         {
1760             ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
1761             if (ret)
1762                 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1763                  pcbComputedHash, 0);
1764             CryptDestroyHash(hHash);
1765         }
1766     }
1767     return ret;
1768 }
1769
1770 BOOL WINAPI CryptHashPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
1771  DWORD dwFlags, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo,
1772  BYTE *pbComputedHash, DWORD *pcbComputedHash)
1773 {
1774     BOOL ret = TRUE;
1775     HCRYPTHASH hHash = 0;
1776
1777     TRACE("(%08lx, %d, %08x, %d, %p, %p, %p)\n", hCryptProv, Algid, dwFlags,
1778      dwCertEncodingType, pInfo, pbComputedHash, pcbComputedHash);
1779
1780     if (!hCryptProv)
1781         hCryptProv = CRYPT_GetDefaultProvider();
1782     if (!Algid)
1783         Algid = CALG_MD5;
1784     if (ret)
1785     {
1786         BYTE *buf;
1787         DWORD size = 0;
1788
1789         ret = CryptEncodeObjectEx(dwCertEncodingType, X509_PUBLIC_KEY_INFO,
1790          pInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL, &buf, &size);
1791         if (ret)
1792         {
1793             ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1794             if (ret)
1795             {
1796                 ret = CryptHashData(hHash, buf, size, 0);
1797                 if (ret)
1798                     ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1799                      pcbComputedHash, 0);
1800                 CryptDestroyHash(hHash);
1801             }
1802             LocalFree(buf);
1803         }
1804     }
1805     return ret;
1806 }
1807
1808 BOOL WINAPI CryptHashToBeSigned(HCRYPTPROV_LEGACY hCryptProv,
1809  DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
1810  BYTE *pbComputedHash, DWORD *pcbComputedHash)
1811 {
1812     BOOL ret;
1813     CERT_SIGNED_CONTENT_INFO *info;
1814     DWORD size;
1815
1816     TRACE("(%08lx, %08x, %p, %d, %p, %d)\n", hCryptProv, dwCertEncodingType,
1817      pbEncoded, cbEncoded, pbComputedHash, *pcbComputedHash);
1818
1819     ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
1820      pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &size);
1821     if (ret)
1822     {
1823         PCCRYPT_OID_INFO oidInfo;
1824         HCRYPTHASH hHash;
1825
1826         if (!hCryptProv)
1827             hCryptProv = CRYPT_GetDefaultProvider();
1828         oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1829          info->SignatureAlgorithm.pszObjId, 0);
1830         if (!oidInfo)
1831         {
1832             SetLastError(NTE_BAD_ALGID);
1833             ret = FALSE;
1834         }
1835         else
1836         {
1837             ret = CryptCreateHash(hCryptProv, oidInfo->u.Algid, 0, 0, &hHash);
1838             if (ret)
1839             {
1840                 ret = CryptHashData(hHash, info->ToBeSigned.pbData,
1841                  info->ToBeSigned.cbData, 0);
1842                 if (ret)
1843                     ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1844                      pcbComputedHash, 0);
1845                 CryptDestroyHash(hHash);
1846             }
1847         }
1848         LocalFree(info);
1849     }
1850     return ret;
1851 }
1852
1853 BOOL WINAPI CryptSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
1854  DWORD dwKeySpec, DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
1855  DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1856  const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
1857 {
1858     BOOL ret;
1859     PCCRYPT_OID_INFO info;
1860     HCRYPTHASH hHash;
1861
1862     TRACE("(%08lx, %d, %d, %p, %d, %p, %p, %p, %p)\n", hCryptProv,
1863      dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
1864      pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
1865
1866     info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1867      pSignatureAlgorithm->pszObjId, 0);
1868     if (!info)
1869     {
1870         SetLastError(NTE_BAD_ALGID);
1871         return FALSE;
1872     }
1873     if (info->dwGroupId == CRYPT_HASH_ALG_OID_GROUP_ID)
1874     {
1875         if (!hCryptProv)
1876             hCryptProv = CRYPT_GetDefaultProvider();
1877         ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
1878         if (ret)
1879         {
1880             ret = CryptHashData(hHash, pbEncodedToBeSigned,
1881              cbEncodedToBeSigned, 0);
1882             if (ret)
1883                 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbSignature,
1884                  pcbSignature, 0);
1885             CryptDestroyHash(hHash);
1886         }
1887     }
1888     else
1889     {
1890         if (!hCryptProv)
1891         {
1892             SetLastError(ERROR_INVALID_PARAMETER);
1893             ret = FALSE;
1894         }
1895         else
1896         {
1897             ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
1898             if (ret)
1899             {
1900                 ret = CryptHashData(hHash, pbEncodedToBeSigned,
1901                  cbEncodedToBeSigned, 0);
1902                 if (ret)
1903                     ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
1904                      pcbSignature);
1905                 CryptDestroyHash(hHash);
1906             }
1907         }
1908     }
1909     return ret;
1910 }
1911
1912 BOOL WINAPI CryptSignAndEncodeCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
1913  DWORD dwKeySpec, DWORD dwCertEncodingType, LPCSTR lpszStructType,
1914  const void *pvStructInfo, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1915  const void *pvHashAuxInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
1916 {
1917     BOOL ret;
1918     DWORD encodedSize, hashSize;
1919
1920     TRACE("(%08lx, %d, %d, %s, %p, %p, %p, %p, %p)\n", hCryptProv, dwKeySpec,
1921      dwCertEncodingType, debugstr_a(lpszStructType), pvStructInfo,
1922      pSignatureAlgorithm, pvHashAuxInfo, pbEncoded, pcbEncoded);
1923
1924     ret = CryptEncodeObject(dwCertEncodingType, lpszStructType, pvStructInfo,
1925      NULL, &encodedSize);
1926     if (ret)
1927     {
1928         PBYTE encoded = CryptMemAlloc(encodedSize);
1929
1930         if (encoded)
1931         {
1932             ret = CryptEncodeObject(dwCertEncodingType, lpszStructType,
1933              pvStructInfo, encoded, &encodedSize);
1934             if (ret)
1935             {
1936                 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
1937                  dwCertEncodingType, encoded, encodedSize, pSignatureAlgorithm,
1938                  pvHashAuxInfo, NULL, &hashSize);
1939                 if (ret)
1940                 {
1941                     PBYTE hash = CryptMemAlloc(hashSize);
1942
1943                     if (hash)
1944                     {
1945                         ret = CryptSignCertificate(hCryptProv, dwKeySpec,
1946                          dwCertEncodingType, encoded, encodedSize,
1947                          pSignatureAlgorithm, pvHashAuxInfo, hash, &hashSize);
1948                         if (ret)
1949                         {
1950                             CERT_SIGNED_CONTENT_INFO info = { { 0 } };
1951
1952                             info.ToBeSigned.cbData = encodedSize;
1953                             info.ToBeSigned.pbData = encoded;
1954                             memcpy(&info.SignatureAlgorithm,
1955                              pSignatureAlgorithm,
1956                              sizeof(info.SignatureAlgorithm));
1957                             info.Signature.cbData = hashSize;
1958                             info.Signature.pbData = hash;
1959                             info.Signature.cUnusedBits = 0;
1960                             ret = CryptEncodeObject(dwCertEncodingType,
1961                              X509_CERT, &info, pbEncoded, pcbEncoded);
1962                         }
1963                         CryptMemFree(hash);
1964                     }
1965                 }
1966             }
1967             CryptMemFree(encoded);
1968         }
1969     }
1970     return ret;
1971 }
1972
1973 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV_LEGACY hCryptProv,
1974  DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
1975  PCERT_PUBLIC_KEY_INFO pPublicKey)
1976 {
1977     return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
1978      CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, (void *)pbEncoded,
1979      CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
1980 }
1981
1982 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv,
1983  DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pubKeyInfo,
1984  const CERT_SIGNED_CONTENT_INFO *signedCert)
1985 {
1986     BOOL ret;
1987     HCRYPTKEY key;
1988     PCCRYPT_OID_INFO info;
1989     ALG_ID pubKeyID, hashID;
1990
1991     info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1992      signedCert->SignatureAlgorithm.pszObjId, 0);
1993     if (!info || info->dwGroupId != CRYPT_SIGN_ALG_OID_GROUP_ID)
1994     {
1995         SetLastError(NTE_BAD_ALGID);
1996         return FALSE;
1997     }
1998     hashID = info->u.Algid;
1999     if (info->ExtraInfo.cbData >= sizeof(ALG_ID))
2000         pubKeyID = *(ALG_ID *)info->ExtraInfo.pbData;
2001     else
2002         pubKeyID = hashID;
2003     /* Load the default provider if necessary */
2004     if (!hCryptProv)
2005         hCryptProv = CRYPT_GetDefaultProvider();
2006     ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
2007      pubKeyInfo, pubKeyID, 0, NULL, &key);
2008     if (ret)
2009     {
2010         HCRYPTHASH hash;
2011
2012         ret = CryptCreateHash(hCryptProv, hashID, 0, 0, &hash);
2013         if (ret)
2014         {
2015             ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
2016              signedCert->ToBeSigned.cbData, 0);
2017             if (ret)
2018                 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
2019                  signedCert->Signature.cbData, key, NULL, 0);
2020             CryptDestroyHash(hash);
2021         }
2022         CryptDestroyKey(key);
2023     }
2024     return ret;
2025 }
2026
2027 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV_LEGACY hCryptProv,
2028  DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
2029  DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
2030 {
2031     BOOL ret = TRUE;
2032     CRYPT_DATA_BLOB subjectBlob;
2033
2034     TRACE("(%08lx, %d, %d, %p, %d, %p, %08x, %p)\n", hCryptProv,
2035      dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
2036      dwFlags, pvReserved);
2037
2038     switch (dwSubjectType)
2039     {
2040     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
2041     {
2042         PCRYPT_DATA_BLOB blob = pvSubject;
2043
2044         subjectBlob.pbData = blob->pbData;
2045         subjectBlob.cbData = blob->cbData;
2046         break;
2047     }
2048     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
2049     {
2050         PCERT_CONTEXT context = pvSubject;
2051
2052         subjectBlob.pbData = context->pbCertEncoded;
2053         subjectBlob.cbData = context->cbCertEncoded;
2054         break;
2055     }
2056     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
2057     {
2058         PCRL_CONTEXT context = pvSubject;
2059
2060         subjectBlob.pbData = context->pbCrlEncoded;
2061         subjectBlob.cbData = context->cbCrlEncoded;
2062         break;
2063     }
2064     default:
2065         SetLastError(E_INVALIDARG);
2066         ret = FALSE;
2067     }
2068
2069     if (ret)
2070     {
2071         PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
2072         DWORD size = 0;
2073
2074         ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2075          subjectBlob.pbData, subjectBlob.cbData,
2076          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2077          &signedCert, &size);
2078         if (ret)
2079         {
2080             switch (dwIssuerType)
2081             {
2082             case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
2083                 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2084                  dwCertEncodingType, pvIssuer,
2085                  signedCert);
2086                 break;
2087             case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
2088                 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2089                  dwCertEncodingType,
2090                  &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
2091                  signedCert);
2092                 break;
2093             case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
2094                 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
2095                 ret = FALSE;
2096                 break;
2097             case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
2098                 if (pvIssuer)
2099                 {
2100                     SetLastError(E_INVALIDARG);
2101                     ret = FALSE;
2102                 }
2103                 else
2104                 {
2105                     FIXME("unimplemented for NULL signer\n");
2106                     SetLastError(E_INVALIDARG);
2107                     ret = FALSE;
2108                 }
2109                 break;
2110             default:
2111                 SetLastError(E_INVALIDARG);
2112                 ret = FALSE;
2113             }
2114             LocalFree(signedCert);
2115         }
2116     }
2117     return ret;
2118 }
2119
2120 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
2121  PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
2122 {
2123     PCERT_ENHKEY_USAGE usage = NULL;
2124     DWORD bytesNeeded;
2125     BOOL ret = TRUE;
2126
2127     if (!pCertContext || !pcbUsage)
2128     {
2129         SetLastError(ERROR_INVALID_PARAMETER);
2130         return FALSE;
2131     }
2132
2133     TRACE("(%p, %08x, %p, %d)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
2134
2135     if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
2136     {
2137         DWORD propSize = 0;
2138
2139         if (CertGetCertificateContextProperty(pCertContext,
2140          CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
2141         {
2142             LPBYTE buf = CryptMemAlloc(propSize);
2143
2144             if (buf)
2145             {
2146                 if (CertGetCertificateContextProperty(pCertContext,
2147                  CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
2148                 {
2149                     ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
2150                      X509_ENHANCED_KEY_USAGE, buf, propSize,
2151                      CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
2152                 }
2153                 CryptMemFree(buf);
2154             }
2155         }
2156     }
2157     if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
2158     {
2159         PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
2160          pCertContext->pCertInfo->cExtension,
2161          pCertContext->pCertInfo->rgExtension);
2162
2163         if (ext)
2164         {
2165             ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
2166              X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
2167              CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
2168         }
2169     }
2170     if (!usage)
2171     {
2172         /* If a particular location is specified, this should fail.  Otherwise
2173          * it should succeed with an empty usage.  (This is true on Win2k and
2174          * later, which we emulate.)
2175          */
2176         if (dwFlags)
2177         {
2178             SetLastError(CRYPT_E_NOT_FOUND);
2179             ret = FALSE;
2180         }
2181         else
2182             bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
2183     }
2184
2185     if (ret)
2186     {
2187         if (!pUsage)
2188             *pcbUsage = bytesNeeded;
2189         else if (*pcbUsage < bytesNeeded)
2190         {
2191             SetLastError(ERROR_MORE_DATA);
2192             *pcbUsage = bytesNeeded;
2193             ret = FALSE;
2194         }
2195         else
2196         {
2197             *pcbUsage = bytesNeeded;
2198             if (usage)
2199             {
2200                 DWORD i;
2201                 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
2202                  sizeof(CERT_ENHKEY_USAGE) +
2203                  usage->cUsageIdentifier * sizeof(LPSTR));
2204
2205                 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
2206                 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
2207                  sizeof(CERT_ENHKEY_USAGE));
2208                 for (i = 0; i < usage->cUsageIdentifier; i++)
2209                 {
2210                     pUsage->rgpszUsageIdentifier[i] = nextOID;
2211                     strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
2212                     nextOID += strlen(nextOID) + 1;
2213                 }
2214             }
2215             else
2216                 pUsage->cUsageIdentifier = 0;
2217         }
2218     }
2219     if (usage)
2220         LocalFree(usage);
2221     TRACE("returning %d\n", ret);
2222     return ret;
2223 }
2224
2225 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
2226  PCERT_ENHKEY_USAGE pUsage)
2227 {
2228     BOOL ret;
2229
2230     TRACE("(%p, %p)\n", pCertContext, pUsage);
2231
2232     if (pUsage)
2233     {
2234         CRYPT_DATA_BLOB blob = { 0, NULL };
2235
2236         ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
2237          pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
2238         if (ret)
2239         {
2240             ret = CertSetCertificateContextProperty(pCertContext,
2241              CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
2242             LocalFree(blob.pbData);
2243         }
2244     }
2245     else
2246         ret = CertSetCertificateContextProperty(pCertContext,
2247          CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
2248     return ret;
2249 }
2250
2251 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
2252  LPCSTR pszUsageIdentifier)
2253 {
2254     BOOL ret;
2255     DWORD size;
2256
2257     TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
2258
2259     if (CertGetEnhancedKeyUsage(pCertContext,
2260      CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
2261     {
2262         PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
2263
2264         if (usage)
2265         {
2266             ret = CertGetEnhancedKeyUsage(pCertContext,
2267              CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
2268             if (ret)
2269             {
2270                 DWORD i;
2271                 BOOL exists = FALSE;
2272
2273                 /* Make sure usage doesn't already exist */
2274                 for (i = 0; !exists && i < usage->cUsageIdentifier; i++)
2275                 {
2276                     if (!strcmp(usage->rgpszUsageIdentifier[i],
2277                      pszUsageIdentifier))
2278                         exists = TRUE;
2279                 }
2280                 if (!exists)
2281                 {
2282                     PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
2283                      sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
2284
2285                     if (newUsage)
2286                     {
2287                         LPSTR nextOID;
2288
2289                         newUsage->rgpszUsageIdentifier = (LPSTR *)
2290                          ((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
2291                         nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier
2292                           + (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
2293                         for (i = 0; i < usage->cUsageIdentifier; i++)
2294                         {
2295                             newUsage->rgpszUsageIdentifier[i] = nextOID;
2296                             strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
2297                             nextOID += strlen(nextOID) + 1;
2298                         }
2299                         newUsage->rgpszUsageIdentifier[i] = nextOID;
2300                         strcpy(nextOID, pszUsageIdentifier);
2301                         newUsage->cUsageIdentifier = i + 1;
2302                         ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
2303                         CryptMemFree(newUsage);
2304                     }
2305                     else
2306                         ret = FALSE;
2307                 }
2308             }
2309             CryptMemFree(usage);
2310         }
2311         else
2312             ret = FALSE;
2313     }
2314     else
2315     {
2316         PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
2317          sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
2318
2319         if (usage)
2320         {
2321             usage->rgpszUsageIdentifier =
2322              (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
2323             usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
2324              sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
2325             strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
2326             usage->cUsageIdentifier = 1;
2327             ret = CertSetEnhancedKeyUsage(pCertContext, usage);
2328             CryptMemFree(usage);
2329         }
2330         else
2331             ret = FALSE;
2332     }
2333     return ret;
2334 }
2335
2336 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
2337  LPCSTR pszUsageIdentifier)
2338 {
2339     BOOL ret;
2340     DWORD size;
2341     CERT_ENHKEY_USAGE usage;
2342
2343     TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
2344
2345     size = sizeof(usage);
2346     ret = CertGetEnhancedKeyUsage(pCertContext,
2347      CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
2348     if (!ret && GetLastError() == ERROR_MORE_DATA)
2349     {
2350         PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
2351
2352         if (pUsage)
2353         {
2354             ret = CertGetEnhancedKeyUsage(pCertContext,
2355              CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
2356             if (ret)
2357             {
2358                 if (pUsage->cUsageIdentifier)
2359                 {
2360                     DWORD i;
2361                     BOOL found = FALSE;
2362
2363                     for (i = 0; i < pUsage->cUsageIdentifier; i++)
2364                     {
2365                         if (!strcmp(pUsage->rgpszUsageIdentifier[i],
2366                          pszUsageIdentifier))
2367                             found = TRUE;
2368                         if (found && i < pUsage->cUsageIdentifier - 1)
2369                             pUsage->rgpszUsageIdentifier[i] =
2370                              pUsage->rgpszUsageIdentifier[i + 1];
2371                     }
2372                     pUsage->cUsageIdentifier--;
2373                     /* Remove the usage if it's empty */
2374                     if (pUsage->cUsageIdentifier)
2375                         ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
2376                     else
2377                         ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
2378                 }
2379             }
2380             CryptMemFree(pUsage);
2381         }
2382         else
2383             ret = FALSE;
2384     }
2385     else
2386     {
2387         /* it fit in an empty usage, therefore there's nothing to remove */
2388         ret = TRUE;
2389     }
2390     return ret;
2391 }
2392
2393 struct BitField
2394 {
2395     DWORD  cIndexes;
2396     DWORD *indexes;
2397 };
2398
2399 #define BITS_PER_DWORD (sizeof(DWORD) * 8)
2400
2401 static void CRYPT_SetBitInField(struct BitField *field, DWORD bit)
2402 {
2403     DWORD indexIndex = bit / BITS_PER_DWORD;
2404
2405     if (indexIndex + 1 > field->cIndexes)
2406     {
2407         if (field->cIndexes)
2408             field->indexes = CryptMemRealloc(field->indexes,
2409              (indexIndex + 1) * sizeof(DWORD));
2410         else
2411             field->indexes = CryptMemAlloc(sizeof(DWORD));
2412         if (field->indexes)
2413         {
2414             field->indexes[indexIndex] = 0;
2415             field->cIndexes = indexIndex + 1;
2416         }
2417     }
2418     if (field->indexes)
2419         field->indexes[indexIndex] |= 1 << (bit % BITS_PER_DWORD);
2420 }
2421
2422 static BOOL CRYPT_IsBitInFieldSet(struct BitField *field, DWORD bit)
2423 {
2424     BOOL set = FALSE;
2425     DWORD indexIndex = bit / BITS_PER_DWORD;
2426
2427     assert(field->cIndexes);
2428     set = field->indexes[indexIndex] & (1 << (bit % BITS_PER_DWORD));
2429     return set;
2430 }
2431
2432 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
2433  int *cNumOIDs, LPSTR *rghOIDs, DWORD *pcbOIDs)
2434 {
2435     BOOL ret = TRUE;
2436     DWORD i, cbOIDs = 0;
2437     BOOL allUsagesValid = TRUE;
2438     CERT_ENHKEY_USAGE validUsages = { 0, NULL };
2439
2440     TRACE("(%d, %p, %d, %p, %d)\n", cCerts, rghCerts, *cNumOIDs,
2441      rghOIDs, *pcbOIDs);
2442
2443     for (i = 0; i < cCerts; i++)
2444     {
2445         CERT_ENHKEY_USAGE usage;
2446         DWORD size = sizeof(usage);
2447
2448         ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
2449         /* Success is deliberately ignored: it implies all usages are valid */
2450         if (!ret && GetLastError() == ERROR_MORE_DATA)
2451         {
2452             PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
2453
2454             allUsagesValid = FALSE;
2455             if (pUsage)
2456             {
2457                 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
2458                 if (ret)
2459                 {
2460                     if (!validUsages.cUsageIdentifier)
2461                     {
2462                         DWORD j;
2463
2464                         cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
2465                         validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
2466                         for (j = 0; j < validUsages.cUsageIdentifier; j++)
2467                             cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
2468                              + 1;
2469                         validUsages.rgpszUsageIdentifier =
2470                          CryptMemAlloc(cbOIDs);
2471                         if (validUsages.rgpszUsageIdentifier)
2472                         {
2473                             LPSTR nextOID = (LPSTR)
2474                              ((LPBYTE)validUsages.rgpszUsageIdentifier +
2475                              validUsages.cUsageIdentifier * sizeof(LPSTR));
2476
2477                             for (j = 0; j < validUsages.cUsageIdentifier; j++)
2478                             {
2479                                 validUsages.rgpszUsageIdentifier[j] = nextOID;
2480                                 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
2481                                  pUsage->rgpszUsageIdentifier[j]);
2482                                 nextOID += lstrlenA(nextOID) + 1;
2483                             }
2484                         }
2485                     }
2486                     else
2487                     {
2488                         struct BitField validIndexes = { 0, NULL };
2489                         DWORD j, k, numRemoved = 0;
2490
2491                         /* Merge: build a bitmap of all the indexes of
2492                          * validUsages.rgpszUsageIdentifier that are in pUsage.
2493                          */
2494                         for (j = 0; j < pUsage->cUsageIdentifier; j++)
2495                         {
2496                             for (k = 0; k < validUsages.cUsageIdentifier; k++)
2497                             {
2498                                 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
2499                                  validUsages.rgpszUsageIdentifier[k]))
2500                                 {
2501                                     CRYPT_SetBitInField(&validIndexes, k);
2502                                     break;
2503                                 }
2504                             }
2505                         }
2506                         /* Merge by removing from validUsages those that are
2507                          * not in the bitmap.
2508                          */
2509                         for (j = 0; j < validUsages.cUsageIdentifier; j++)
2510                         {
2511                             if (!CRYPT_IsBitInFieldSet(&validIndexes, j))
2512                             {
2513                                 if (j < validUsages.cUsageIdentifier - 1)
2514                                 {
2515                                     memmove(&validUsages.rgpszUsageIdentifier[j],
2516                                      &validUsages.rgpszUsageIdentifier[j +
2517                                      numRemoved + 1],
2518                                      (validUsages.cUsageIdentifier - numRemoved
2519                                      - j - 1) * sizeof(LPSTR));
2520                                     cbOIDs -= lstrlenA(
2521                                      validUsages.rgpszUsageIdentifier[j]) + 1 +
2522                                      sizeof(LPSTR);
2523                                     validUsages.cUsageIdentifier--;
2524                                     numRemoved++;
2525                                 }
2526                                 else
2527                                     validUsages.cUsageIdentifier--;
2528                             }
2529                         }
2530                         CryptMemFree(validIndexes.indexes);
2531                     }
2532                 }
2533                 CryptMemFree(pUsage);
2534             }
2535         }
2536     }
2537     ret = TRUE;
2538     if (allUsagesValid)
2539     {
2540         *cNumOIDs = -1;
2541         *pcbOIDs = 0;
2542     }
2543     else
2544     {
2545         *cNumOIDs = validUsages.cUsageIdentifier;
2546         if (!rghOIDs)
2547             *pcbOIDs = cbOIDs;
2548         else if (*pcbOIDs < cbOIDs)
2549         {
2550             *pcbOIDs = cbOIDs;
2551             SetLastError(ERROR_MORE_DATA);
2552             ret = FALSE;
2553         }
2554         else
2555         {
2556             LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
2557              validUsages.cUsageIdentifier * sizeof(LPSTR));
2558
2559             *pcbOIDs = cbOIDs;
2560             for (i = 0; i < validUsages.cUsageIdentifier; i++)
2561             {
2562                 rghOIDs[i] = nextOID;
2563                 lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
2564                 nextOID += lstrlenA(nextOID) + 1;
2565             }
2566         }
2567     }
2568     CryptMemFree(validUsages.rgpszUsageIdentifier);
2569     TRACE("cNumOIDs: %d\n", *cNumOIDs);
2570     TRACE("returning %d\n", ret);
2571     return ret;
2572 }
2573
2574 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
2575  * pInfo is NULL, from the attributes of hProv.
2576  */
2577 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
2578  const CRYPT_KEY_PROV_INFO *pInfo, HCRYPTPROV hProv)
2579 {
2580     CRYPT_KEY_PROV_INFO info = { 0 };
2581     BOOL ret;
2582
2583     if (!pInfo)
2584     {
2585         DWORD size;
2586         int len;
2587
2588         ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
2589         if (ret)
2590         {
2591             LPSTR szContainer = CryptMemAlloc(size);
2592
2593             if (szContainer)
2594             {
2595                 ret = CryptGetProvParam(hProv, PP_CONTAINER,
2596                  (BYTE *)szContainer, &size, 0);
2597                 if (ret)
2598                 {
2599                     len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
2600                      NULL, 0);
2601                     if (len)
2602                     {
2603                         info.pwszContainerName = CryptMemAlloc(len *
2604                          sizeof(WCHAR));
2605                         len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
2606                          info.pwszContainerName, len);
2607                     }
2608                 }
2609                 CryptMemFree(szContainer);
2610             }
2611         }
2612         ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
2613         if (ret)
2614         {
2615             LPSTR szProvider = CryptMemAlloc(size);
2616
2617             if (szProvider)
2618             {
2619                 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
2620                  &size, 0);
2621                 if (ret)
2622                 {
2623                     len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
2624                      NULL, 0);
2625                     if (len)
2626                     {
2627                         info.pwszProvName = CryptMemAlloc(len *
2628                          sizeof(WCHAR));
2629                         len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
2630                          info.pwszProvName, len);
2631                     }
2632                 }
2633                 CryptMemFree(szProvider);
2634             }
2635         }
2636         size = sizeof(info.dwKeySpec);
2637         /* in case no CRYPT_KEY_PROV_INFO given,
2638          *  we always use AT_SIGNATURE key spec
2639          */
2640         info.dwKeySpec = AT_SIGNATURE;
2641         size = sizeof(info.dwProvType);
2642         ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
2643          &size, 0);
2644         if (!ret)
2645             info.dwProvType = PROV_RSA_FULL;
2646         pInfo = &info;
2647     }
2648
2649     ret = CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
2650      0, pInfo);
2651
2652     if (pInfo == &info)
2653     {
2654         CryptMemFree(info.pwszContainerName);
2655         CryptMemFree(info.pwszProvName);
2656     }
2657 }
2658
2659 /* Creates a signed certificate context from the unsigned, encoded certificate
2660  * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
2661  */
2662 static PCCERT_CONTEXT CRYPT_CreateSignedCert(const CRYPT_DER_BLOB *blob,
2663  HCRYPTPROV hProv, DWORD dwKeySpec, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
2664 {
2665     PCCERT_CONTEXT context = NULL;
2666     BOOL ret;
2667     DWORD sigSize = 0;
2668
2669     ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
2670      blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
2671     if (ret)
2672     {
2673         LPBYTE sig = CryptMemAlloc(sigSize);
2674
2675         ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
2676          blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
2677         if (ret)
2678         {
2679             CERT_SIGNED_CONTENT_INFO signedInfo;
2680             BYTE *encodedSignedCert = NULL;
2681             DWORD encodedSignedCertSize = 0;
2682
2683             signedInfo.ToBeSigned.cbData = blob->cbData;
2684             signedInfo.ToBeSigned.pbData = blob->pbData;
2685             memcpy(&signedInfo.SignatureAlgorithm, sigAlgo,
2686              sizeof(signedInfo.SignatureAlgorithm));
2687             signedInfo.Signature.cbData = sigSize;
2688             signedInfo.Signature.pbData = sig;
2689             signedInfo.Signature.cUnusedBits = 0;
2690             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
2691              &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
2692              &encodedSignedCert, &encodedSignedCertSize);
2693             if (ret)
2694             {
2695                 context = CertCreateCertificateContext(X509_ASN_ENCODING,
2696                  encodedSignedCert, encodedSignedCertSize);
2697                 LocalFree(encodedSignedCert);
2698             }
2699         }
2700         CryptMemFree(sig);
2701     }
2702     return context;
2703 }
2704
2705 /* Copies data from the parameters into info, where:
2706  * pSerialNumber: The serial number.  Must not be NULL.
2707  * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
2708  *                     Must not be NULL
2709  * pSignatureAlgorithm: Optional.
2710  * pStartTime: The starting time of the certificate.  If NULL, the current
2711  *             system time is used.
2712  * pEndTime: The ending time of the certificate.  If NULL, one year past the
2713  *           starting time is used.
2714  * pubKey: The public key of the certificate.  Must not be NULL.
2715  * pExtensions: Extensions to be included with the certificate.  Optional.
2716  */
2717 static void CRYPT_MakeCertInfo(PCERT_INFO info, const CRYPT_DATA_BLOB *pSerialNumber,
2718  const CERT_NAME_BLOB *pSubjectIssuerBlob,
2719  const CRYPT_ALGORITHM_IDENTIFIER *pSignatureAlgorithm, const SYSTEMTIME *pStartTime,
2720  const SYSTEMTIME *pEndTime, const CERT_PUBLIC_KEY_INFO *pubKey,
2721  const CERT_EXTENSIONS *pExtensions)
2722 {
2723     static CHAR oid[] = szOID_RSA_SHA1RSA;
2724
2725     assert(info);
2726     assert(pSerialNumber);
2727     assert(pSubjectIssuerBlob);
2728     assert(pubKey);
2729
2730     info->dwVersion = CERT_V3;
2731     info->SerialNumber.cbData = pSerialNumber->cbData;
2732     info->SerialNumber.pbData = pSerialNumber->pbData;
2733     if (pSignatureAlgorithm)
2734         memcpy(&info->SignatureAlgorithm, pSignatureAlgorithm,
2735          sizeof(info->SignatureAlgorithm));
2736     else
2737     {
2738         info->SignatureAlgorithm.pszObjId = oid;
2739         info->SignatureAlgorithm.Parameters.cbData = 0;
2740         info->SignatureAlgorithm.Parameters.pbData = NULL;
2741     }
2742     info->Issuer.cbData = pSubjectIssuerBlob->cbData;
2743     info->Issuer.pbData = pSubjectIssuerBlob->pbData;
2744     if (pStartTime)
2745         SystemTimeToFileTime(pStartTime, &info->NotBefore);
2746     else
2747         GetSystemTimeAsFileTime(&info->NotBefore);
2748     if (pEndTime)
2749         SystemTimeToFileTime(pEndTime, &info->NotAfter);
2750     else
2751     {
2752         SYSTEMTIME endTime;
2753
2754         if (FileTimeToSystemTime(&info->NotBefore, &endTime))
2755         {
2756             endTime.wYear++;
2757             SystemTimeToFileTime(&endTime, &info->NotAfter);
2758         }
2759     }
2760     info->Subject.cbData = pSubjectIssuerBlob->cbData;
2761     info->Subject.pbData = pSubjectIssuerBlob->pbData;
2762     memcpy(&info->SubjectPublicKeyInfo, pubKey,
2763      sizeof(info->SubjectPublicKeyInfo));
2764     if (pExtensions)
2765     {
2766         info->cExtension = pExtensions->cExtension;
2767         info->rgExtension = pExtensions->rgExtension;
2768     }
2769     else
2770     {
2771         info->cExtension = 0;
2772         info->rgExtension = NULL;
2773     }
2774 }
2775  
2776 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
2777 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
2778 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
2779
2780 static HCRYPTPROV CRYPT_CreateKeyProv(void)
2781 {
2782     HCRYPTPROV hProv = 0;
2783     HMODULE rpcrt = LoadLibraryA("rpcrt4");
2784
2785     if (rpcrt)
2786     {
2787         UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
2788          "UuidCreate");
2789         UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
2790          "UuidToStringA");
2791         RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
2792          rpcrt, "RpcStringFreeA");
2793
2794         if (uuidCreate && uuidToString && rpcStringFree)
2795         {
2796             UUID uuid;
2797             RPC_STATUS status = uuidCreate(&uuid);
2798
2799             if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
2800             {
2801                 unsigned char *uuidStr;
2802
2803                 status = uuidToString(&uuid, &uuidStr);
2804                 if (status == RPC_S_OK)
2805                 {
2806                     BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
2807                      MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
2808
2809                     if (ret)
2810                     {
2811                         HCRYPTKEY key;
2812
2813                         ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
2814                         if (ret)
2815                             CryptDestroyKey(key);
2816                     }
2817                     rpcStringFree(&uuidStr);
2818                 }
2819             }
2820         }
2821         FreeLibrary(rpcrt);
2822     }
2823     return hProv;
2824 }
2825
2826 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hProv,
2827  PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
2828  PCRYPT_KEY_PROV_INFO pKeyProvInfo,
2829  PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
2830  PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
2831 {
2832     PCCERT_CONTEXT context = NULL;
2833     BOOL ret, releaseContext = FALSE;
2834     PCERT_PUBLIC_KEY_INFO pubKey = NULL;
2835     DWORD pubKeySize = 0,dwKeySpec = AT_SIGNATURE;
2836
2837     TRACE("(%08lx, %p, %08x, %p, %p, %p, %p, %p)\n", hProv,
2838      pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
2839      pExtensions, pExtensions);
2840
2841     if(!pSubjectIssuerBlob)
2842     {
2843         SetLastError(ERROR_INVALID_PARAMETER);
2844         return NULL;
2845     }
2846
2847     if (!hProv)
2848     {
2849         if (!pKeyProvInfo)
2850         {
2851             hProv = CRYPT_CreateKeyProv();
2852             releaseContext = TRUE;
2853         }
2854         else if (pKeyProvInfo->dwFlags & CERT_SET_KEY_PROV_HANDLE_PROP_ID)
2855         {
2856             SetLastError(NTE_BAD_FLAGS);
2857             return NULL;
2858         }
2859         else
2860         {
2861             HCRYPTKEY hKey = 0;
2862             /* acquire the context using the given information*/
2863             ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
2864                     pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
2865                     pKeyProvInfo->dwFlags);
2866             if (!ret)
2867             {
2868                 if(GetLastError() != NTE_BAD_KEYSET)
2869                     return NULL;
2870                 /* create the key set */
2871                 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
2872                     pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
2873                     pKeyProvInfo->dwFlags|CRYPT_NEWKEYSET);
2874                 if (!ret)
2875                     return NULL;
2876             }
2877             dwKeySpec = pKeyProvInfo->dwKeySpec;
2878             /* check if the key is here */
2879             ret = CryptGetUserKey(hProv,dwKeySpec,&hKey);
2880             if(!ret)
2881             {
2882                 if (NTE_NO_KEY == GetLastError())
2883                 { /* generate the key */
2884                     ret = CryptGenKey(hProv,dwKeySpec,0,&hKey);
2885                 }
2886                 if (!ret)
2887                 {
2888                     CryptReleaseContext(hProv,0);
2889                     SetLastError(NTE_BAD_KEYSET);
2890                     return NULL;
2891                 }
2892             }
2893             CryptDestroyKey(hKey);
2894             releaseContext = TRUE;
2895         }
2896     }
2897     else if (pKeyProvInfo)
2898     {
2899         SetLastError(ERROR_INVALID_PARAMETER);
2900         return NULL;
2901     }
2902
2903     CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING, NULL,
2904      &pubKeySize);
2905     pubKey = CryptMemAlloc(pubKeySize);
2906     if (pubKey)
2907     {
2908         ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING,
2909          pubKey, &pubKeySize);
2910         if (ret)
2911         {
2912             CERT_INFO info = { 0 };
2913             CRYPT_DER_BLOB blob = { 0, NULL };
2914             BYTE serial[16];
2915             CRYPT_DATA_BLOB serialBlob = { sizeof(serial), serial };
2916
2917             CryptGenRandom(hProv, sizeof(serial), serial);
2918             CRYPT_MakeCertInfo(&info, &serialBlob, pSubjectIssuerBlob,
2919              pSignatureAlgorithm, pStartTime, pEndTime, pubKey, pExtensions);
2920             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
2921              &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData,
2922              &blob.cbData);
2923             if (ret)
2924             {
2925                 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
2926                     context = CRYPT_CreateSignedCert(&blob, hProv,dwKeySpec,
2927                      &info.SignatureAlgorithm);
2928                 else
2929                     context = CertCreateCertificateContext(X509_ASN_ENCODING,
2930                      blob.pbData, blob.cbData);
2931                 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
2932                     CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
2933                 LocalFree(blob.pbData);
2934             }
2935         }
2936         CryptMemFree(pubKey);
2937     }
2938     if (releaseContext)
2939         CryptReleaseContext(hProv, 0);
2940     return context;
2941 }
2942
2943 BOOL WINAPI CertVerifyCTLUsage(DWORD dwEncodingType, DWORD dwSubjectType,
2944                                void *pvSubject, PCTL_USAGE pSubjectUsage, DWORD dwFlags,
2945                                PCTL_VERIFY_USAGE_PARA pVerifyUsagePara,
2946                                PCTL_VERIFY_USAGE_STATUS pVerifyUsageStatus)
2947 {
2948     FIXME("(0x%x, %d, %p, %p, 0x%x, %p, %p): stub\n", dwEncodingType,
2949           dwSubjectType, pvSubject, pSubjectUsage, dwFlags, pVerifyUsagePara,
2950           pVerifyUsageStatus);
2951     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2952     return FALSE;
2953 }