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