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