ole32: Remove unnecessary assert(This) calls.
[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 #include "windef.h"
23 #include "winbase.h"
24 #include "wincrypt.h"
25 #include "winnls.h"
26 #include "rpc.h"
27 #include "wine/debug.h"
28 #include "crypt32_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
31
32 /* Internal version of CertGetCertificateContextProperty that gets properties
33  * directly from the context (or the context it's linked to, depending on its
34  * type.) Doesn't handle special-case properties, since they are handled by
35  * CertGetCertificateContextProperty, and are particular to the store in which
36  * the property exists (which is separate from the context.)
37  */
38 static BOOL WINAPI CertContext_GetProperty(void *context, DWORD dwPropId,
39  void *pvData, DWORD *pcbData);
40
41 /* Internal version of CertSetCertificateContextProperty that sets properties
42  * directly on the context (or the context it's linked to, depending on its
43  * type.) Doesn't handle special cases, since they're handled by
44  * CertSetCertificateContextProperty anyway.
45  */
46 static BOOL WINAPI CertContext_SetProperty(void *context, DWORD dwPropId,
47  DWORD dwFlags, const void *pvData);
48
49 BOOL WINAPI CertAddEncodedCertificateToStore(HCERTSTORE hCertStore,
50  DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded,
51  DWORD dwAddDisposition, PCCERT_CONTEXT *ppCertContext)
52 {
53     PCCERT_CONTEXT cert = CertCreateCertificateContext(dwCertEncodingType,
54      pbCertEncoded, cbCertEncoded);
55     BOOL ret;
56
57     TRACE("(%p, %08lx, %p, %ld, %08lx, %p)\n", hCertStore, dwCertEncodingType,
58      pbCertEncoded, cbCertEncoded, dwAddDisposition, ppCertContext);
59
60     if (cert)
61     {
62         ret = CertAddCertificateContextToStore(hCertStore, cert,
63          dwAddDisposition, ppCertContext);
64         CertFreeCertificateContext(cert);
65     }
66     else
67         ret = FALSE;
68     return ret;
69 }
70
71 PCCERT_CONTEXT WINAPI CertCreateCertificateContext(DWORD dwCertEncodingType,
72  const BYTE *pbCertEncoded, DWORD cbCertEncoded)
73 {
74     PCERT_CONTEXT cert = NULL;
75     BOOL ret;
76     PCERT_INFO certInfo = NULL;
77     DWORD size = 0;
78
79     TRACE("(%08lx, %p, %ld)\n", dwCertEncodingType, pbCertEncoded,
80      cbCertEncoded);
81
82     ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
83      pbCertEncoded, cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
84      (BYTE *)&certInfo, &size);
85     if (ret)
86     {
87         BYTE *data = NULL;
88
89         cert = (PCERT_CONTEXT)Context_CreateDataContext(sizeof(CERT_CONTEXT));
90         if (!cert)
91             goto end;
92         data = CryptMemAlloc(cbCertEncoded);
93         if (!data)
94         {
95             CryptMemFree(cert);
96             cert = NULL;
97             goto end;
98         }
99         memcpy(data, pbCertEncoded, cbCertEncoded);
100         cert->dwCertEncodingType = dwCertEncodingType;
101         cert->pbCertEncoded      = data;
102         cert->cbCertEncoded      = cbCertEncoded;
103         cert->pCertInfo          = certInfo;
104         cert->hCertStore         = 0;
105     }
106
107 end:
108     return (PCCERT_CONTEXT)cert;
109 }
110
111 PCCERT_CONTEXT WINAPI CertDuplicateCertificateContext(
112  PCCERT_CONTEXT pCertContext)
113 {
114     TRACE("(%p)\n", pCertContext);
115     Context_AddRef((void *)pCertContext, sizeof(CERT_CONTEXT));
116     return pCertContext;
117 }
118
119 static void CertDataContext_Free(void *context)
120 {
121     PCERT_CONTEXT certContext = (PCERT_CONTEXT)context;
122
123     CryptMemFree(certContext->pbCertEncoded);
124     LocalFree(certContext->pCertInfo);
125 }
126
127 BOOL WINAPI CertFreeCertificateContext(PCCERT_CONTEXT pCertContext)
128 {
129     TRACE("(%p)\n", pCertContext);
130
131     if (pCertContext)
132         Context_Release((void *)pCertContext, sizeof(CERT_CONTEXT),
133          CertDataContext_Free);
134     return TRUE;
135 }
136
137 DWORD WINAPI CertEnumCertificateContextProperties(PCCERT_CONTEXT pCertContext,
138  DWORD dwPropId)
139 {
140     PCONTEXT_PROPERTY_LIST properties = Context_GetProperties(
141      (void *)pCertContext, sizeof(CERT_CONTEXT));
142     DWORD ret;
143
144     TRACE("(%p, %ld)\n", pCertContext, dwPropId);
145
146     if (properties)
147         ret = ContextPropertyList_EnumPropIDs(properties, dwPropId);
148     else
149         ret = 0;
150     return ret;
151 }
152
153 static BOOL CertContext_GetHashProp(void *context, DWORD dwPropId,
154  ALG_ID algID, const BYTE *toHash, DWORD toHashLen, void *pvData,
155  DWORD *pcbData)
156 {
157     BOOL ret = CryptHashCertificate(0, algID, 0, toHash, toHashLen, pvData,
158      pcbData);
159     if (ret)
160     {
161         CRYPT_DATA_BLOB blob = { *pcbData, pvData };
162
163         ret = CertContext_SetProperty(context, dwPropId, 0, &blob);
164     }
165     return ret;
166 }
167
168 static BOOL WINAPI CertContext_GetProperty(void *context, DWORD dwPropId,
169  void *pvData, DWORD *pcbData)
170 {
171     PCCERT_CONTEXT pCertContext = (PCCERT_CONTEXT)context;
172     PCONTEXT_PROPERTY_LIST properties =
173      Context_GetProperties(context, sizeof(CERT_CONTEXT));
174     BOOL ret;
175     CRYPT_DATA_BLOB blob;
176
177     TRACE("(%p, %ld, %p, %p)\n", context, dwPropId, pvData, pcbData);
178
179     if (properties)
180         ret = ContextPropertyList_FindProperty(properties, dwPropId, &blob);
181     else
182         ret = FALSE;
183     if (ret)
184     {
185         if (!pvData)
186         {
187             *pcbData = blob.cbData;
188             ret = TRUE;
189         }
190         else if (*pcbData < blob.cbData)
191         {
192             SetLastError(ERROR_MORE_DATA);
193             *pcbData = blob.cbData;
194         }
195         else
196         {
197             memcpy(pvData, blob.pbData, blob.cbData);
198             *pcbData = blob.cbData;
199             ret = TRUE;
200         }
201     }
202     else
203     {
204         /* Implicit properties */
205         switch (dwPropId)
206         {
207         case CERT_SHA1_HASH_PROP_ID:
208             ret = CertContext_GetHashProp(context, dwPropId, CALG_SHA1,
209              pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
210              pcbData);
211             break;
212         case CERT_MD5_HASH_PROP_ID:
213             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
214              pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
215              pcbData);
216             break;
217         case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
218             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
219              pCertContext->pCertInfo->Subject.pbData,
220              pCertContext->pCertInfo->Subject.cbData,
221              pvData, pcbData);
222             break;
223         case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
224             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
225              pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
226              pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData,
227              pvData, pcbData);
228             break;
229         case CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID:
230             ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
231              pCertContext->pCertInfo->SerialNumber.pbData,
232              pCertContext->pCertInfo->SerialNumber.cbData,
233              pvData, pcbData);
234             break;
235         case CERT_SIGNATURE_HASH_PROP_ID:
236             FIXME("CERT_SIGNATURE_HASH_PROP_ID unimplemented\n");
237             SetLastError(CRYPT_E_NOT_FOUND);
238             break;
239         default:
240             SetLastError(CRYPT_E_NOT_FOUND);
241         }
242     }
243     TRACE("returning %d\n", ret);
244     return ret;
245 }
246
247 /* info is assumed to be a CRYPT_KEY_PROV_INFO, followed by its container name,
248  * provider name, and any provider parameters, in a contiguous buffer, but
249  * where info's pointers are assumed to be invalid.  Upon return, info's
250  * pointers point to the appropriate memory locations.
251  */
252 static void CRYPT_FixKeyProvInfoPointers(PCRYPT_KEY_PROV_INFO info)
253 {
254     DWORD i, containerLen, provNameLen;
255     LPBYTE data = (LPBYTE)info + sizeof(CRYPT_KEY_PROV_INFO);
256
257     info->pwszContainerName = (LPWSTR)data;
258     containerLen = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
259     data += containerLen;
260
261     info->pwszProvName = (LPWSTR)data;
262     provNameLen = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
263     data += provNameLen;
264
265     info->rgProvParam = (PCRYPT_KEY_PROV_PARAM)data;
266     data += info->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
267
268     for (i = 0; i < info->cProvParam; i++)
269     {
270         info->rgProvParam[i].pbData = data;
271         data += info->rgProvParam[i].cbData;
272     }
273 }
274
275 BOOL WINAPI CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
276  DWORD dwPropId, void *pvData, DWORD *pcbData)
277 {
278     BOOL ret;
279
280     TRACE("(%p, %ld, %p, %p)\n", pCertContext, dwPropId, pvData, pcbData);
281
282     switch (dwPropId)
283     {
284     case 0:
285     case CERT_CERT_PROP_ID:
286     case CERT_CRL_PROP_ID:
287     case CERT_CTL_PROP_ID:
288         SetLastError(E_INVALIDARG);
289         ret = FALSE;
290         break;
291     case CERT_ACCESS_STATE_PROP_ID:
292         if (!pvData)
293         {
294             *pcbData = sizeof(DWORD);
295             ret = TRUE;
296         }
297         else if (*pcbData < sizeof(DWORD))
298         {
299             SetLastError(ERROR_MORE_DATA);
300             *pcbData = sizeof(DWORD);
301             ret = FALSE;
302         }
303         else
304         {
305             *(DWORD *)pvData =
306              CertStore_GetAccessState(pCertContext->hCertStore);
307             ret = TRUE;
308         }
309         break;
310     case CERT_KEY_IDENTIFIER_PROP_ID:
311         ret = CertContext_GetProperty((void *)pCertContext, dwPropId,
312          pvData, pcbData);
313         if (!ret)
314             SetLastError(ERROR_INVALID_DATA);
315         break;
316     case CERT_KEY_PROV_HANDLE_PROP_ID:
317     {
318         CERT_KEY_CONTEXT keyContext;
319         DWORD size = sizeof(keyContext);
320
321         ret = CertContext_GetProperty((void *)pCertContext,
322          CERT_KEY_CONTEXT_PROP_ID, &keyContext, &size);
323         if (ret)
324         {
325             if (!pvData)
326             {
327                 *pcbData = sizeof(HCRYPTPROV);
328                 ret = TRUE;
329             }
330             else if (*pcbData < sizeof(HCRYPTPROV))
331             {
332                 SetLastError(ERROR_MORE_DATA);
333                 *pcbData = sizeof(HCRYPTPROV);
334                 ret = FALSE;
335             }
336             else
337             {
338                 *(HCRYPTPROV *)pvData = keyContext.hCryptProv;
339                 ret = TRUE;
340             }
341         }
342         break;
343     }
344     case CERT_KEY_PROV_INFO_PROP_ID:
345         ret = CertContext_GetProperty((void *)pCertContext, dwPropId, pvData,
346          pcbData);
347         if (ret && pvData)
348             CRYPT_FixKeyProvInfoPointers((PCRYPT_KEY_PROV_INFO)pvData);
349         break;
350     default:
351         ret = CertContext_GetProperty((void *)pCertContext, dwPropId, pvData,
352          pcbData);
353     }
354
355     TRACE("returning %d\n", ret);
356     return ret;
357 }
358
359 /* Copies key provider info from from into to, where to is assumed to be a
360  * contiguous buffer of memory large enough for from and all its associated
361  * data, but whose pointers are uninitialized.
362  * Upon return, to contains a contiguous copy of from, packed in the following
363  * order:
364  * - CRYPT_KEY_PROV_INFO
365  * - pwszContainerName
366  * - pwszProvName
367  * - rgProvParam[0]...
368  */
369 static void CRYPT_CopyKeyProvInfo(PCRYPT_KEY_PROV_INFO to,
370  PCRYPT_KEY_PROV_INFO from)
371 {
372     DWORD i;
373     LPBYTE nextData = (LPBYTE)to + sizeof(CRYPT_KEY_PROV_INFO);
374
375     to->pwszContainerName = (LPWSTR)nextData;
376     lstrcpyW(to->pwszContainerName, from->pwszContainerName);
377     nextData += (lstrlenW(from->pwszContainerName) + 1) * sizeof(WCHAR);
378     to->pwszProvName = (LPWSTR)nextData;
379     lstrcpyW(to->pwszProvName, from->pwszProvName);
380     nextData += (lstrlenW(from->pwszProvName) + 1) * sizeof(WCHAR);
381     to->dwProvType = from->dwProvType;
382     to->dwFlags = from->dwFlags;
383     to->cProvParam = from->cProvParam;
384     to->rgProvParam = (PCRYPT_KEY_PROV_PARAM)nextData;
385     nextData += to->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
386     to->dwKeySpec = from->dwKeySpec;
387     for (i = 0; i < to->cProvParam; i++)
388     {
389         memcpy(&to->rgProvParam[i], &from->rgProvParam[i],
390          sizeof(CRYPT_KEY_PROV_PARAM));
391         to->rgProvParam[i].pbData = nextData;
392         memcpy(to->rgProvParam[i].pbData, from->rgProvParam[i].pbData,
393          from->rgProvParam[i].cbData);
394         nextData += from->rgProvParam[i].cbData;
395     }
396 }
397
398 static BOOL CertContext_SetKeyProvInfoProperty(PCONTEXT_PROPERTY_LIST properties,
399  PCRYPT_KEY_PROV_INFO info)
400 {
401     BOOL ret;
402     LPBYTE buf = NULL;
403     DWORD size = sizeof(CRYPT_KEY_PROV_INFO), i, containerSize, provNameSize;
404
405     containerSize = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
406     provNameSize = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
407     size += containerSize + provNameSize;
408     for (i = 0; i < info->cProvParam; i++)
409         size += sizeof(CRYPT_KEY_PROV_PARAM) + info->rgProvParam[i].cbData;
410     buf = CryptMemAlloc(size);
411     if (buf)
412     {
413         CRYPT_CopyKeyProvInfo((PCRYPT_KEY_PROV_INFO)buf, info);
414         ret = ContextPropertyList_SetProperty(properties,
415          CERT_KEY_PROV_INFO_PROP_ID, buf, size);
416         CryptMemFree(buf);
417     }
418     else
419         ret = FALSE;
420     return ret;
421 }
422
423 static BOOL WINAPI CertContext_SetProperty(void *context, DWORD dwPropId,
424  DWORD dwFlags, const void *pvData)
425 {
426     PCONTEXT_PROPERTY_LIST properties =
427      Context_GetProperties(context, sizeof(CERT_CONTEXT));
428     BOOL ret;
429
430     TRACE("(%p, %ld, %08lx, %p)\n", context, dwPropId, dwFlags, pvData);
431
432     if (!properties)
433         ret = FALSE;
434     else
435     {
436         switch (dwPropId)
437         {
438         case CERT_AUTO_ENROLL_PROP_ID:
439         case CERT_CTL_USAGE_PROP_ID: /* same as CERT_ENHKEY_USAGE_PROP_ID */
440         case CERT_DESCRIPTION_PROP_ID:
441         case CERT_FRIENDLY_NAME_PROP_ID:
442         case CERT_HASH_PROP_ID:
443         case CERT_KEY_IDENTIFIER_PROP_ID:
444         case CERT_MD5_HASH_PROP_ID:
445         case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
446         case CERT_PUBKEY_ALG_PARA_PROP_ID:
447         case CERT_PVK_FILE_PROP_ID:
448         case CERT_SIGNATURE_HASH_PROP_ID:
449         case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
450         case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
451         case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
452         case CERT_ENROLLMENT_PROP_ID:
453         case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
454         case CERT_RENEWAL_PROP_ID:
455         {
456             if (pvData)
457             {
458                 PCRYPT_DATA_BLOB blob = (PCRYPT_DATA_BLOB)pvData;
459
460                 ret = ContextPropertyList_SetProperty(properties, dwPropId,
461                  blob->pbData, blob->cbData);
462             }
463             else
464             {
465                 ContextPropertyList_RemoveProperty(properties, dwPropId);
466                 ret = TRUE;
467             }
468             break;
469         }
470         case CERT_DATE_STAMP_PROP_ID:
471             if (pvData)
472                 ret = ContextPropertyList_SetProperty(properties, dwPropId,
473                  (LPBYTE)pvData, sizeof(FILETIME));
474             else
475             {
476                 ContextPropertyList_RemoveProperty(properties, dwPropId);
477                 ret = TRUE;
478             }
479             break;
480         case CERT_KEY_CONTEXT_PROP_ID:
481         {
482             if (pvData)
483             {
484                 PCERT_KEY_CONTEXT keyContext = (PCERT_KEY_CONTEXT)pvData;
485
486                 ret = ContextPropertyList_SetProperty(properties, dwPropId,
487                  (const BYTE *)keyContext, keyContext->cbSize);
488             }
489             else
490             {
491                 ContextPropertyList_RemoveProperty(properties, dwPropId);
492                 ret = TRUE;
493             }
494             break;
495         }
496         case CERT_KEY_PROV_INFO_PROP_ID:
497             if (pvData)
498                 ret = CertContext_SetKeyProvInfoProperty(properties,
499                  (PCRYPT_KEY_PROV_INFO)pvData);
500             else
501             {
502                 ContextPropertyList_RemoveProperty(properties, dwPropId);
503                 ret = TRUE;
504             }
505             break;
506         case CERT_KEY_PROV_HANDLE_PROP_ID:
507         {
508             CERT_KEY_CONTEXT keyContext;
509             DWORD size = sizeof(keyContext);
510
511             ret = CertContext_GetProperty(context, CERT_KEY_CONTEXT_PROP_ID,
512              &keyContext, &size);
513             if (ret)
514             {
515                 if (!(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG))
516                     CryptReleaseContext(keyContext.hCryptProv, 0);
517                 if (pvData)
518                     keyContext.hCryptProv = *(HCRYPTPROV *)pvData;
519                 else
520                     keyContext.hCryptProv = 0;
521                 ret = CertContext_SetProperty(context, CERT_KEY_CONTEXT_PROP_ID,
522                  0, &keyContext);
523             }
524             break;
525         }
526         default:
527             FIXME("%ld: stub\n", dwPropId);
528             ret = FALSE;
529         }
530     }
531     TRACE("returning %d\n", ret);
532     return ret;
533 }
534
535 BOOL WINAPI CertSetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
536  DWORD dwPropId, DWORD dwFlags, const void *pvData)
537 {
538     BOOL ret;
539
540     TRACE("(%p, %ld, %08lx, %p)\n", pCertContext, dwPropId, dwFlags, pvData);
541
542     /* Handle special cases for "read-only"/invalid prop IDs.  Windows just
543      * crashes on most of these, I'll be safer.
544      */
545     switch (dwPropId)
546     {
547     case 0:
548     case CERT_ACCESS_STATE_PROP_ID:
549     case CERT_CERT_PROP_ID:
550     case CERT_CRL_PROP_ID:
551     case CERT_CTL_PROP_ID:
552         SetLastError(E_INVALIDARG);
553         return FALSE;
554     }
555     ret = CertContext_SetProperty((void *)pCertContext, dwPropId, dwFlags,
556      pvData);
557     TRACE("returning %d\n", ret);
558     return ret;
559 }
560
561 /* Acquires the private key using the key provider info, retrieving info from
562  * the certificate if info is NULL.  The acquired provider is returned in
563  * *phCryptProv, and the key spec for the provider is returned in *pdwKeySpec.
564  */
565 static BOOL CRYPT_AcquirePrivateKeyFromProvInfo(PCCERT_CONTEXT pCert,
566  PCRYPT_KEY_PROV_INFO info, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec)
567 {
568     DWORD size = 0;
569     BOOL allocated = FALSE, ret = TRUE;
570
571     if (!info)
572     {
573         ret = CertGetCertificateContextProperty(pCert,
574          CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
575         if (ret)
576         {
577             info = (PCRYPT_KEY_PROV_INFO)HeapAlloc(GetProcessHeap(), 0, size);
578             if (info)
579             {
580                 ret = CertGetCertificateContextProperty(pCert,
581                  CERT_KEY_PROV_INFO_PROP_ID, info, &size);
582                 allocated = TRUE;
583             }
584         }
585         else
586             SetLastError(CRYPT_E_NO_KEY_PROPERTY);
587     }
588     if (ret)
589     {
590         ret = CryptAcquireContextW(phCryptProv, info->pwszContainerName,
591          info->pwszProvName, info->dwProvType, 0);
592         if (ret)
593         {
594             DWORD i;
595
596             for (i = 0; i < info->cProvParam; i++)
597             {
598                 CryptSetProvParam(*phCryptProv,
599                  info->rgProvParam[i].dwParam, info->rgProvParam[i].pbData,
600                  info->rgProvParam[i].dwFlags);
601             }
602             *pdwKeySpec = info->dwKeySpec;
603         }
604         else
605             SetLastError(CRYPT_E_NO_KEY_PROPERTY);
606     }
607     if (allocated)
608         HeapFree(GetProcessHeap(), 0, info);
609     return ret;
610 }
611
612 BOOL WINAPI CryptAcquireCertificatePrivateKey(PCCERT_CONTEXT pCert,
613  DWORD dwFlags, void *pvReserved, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec,
614  BOOL *pfCallerFreeProv)
615 {
616     BOOL ret = FALSE, cache = FALSE;
617     PCRYPT_KEY_PROV_INFO info = NULL;
618     CERT_KEY_CONTEXT keyContext;
619     DWORD size;
620
621     TRACE("(%p, %08lx, %p, %p, %p, %p)\n", pCert, dwFlags, pvReserved,
622      phCryptProv, pdwKeySpec, pfCallerFreeProv);
623
624     if (dwFlags & CRYPT_ACQUIRE_USE_PROV_INFO_FLAG)
625     {
626         DWORD size = 0;
627
628         ret = CertGetCertificateContextProperty(pCert,
629          CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
630         if (ret)
631         {
632             info = (PCRYPT_KEY_PROV_INFO)HeapAlloc(
633              GetProcessHeap(), 0, size);
634             ret = CertGetCertificateContextProperty(pCert,
635              CERT_KEY_PROV_INFO_PROP_ID, info, &size);
636             if (ret)
637                 cache = info->dwFlags & CERT_SET_KEY_CONTEXT_PROP_ID;
638         }
639     }
640     else if (dwFlags & CRYPT_ACQUIRE_CACHE_FLAG)
641         cache = TRUE;
642     *phCryptProv = 0;
643     if (cache)
644     {
645         size = sizeof(keyContext);
646         ret = CertGetCertificateContextProperty(pCert, CERT_KEY_CONTEXT_PROP_ID,
647          &keyContext, &size);
648         if (ret)
649         {
650             *phCryptProv = keyContext.hCryptProv;
651             if (pdwKeySpec)
652                 *pdwKeySpec = keyContext.dwKeySpec;
653             if (pfCallerFreeProv)
654                 *pfCallerFreeProv = !cache;
655         }
656     }
657     if (!*phCryptProv)
658     {
659         ret = CRYPT_AcquirePrivateKeyFromProvInfo(pCert, info,
660          &keyContext.hCryptProv, &keyContext.dwKeySpec);
661         if (ret)
662         {
663             *phCryptProv = keyContext.hCryptProv;
664             if (pdwKeySpec)
665                 *pdwKeySpec = keyContext.dwKeySpec;
666             if (cache)
667             {
668                 keyContext.cbSize = sizeof(keyContext);
669                 if (CertSetCertificateContextProperty(pCert,
670                  CERT_KEY_CONTEXT_PROP_ID, 0, &keyContext))
671                 {
672                     if (pfCallerFreeProv)
673                         *pfCallerFreeProv = FALSE;
674                 }
675             }
676             else
677             {
678                 if (pfCallerFreeProv)
679                     *pfCallerFreeProv = TRUE;
680             }
681         }
682     }
683     HeapFree(GetProcessHeap(), 0, info);
684     return ret;
685 }
686
687 BOOL WINAPI CertCompareCertificate(DWORD dwCertEncodingType,
688  PCERT_INFO pCertId1, PCERT_INFO pCertId2)
689 {
690     TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pCertId1, pCertId2);
691
692     return CertCompareCertificateName(dwCertEncodingType, &pCertId1->Issuer,
693      &pCertId2->Issuer) && CertCompareIntegerBlob(&pCertId1->SerialNumber,
694      &pCertId2->SerialNumber);
695 }
696
697 BOOL WINAPI CertCompareCertificateName(DWORD dwCertEncodingType,
698  PCERT_NAME_BLOB pCertName1, PCERT_NAME_BLOB pCertName2)
699 {
700     BOOL ret;
701
702     TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pCertName1, pCertName2);
703
704     if (pCertName1->cbData == pCertName2->cbData)
705     {
706         if (pCertName1->cbData)
707             ret = !memcmp(pCertName1->pbData, pCertName2->pbData,
708              pCertName1->cbData);
709         else
710             ret = TRUE;
711     }
712     else
713         ret = FALSE;
714     return ret;
715 }
716
717 /* Returns the number of significant bytes in pInt, where a byte is
718  * insignificant if it's a leading 0 for positive numbers or a leading 0xff
719  * for negative numbers.  pInt is assumed to be little-endian.
720  */
721 static DWORD CRYPT_significantBytes(PCRYPT_INTEGER_BLOB pInt)
722 {
723     DWORD ret = pInt->cbData;
724
725     while (ret > 1)
726     {
727         if (pInt->pbData[ret - 2] <= 0x7f && pInt->pbData[ret - 1] == 0)
728             ret--;
729         else if (pInt->pbData[ret - 2] >= 0x80 && pInt->pbData[ret - 1] == 0xff)
730             ret--;
731         else
732             break;
733     }
734     return ret;
735 }
736
737 BOOL WINAPI CertCompareIntegerBlob(PCRYPT_INTEGER_BLOB pInt1,
738  PCRYPT_INTEGER_BLOB pInt2)
739 {
740     BOOL ret;
741     DWORD cb1, cb2;
742
743     TRACE("(%p, %p)\n", pInt1, pInt2);
744
745     cb1 = CRYPT_significantBytes(pInt1);
746     cb2 = CRYPT_significantBytes(pInt2);
747     if (cb1 == cb2)
748     {
749         if (cb1)
750             ret = !memcmp(pInt1->pbData, pInt1->pbData, cb1);
751         else
752             ret = TRUE;
753     }
754     else
755         ret = FALSE;
756     return ret;
757 }
758
759 BOOL WINAPI CertComparePublicKeyInfo(DWORD dwCertEncodingType,
760  PCERT_PUBLIC_KEY_INFO pPublicKey1, PCERT_PUBLIC_KEY_INFO pPublicKey2)
761 {
762     BOOL ret;
763
764     TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pPublicKey1, pPublicKey2);
765
766     if (pPublicKey1->PublicKey.cbData == pPublicKey2->PublicKey.cbData &&
767      pPublicKey1->PublicKey.cUnusedBits == pPublicKey2->PublicKey.cUnusedBits)
768     {
769         if (pPublicKey2->PublicKey.cbData)
770             ret = !memcmp(pPublicKey1->PublicKey.pbData,
771              pPublicKey2->PublicKey.pbData, pPublicKey1->PublicKey.cbData);
772         else
773             ret = TRUE;
774     }
775     else
776         ret = FALSE;
777     return ret;
778 }
779
780 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
781  DWORD dwFlags, const void *pvPara);
782
783 static BOOL compare_cert_any(PCCERT_CONTEXT pCertContext, DWORD dwType,
784  DWORD dwFlags, const void *pvPara)
785 {
786     return TRUE;
787 }
788
789 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
790  DWORD dwFlags, const void *pvPara)
791 {
792     BOOL ret;
793     BYTE hash[16];
794     DWORD size = sizeof(hash);
795
796     ret = CertGetCertificateContextProperty(pCertContext,
797      CERT_MD5_HASH_PROP_ID, hash, &size);
798     if (ret)
799     {
800         const CRYPT_HASH_BLOB *pHash = (const CRYPT_HASH_BLOB *)pvPara;
801
802         if (size == pHash->cbData)
803             ret = !memcmp(pHash->pbData, hash, size);
804         else
805             ret = FALSE;
806     }
807     return ret;
808 }
809
810 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
811  DWORD dwFlags, const void *pvPara)
812 {
813     BOOL ret;
814     BYTE hash[20];
815     DWORD size = sizeof(hash);
816
817     ret = CertGetCertificateContextProperty(pCertContext,
818      CERT_SHA1_HASH_PROP_ID, hash, &size);
819     if (ret)
820     {
821         const CRYPT_HASH_BLOB *pHash = (const CRYPT_HASH_BLOB *)pvPara;
822
823         if (size == pHash->cbData)
824             ret = !memcmp(pHash->pbData, hash, size);
825         else
826             ret = FALSE;
827     }
828     return ret;
829 }
830
831 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
832  DWORD dwFlags, const void *pvPara)
833 {
834     CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
835     BOOL ret;
836
837     if (dwType & CERT_INFO_SUBJECT_FLAG)
838         toCompare = &pCertContext->pCertInfo->Subject;
839     else
840         toCompare = &pCertContext->pCertInfo->Issuer;
841     ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
842      toCompare, blob);
843     return ret;
844 }
845
846 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
847  DWORD dwType, DWORD dwFlags, const void *pvPara)
848 {
849     CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
850
851     return CertCompareCertificateName(pCertContext->dwCertEncodingType,
852      &pCertInfo->Issuer, &pCertContext->pCertInfo->Subject);
853 }
854
855 static BOOL compare_cert_by_issuer(PCCERT_CONTEXT pCertContext,
856  DWORD dwType, DWORD dwFlags, const void *pvPara)
857 {
858     return compare_cert_by_subject_cert(pCertContext, dwType, dwFlags,
859      ((PCCERT_CONTEXT)pvPara)->pCertInfo);
860 }
861
862 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
863  DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
864  PCCERT_CONTEXT pPrevCertContext)
865 {
866     PCCERT_CONTEXT ret;
867     CertCompareFunc compare;
868
869     TRACE("(%p, %ld, %ld, %ld, %p, %p)\n", hCertStore, dwCertEncodingType,
870          dwFlags, dwType, pvPara, pPrevCertContext);
871
872     switch (dwType >> CERT_COMPARE_SHIFT)
873     {
874     case CERT_COMPARE_ANY:
875         compare = compare_cert_any;
876         break;
877     case CERT_COMPARE_MD5_HASH:
878         compare = compare_cert_by_md5_hash;
879         break;
880     case CERT_COMPARE_SHA1_HASH:
881         compare = compare_cert_by_sha1_hash;
882         break;
883     case CERT_COMPARE_NAME:
884         compare = compare_cert_by_name;
885         break;
886     case CERT_COMPARE_SUBJECT_CERT:
887         compare = compare_cert_by_subject_cert;
888         break;
889     case CERT_COMPARE_ISSUER_OF:
890         compare = compare_cert_by_issuer;
891         break;
892     default:
893         FIXME("find type %08lx unimplemented\n", dwType);
894         compare = NULL;
895     }
896
897     if (compare)
898     {
899         BOOL matches = FALSE;
900
901         ret = pPrevCertContext;
902         do {
903             ret = CertEnumCertificatesInStore(hCertStore, ret);
904             if (ret)
905                 matches = compare(ret, dwType, dwFlags, pvPara);
906         } while (ret != NULL && !matches);
907         if (!ret)
908             SetLastError(CRYPT_E_NOT_FOUND);
909     }
910     else
911     {
912         SetLastError(CRYPT_E_NOT_FOUND);
913         ret = NULL;
914     }
915     return ret;
916 }
917
918 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
919  DWORD dwCertEncodingType, PCERT_INFO pCertId)
920 {
921     TRACE("(%p, %08lx, %p)\n", hCertStore, dwCertEncodingType, pCertId);
922
923     if (!pCertId)
924     {
925         SetLastError(E_INVALIDARG);
926         return NULL;
927     }
928     return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
929      CERT_FIND_SUBJECT_CERT, pCertId, NULL);
930 }
931
932 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
933  PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
934 {
935     static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
936      CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
937
938     if (*pdwFlags & ~supportedFlags)
939     {
940         SetLastError(E_INVALIDARG);
941         return FALSE;
942     }
943     if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
944     {
945         DWORD flags = 0;
946         PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
947          NULL, &flags);
948
949         /* FIXME: what if the CRL has expired? */
950         if (crl)
951         {
952             if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
953              pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
954                 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
955         }
956         else
957             *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
958     }
959     if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
960     {
961         if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
962             *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
963     }
964     if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
965     {
966         if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
967          CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
968          CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
969             *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
970     }
971     return TRUE;
972 }
973
974 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
975  PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
976  DWORD *pdwFlags)
977 {
978     PCCERT_CONTEXT ret;
979
980     TRACE("(%p, %p, %p, %08lx)\n", hCertStore, pSubjectContext,
981      pPrevIssuerContext, *pdwFlags);
982
983     if (!pSubjectContext)
984     {
985         SetLastError(E_INVALIDARG);
986         return NULL;
987     }
988
989     ret = CertFindCertificateInStore(hCertStore,
990      pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
991      pSubjectContext, pPrevIssuerContext);
992     if (ret)
993     {
994         if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
995          pdwFlags))
996         {
997             CertFreeCertificateContext(ret);
998             ret = NULL;
999         }
1000     }
1001
1002     return ret;
1003 }
1004
1005 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
1006  CRYPT_ATTRIBUTE rgAttr[])
1007 {
1008     PCRYPT_ATTRIBUTE ret = NULL;
1009     DWORD i;
1010
1011     TRACE("%s %ld %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
1012
1013     if (!cAttr)
1014         return NULL;
1015     if (!pszObjId)
1016     {
1017         SetLastError(ERROR_INVALID_PARAMETER);
1018         return NULL;
1019     }
1020
1021     for (i = 0; !ret && i < cAttr; i++)
1022         if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
1023             ret = &rgAttr[i];
1024     return ret;
1025 }
1026
1027 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
1028  CERT_EXTENSION rgExtensions[])
1029 {
1030     PCERT_EXTENSION ret = NULL;
1031     DWORD i;
1032
1033     TRACE("%s %ld %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
1034
1035     if (!cExtensions)
1036         return NULL;
1037     if (!pszObjId)
1038     {
1039         SetLastError(ERROR_INVALID_PARAMETER);
1040         return NULL;
1041     }
1042
1043     for (i = 0; !ret && i < cExtensions; i++)
1044         if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
1045          rgExtensions[i].pszObjId))
1046             ret = &rgExtensions[i];
1047     return ret;
1048 }
1049
1050 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
1051 {
1052     PCERT_RDN_ATTR ret = NULL;
1053     DWORD i, j;
1054
1055     TRACE("%s %p\n", debugstr_a(pszObjId), pName);
1056
1057     if (!pszObjId)
1058     {
1059         SetLastError(ERROR_INVALID_PARAMETER);
1060         return NULL;
1061     }
1062
1063     for (i = 0; !ret && i < pName->cRDN; i++)
1064         for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
1065             if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
1066              pName->rgRDN[i].rgRDNAttr[j].pszObjId))
1067                 ret = &pName->rgRDN[i].rgRDNAttr[j];
1068     return ret;
1069 }
1070
1071 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
1072  PCERT_INFO pCertInfo)
1073 {
1074     FILETIME fileTime;
1075     LONG ret;
1076
1077     if (!pTimeToVerify)
1078     {
1079         SYSTEMTIME sysTime;
1080
1081         GetSystemTime(&sysTime);
1082         SystemTimeToFileTime(&sysTime, &fileTime);
1083         pTimeToVerify = &fileTime;
1084     }
1085     if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
1086     {
1087         ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
1088         if (ret < 0)
1089             ret = 0;
1090     }
1091     return ret;
1092 }
1093
1094 BOOL WINAPI CryptHashCertificate(HCRYPTPROV hCryptProv, ALG_ID Algid,
1095  DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
1096  DWORD *pcbComputedHash)
1097 {
1098     BOOL ret = TRUE;
1099     HCRYPTHASH hHash = 0;
1100
1101     TRACE("(%ld, %d, %08lx, %p, %ld, %p, %p)\n", hCryptProv, Algid, dwFlags,
1102      pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
1103
1104     if (!hCryptProv)
1105         hCryptProv = CRYPT_GetDefaultProvider();
1106     if (!Algid)
1107         Algid = CALG_SHA1;
1108     if (ret)
1109     {
1110         ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1111         if (ret)
1112         {
1113             ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
1114             if (ret)
1115                 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1116                  pcbComputedHash, 0);
1117             CryptDestroyHash(hHash);
1118         }
1119     }
1120     return ret;
1121 }
1122
1123 BOOL WINAPI CryptSignCertificate(HCRYPTPROV hCryptProv, DWORD dwKeySpec,
1124  DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
1125  DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1126  const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
1127 {
1128     BOOL ret;
1129     ALG_ID algID;
1130     HCRYPTHASH hHash;
1131
1132     TRACE("(%08lx, %ld, %ld, %p, %ld, %p, %p, %p, %p)\n", hCryptProv,
1133      dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
1134      pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
1135
1136     algID = CertOIDToAlgId(pSignatureAlgorithm->pszObjId);
1137     if (!algID)
1138     {
1139         SetLastError(NTE_BAD_ALGID);
1140         return FALSE;
1141     }
1142     if (!hCryptProv)
1143     {
1144         SetLastError(ERROR_INVALID_PARAMETER);
1145         return FALSE;
1146     }
1147
1148     ret = CryptCreateHash(hCryptProv, algID, 0, 0, &hHash);
1149     if (ret)
1150     {
1151         ret = CryptHashData(hHash, pbEncodedToBeSigned, cbEncodedToBeSigned, 0);
1152         if (ret)
1153             ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
1154              pcbSignature);
1155         CryptDestroyHash(hHash);
1156     }
1157     return ret;
1158 }
1159
1160 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV hCryptProv,
1161  DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
1162  PCERT_PUBLIC_KEY_INFO pPublicKey)
1163 {
1164     return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
1165      CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, (void *)pbEncoded,
1166      CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
1167 }
1168
1169 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV hCryptProv,
1170  DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pubKeyInfo,
1171  PCERT_SIGNED_CONTENT_INFO signedCert)
1172 {
1173     BOOL ret;
1174     ALG_ID algID = CertOIDToAlgId(pubKeyInfo->Algorithm.pszObjId);
1175     HCRYPTKEY key;
1176
1177     /* Load the default provider if necessary */
1178     if (!hCryptProv)
1179         hCryptProv = CRYPT_GetDefaultProvider();
1180     ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
1181      pubKeyInfo, algID, 0, NULL, &key);
1182     if (ret)
1183     {
1184         HCRYPTHASH hash;
1185
1186         /* Some key algorithms aren't hash algorithms, so map them */
1187         if (algID == CALG_RSA_SIGN || algID == CALG_RSA_KEYX)
1188             algID = CALG_SHA1;
1189         ret = CryptCreateHash(hCryptProv, algID, 0, 0, &hash);
1190         if (ret)
1191         {
1192             ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
1193              signedCert->ToBeSigned.cbData, 0);
1194             if (ret)
1195                 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
1196                  signedCert->Signature.cbData, key, NULL, 0);
1197             CryptDestroyHash(hash);
1198         }
1199         CryptDestroyKey(key);
1200     }
1201     return ret;
1202 }
1203
1204 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV hCryptProv,
1205  DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
1206  DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
1207 {
1208     BOOL ret = TRUE;
1209     CRYPT_DATA_BLOB subjectBlob;
1210
1211     TRACE("(%08lx, %ld, %ld, %p, %ld, %p, %08lx, %p)\n", hCryptProv,
1212      dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
1213      dwFlags, pvReserved);
1214
1215     switch (dwSubjectType)
1216     {
1217     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
1218     {
1219         PCRYPT_DATA_BLOB blob = (PCRYPT_DATA_BLOB)pvSubject;
1220
1221         subjectBlob.pbData = blob->pbData;
1222         subjectBlob.cbData = blob->cbData;
1223         break;
1224     }
1225     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
1226     {
1227         PCERT_CONTEXT context = (PCERT_CONTEXT)pvSubject;
1228
1229         subjectBlob.pbData = context->pbCertEncoded;
1230         subjectBlob.cbData = context->cbCertEncoded;
1231         break;
1232     }
1233     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
1234     {
1235         PCRL_CONTEXT context = (PCRL_CONTEXT)pvSubject;
1236
1237         subjectBlob.pbData = context->pbCrlEncoded;
1238         subjectBlob.cbData = context->cbCrlEncoded;
1239         break;
1240     }
1241     default:
1242         SetLastError(E_INVALIDARG);
1243         ret = FALSE;
1244     }
1245
1246     if (ret)
1247     {
1248         PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
1249         DWORD size = 0;
1250
1251         ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
1252          subjectBlob.pbData, subjectBlob.cbData,
1253          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1254          (BYTE *)&signedCert, &size);
1255         if (ret)
1256         {
1257             switch (dwIssuerType)
1258             {
1259             case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
1260                 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
1261                  dwCertEncodingType, (PCERT_PUBLIC_KEY_INFO)pvIssuer,
1262                  signedCert);
1263                 break;
1264             case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
1265                 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
1266                  dwCertEncodingType,
1267                  &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
1268                  signedCert);
1269                 break;
1270             case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
1271                 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
1272                 ret = FALSE;
1273                 break;
1274             case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
1275                 if (pvIssuer)
1276                 {
1277                     SetLastError(E_INVALIDARG);
1278                     ret = FALSE;
1279                 }
1280                 else
1281                 {
1282                     FIXME("unimplemented for NULL signer\n");
1283                     SetLastError(E_INVALIDARG);
1284                     ret = FALSE;
1285                 }
1286                 break;
1287             default:
1288                 SetLastError(E_INVALIDARG);
1289                 ret = FALSE;
1290             }
1291             LocalFree(signedCert);
1292         }
1293     }
1294     return ret;
1295 }
1296
1297 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
1298  PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
1299 {
1300     PCERT_ENHKEY_USAGE usage = NULL;
1301     DWORD bytesNeeded;
1302     BOOL ret = TRUE;
1303
1304     if (!pCertContext || !pcbUsage)
1305     {
1306         SetLastError(ERROR_INVALID_PARAMETER);
1307         return FALSE;
1308     }
1309
1310     TRACE("(%p, %08lx, %p, %ld)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
1311
1312     if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
1313     {
1314         DWORD propSize = 0;
1315
1316         if (CertGetCertificateContextProperty(pCertContext,
1317          CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
1318         {
1319             LPBYTE buf = CryptMemAlloc(propSize);
1320
1321             if (buf)
1322             {
1323                 if (CertGetCertificateContextProperty(pCertContext,
1324                  CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
1325                 {
1326                     ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
1327                      X509_ENHANCED_KEY_USAGE, buf, propSize,
1328                      CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
1329                 }
1330                 CryptMemFree(buf);
1331             }
1332         }
1333     }
1334     if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
1335     {
1336         PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
1337          pCertContext->pCertInfo->cExtension,
1338          pCertContext->pCertInfo->rgExtension);
1339
1340         if (ext)
1341         {
1342             ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
1343              X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
1344              CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
1345         }
1346     }
1347     if (!usage)
1348     {
1349         /* If a particular location is specified, this should fail.  Otherwise
1350          * it should succeed with an empty usage.  (This is true on Win2k and
1351          * later, which we emulate.)
1352          */
1353         if (dwFlags)
1354         {
1355             SetLastError(CRYPT_E_NOT_FOUND);
1356             ret = FALSE;
1357         }
1358         else
1359             bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
1360     }
1361
1362     if (ret)
1363     {
1364         if (!pUsage)
1365             *pcbUsage = bytesNeeded;
1366         else if (*pcbUsage < bytesNeeded)
1367         {
1368             SetLastError(ERROR_MORE_DATA);
1369             *pcbUsage = bytesNeeded;
1370             ret = FALSE;
1371         }
1372         else
1373         {
1374             *pcbUsage = bytesNeeded;
1375             if (usage)
1376             {
1377                 DWORD i;
1378                 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
1379                  sizeof(CERT_ENHKEY_USAGE) +
1380                  usage->cUsageIdentifier * sizeof(LPSTR));
1381
1382                 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
1383                 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
1384                  sizeof(CERT_ENHKEY_USAGE));
1385                 for (i = 0; i < usage->cUsageIdentifier; i++)
1386                 {
1387                     pUsage->rgpszUsageIdentifier[i] = nextOID;
1388                     strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
1389                     nextOID += strlen(nextOID) + 1;
1390                 }
1391             }
1392             else
1393                 pUsage->cUsageIdentifier = 0;
1394         }
1395     }
1396     if (usage)
1397         LocalFree(usage);
1398     TRACE("returning %d\n", ret);
1399     return ret;
1400 }
1401
1402 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
1403  PCERT_ENHKEY_USAGE pUsage)
1404 {
1405     BOOL ret;
1406
1407     TRACE("(%p, %p)\n", pCertContext, pUsage);
1408
1409     if (pUsage)
1410     {
1411         CRYPT_DATA_BLOB blob = { 0, NULL };
1412
1413         ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1414          pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
1415         if (ret)
1416         {
1417             ret = CertSetCertificateContextProperty(pCertContext,
1418              CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
1419             LocalFree(blob.pbData);
1420         }
1421     }
1422     else
1423         ret = CertSetCertificateContextProperty(pCertContext,
1424          CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
1425     return ret;
1426 }
1427
1428 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
1429  LPCSTR pszUsageIdentifier)
1430 {
1431     BOOL ret;
1432     DWORD size;
1433
1434     TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
1435
1436     if (CertGetEnhancedKeyUsage(pCertContext,
1437      CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
1438     {
1439         PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
1440
1441         if (usage)
1442         {
1443             ret = CertGetEnhancedKeyUsage(pCertContext,
1444              CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
1445             if (ret)
1446             {
1447                 PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
1448                  sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
1449
1450                 if (newUsage)
1451                 {
1452                     LPSTR nextOID;
1453                     DWORD i;
1454
1455                     newUsage->rgpszUsageIdentifier =
1456                      (LPSTR *)((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
1457                     nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier +
1458                      (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
1459                     for (i = 0; i < usage->cUsageIdentifier; i++)
1460                     {
1461                         newUsage->rgpszUsageIdentifier[i] = nextOID;
1462                         strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
1463                         nextOID += strlen(nextOID) + 1;
1464                     }
1465                     newUsage->rgpszUsageIdentifier[i] = nextOID;
1466                     strcpy(nextOID, pszUsageIdentifier);
1467                     newUsage->cUsageIdentifier = i + 1;
1468                     ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
1469                     CryptMemFree(newUsage);
1470                 }
1471             }
1472             CryptMemFree(usage);
1473         }
1474         else
1475             ret = FALSE;
1476     }
1477     else
1478     {
1479         PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
1480          sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
1481
1482         if (usage)
1483         {
1484             usage->rgpszUsageIdentifier =
1485              (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
1486             usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
1487              sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
1488             strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
1489             usage->cUsageIdentifier = 1;
1490             ret = CertSetEnhancedKeyUsage(pCertContext, usage);
1491             CryptMemFree(usage);
1492         }
1493         else
1494             ret = FALSE;
1495     }
1496     return ret;
1497 }
1498
1499 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
1500  LPCSTR pszUsageIdentifier)
1501 {
1502     BOOL ret;
1503     DWORD size;
1504     CERT_ENHKEY_USAGE usage;
1505
1506     TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
1507
1508     size = sizeof(usage);
1509     ret = CertGetEnhancedKeyUsage(pCertContext,
1510      CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
1511     if (!ret && GetLastError() == ERROR_MORE_DATA)
1512     {
1513         PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
1514
1515         if (pUsage)
1516         {
1517             ret = CertGetEnhancedKeyUsage(pCertContext,
1518              CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
1519             if (ret)
1520             {
1521                 if (pUsage->cUsageIdentifier)
1522                 {
1523                     DWORD i;
1524                     BOOL found = FALSE;
1525
1526                     for (i = 0; i < pUsage->cUsageIdentifier; i++)
1527                     {
1528                         if (!strcmp(pUsage->rgpszUsageIdentifier[i],
1529                          pszUsageIdentifier))
1530                             found = TRUE;
1531                         if (found && i < pUsage->cUsageIdentifier - 1)
1532                             pUsage->rgpszUsageIdentifier[i] =
1533                              pUsage->rgpszUsageIdentifier[i + 1];
1534                     }
1535                     pUsage->cUsageIdentifier--;
1536                     /* Remove the usage if it's empty */
1537                     if (pUsage->cUsageIdentifier)
1538                         ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
1539                     else
1540                         ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
1541                 }
1542             }
1543             CryptMemFree(pUsage);
1544         }
1545         else
1546             ret = FALSE;
1547     }
1548     else
1549     {
1550         /* it fit in an empty usage, therefore there's nothing to remove */
1551         ret = TRUE;
1552     }
1553     return ret;
1554 }
1555
1556 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
1557  int *cNumOIDSs, LPSTR *rghOIDs, DWORD *pcbOIDs)
1558 {
1559     BOOL ret = TRUE;
1560     DWORD i, cbOIDs = 0;
1561     BOOL allUsagesValid = TRUE;
1562     CERT_ENHKEY_USAGE validUsages = { 0, NULL };
1563
1564     TRACE("(%ld, %p, %p, %p, %ld)\n", cCerts, *rghCerts, cNumOIDSs,
1565      rghOIDs, *pcbOIDs);
1566
1567     for (i = 0; ret && i < cCerts; i++)
1568     {
1569         CERT_ENHKEY_USAGE usage;
1570         DWORD size = sizeof(usage);
1571
1572         ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
1573         /* Success is deliberately ignored: it implies all usages are valid */
1574         if (!ret && GetLastError() == ERROR_MORE_DATA)
1575         {
1576             PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
1577
1578             allUsagesValid = FALSE;
1579             if (pUsage)
1580             {
1581                 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
1582                 if (ret)
1583                 {
1584                     if (!validUsages.cUsageIdentifier)
1585                     {
1586                         DWORD j;
1587
1588                         cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
1589                         validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
1590                         for (j = 0; j < validUsages.cUsageIdentifier; j++)
1591                             cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
1592                              + 1;
1593                         validUsages.rgpszUsageIdentifier =
1594                          CryptMemAlloc(cbOIDs);
1595                         if (validUsages.rgpszUsageIdentifier)
1596                         {
1597                             LPSTR nextOID = (LPSTR)
1598                              ((LPBYTE)validUsages.rgpszUsageIdentifier +
1599                              validUsages.cUsageIdentifier * sizeof(LPSTR));
1600
1601                             for (j = 0; j < validUsages.cUsageIdentifier; j++)
1602                             {
1603                                 validUsages.rgpszUsageIdentifier[j] = nextOID;
1604                                 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
1605                                  pUsage->rgpszUsageIdentifier[j]);
1606                                 nextOID += lstrlenA(nextOID) + 1;
1607                             }
1608                         }
1609                         else
1610                             ret = FALSE;
1611                     }
1612                     else
1613                     {
1614                         DWORD j, k, validIndexes = 0, numRemoved = 0;
1615
1616                         /* Merge: build a bitmap of all the indexes of
1617                          * validUsages.rgpszUsageIdentifier that are in pUsage.
1618                          */
1619                         for (j = 0; j < pUsage->cUsageIdentifier; j++)
1620                         {
1621                             for (k = 0; k < validUsages.cUsageIdentifier; k++)
1622                             {
1623                                 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
1624                                  validUsages.rgpszUsageIdentifier[k]))
1625                                 {
1626                                     validIndexes |= (1 << k);
1627                                     break;
1628                                 }
1629                             }
1630                         }
1631                         /* Merge by removing from validUsages those that are
1632                          * not in the bitmap.
1633                          */
1634                         for (j = 0; j < validUsages.cUsageIdentifier; j++)
1635                         {
1636                             if (!(validIndexes & (1 << j)))
1637                             {
1638                                 if (j < validUsages.cUsageIdentifier - 1)
1639                                 {
1640                                     memcpy(&validUsages.rgpszUsageIdentifier[j],
1641                                      &validUsages.rgpszUsageIdentifier[j +
1642                                      numRemoved + 1],
1643                                      (validUsages.cUsageIdentifier - numRemoved
1644                                      - j - 1) * sizeof(LPSTR));
1645                                     cbOIDs -= lstrlenA(
1646                                      validUsages.rgpszUsageIdentifier[j]) + 1 +
1647                                      sizeof(LPSTR);
1648                                     numRemoved++;
1649                                 }
1650                                 else
1651                                     validUsages.cUsageIdentifier--;
1652                             }
1653                         }
1654                     }
1655                 }
1656                 CryptMemFree(pUsage);
1657             }
1658             else
1659                 ret = FALSE;
1660         }
1661     }
1662     if (ret)
1663     {
1664         if (allUsagesValid)
1665         {
1666             *cNumOIDSs = -1;
1667             *pcbOIDs = 0;
1668         }
1669         else
1670         {
1671             if (!rghOIDs || *pcbOIDs < cbOIDs)
1672             {
1673                 *pcbOIDs = cbOIDs;
1674                 SetLastError(ERROR_MORE_DATA);
1675                 ret = FALSE;
1676             }
1677             else
1678             {
1679                 LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
1680                  validUsages.cUsageIdentifier * sizeof(LPSTR));
1681
1682                 *pcbOIDs = cbOIDs;
1683                 *cNumOIDSs = validUsages.cUsageIdentifier;
1684                 for (i = 0; i < validUsages.cUsageIdentifier; i++)
1685                 {
1686                     rghOIDs[i] = nextOID;
1687                     lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
1688                     nextOID += lstrlenA(nextOID) + 1;
1689                 }
1690             }
1691         }
1692     }
1693     CryptMemFree(validUsages.rgpszUsageIdentifier);
1694     return ret;
1695 }
1696
1697 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
1698  * pInfo is NULL, from the attributes of hProv.
1699  */
1700 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
1701  PCRYPT_KEY_PROV_INFO pInfo, HCRYPTPROV hProv)
1702 {
1703     CRYPT_KEY_PROV_INFO info = { 0 };
1704     BOOL ret;
1705
1706     if (!pInfo)
1707     {
1708         DWORD size;
1709         int len;
1710
1711         ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
1712         if (ret)
1713         {
1714             LPSTR szContainer = CryptMemAlloc(size);
1715
1716             if (szContainer)
1717             {
1718                 ret = CryptGetProvParam(hProv, PP_CONTAINER,
1719                  (BYTE *)szContainer, &size, 0);
1720                 if (ret)
1721                 {
1722                     len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
1723                      NULL, 0);
1724                     if (len)
1725                     {
1726                         info.pwszContainerName = CryptMemAlloc(len *
1727                          sizeof(WCHAR));
1728                         len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
1729                          info.pwszContainerName, len);
1730                     }
1731                 }
1732                 CryptMemFree(szContainer);
1733             }
1734         }
1735         ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
1736         if (ret)
1737         {
1738             LPSTR szProvider = CryptMemAlloc(size);
1739
1740             if (szProvider)
1741             {
1742                 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
1743                  &size, 0);
1744                 if (ret)
1745                 {
1746                     len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
1747                      NULL, 0);
1748                     if (len)
1749                     {
1750                         info.pwszProvName = CryptMemAlloc(len *
1751                          sizeof(WCHAR));
1752                         len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
1753                          info.pwszProvName, len);
1754                     }
1755                 }
1756                 CryptMemFree(szProvider);
1757             }
1758         }
1759         size = sizeof(info.dwKeySpec);
1760         ret = CryptGetProvParam(hProv, PP_KEYSPEC, (LPBYTE)&info.dwKeySpec,
1761          &size, 0);
1762         if (!ret)
1763             info.dwKeySpec = AT_SIGNATURE;
1764         size = sizeof(info.dwProvType);
1765         ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
1766          &size, 0);
1767         if (!ret)
1768             info.dwProvType = PROV_RSA_FULL;
1769         pInfo = &info;
1770     }
1771
1772     ret = CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
1773      0, pInfo);
1774
1775     if (pInfo == &info)
1776     {
1777         CryptMemFree(info.pwszContainerName);
1778         CryptMemFree(info.pwszProvName);
1779     }
1780 }
1781
1782 /* Creates a signed certificate context from the unsigned, encoded certificate
1783  * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
1784  */
1785 static PCCERT_CONTEXT CRYPT_CreateSignedCert(PCRYPT_DER_BLOB blob,
1786  HCRYPTPROV hProv, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
1787 {
1788     PCCERT_CONTEXT context = NULL;
1789     BOOL ret;
1790     DWORD sigSize = 0;
1791
1792     ret = CryptSignCertificate(hProv, AT_SIGNATURE, X509_ASN_ENCODING,
1793      blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
1794     if (ret)
1795     {
1796         LPBYTE sig = CryptMemAlloc(sigSize);
1797
1798         ret = CryptSignCertificate(hProv, AT_SIGNATURE, X509_ASN_ENCODING,
1799          blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
1800         if (ret)
1801         {
1802             CERT_SIGNED_CONTENT_INFO signedInfo;
1803             BYTE *encodedSignedCert = NULL;
1804             DWORD encodedSignedCertSize = 0;
1805
1806             signedInfo.ToBeSigned.cbData = blob->cbData;
1807             signedInfo.ToBeSigned.pbData = blob->pbData;
1808             memcpy(&signedInfo.SignatureAlgorithm, sigAlgo,
1809              sizeof(signedInfo.SignatureAlgorithm));
1810             signedInfo.Signature.cbData = sigSize;
1811             signedInfo.Signature.pbData = sig;
1812             signedInfo.Signature.cUnusedBits = 0;
1813             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
1814              &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1815              (BYTE *)&encodedSignedCert, &encodedSignedCertSize);
1816             if (ret)
1817             {
1818                 context = CertCreateCertificateContext(X509_ASN_ENCODING,
1819                  encodedSignedCert, encodedSignedCertSize);
1820                 LocalFree(encodedSignedCert);
1821             }
1822         }
1823         CryptMemFree(sig);
1824     }
1825     return context;
1826 }
1827
1828 /* Copies data from the parameters into info, where:
1829  * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
1830  *                     Must not be NULL
1831  * pSignatureAlgorithm: Optional.
1832  * pStartTime: The starting time of the certificate.  If NULL, the current
1833  *             system time is used.
1834  * pEndTime: The ending time of the certificate.  If NULL, one year past the
1835  *           starting time is used.
1836  * pubKey: The public key of the certificate.  Must not be NULL.
1837  * pExtensions: Extensions to be included with the certificate.  Optional.
1838  */
1839 static void CRYPT_MakeCertInfo(PCERT_INFO info,
1840  PCERT_NAME_BLOB pSubjectIssuerBlob,
1841  PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
1842  PSYSTEMTIME pEndTime, PCERT_PUBLIC_KEY_INFO pubKey,
1843  PCERT_EXTENSIONS pExtensions)
1844 {
1845     /* FIXME: what serial number to use? */
1846     static const BYTE serialNum[] = { 1 };
1847     static CHAR oid[] = szOID_RSA_SHA1RSA;
1848
1849     assert(info);
1850     assert(pSubjectIssuerBlob);
1851     assert(pubKey);
1852
1853     info->dwVersion = CERT_V3;
1854     info->SerialNumber.cbData = sizeof(serialNum);
1855     info->SerialNumber.pbData = (LPBYTE)serialNum;
1856     if (pSignatureAlgorithm)
1857         memcpy(&info->SignatureAlgorithm, pSignatureAlgorithm,
1858          sizeof(info->SignatureAlgorithm));
1859     else
1860     {
1861         info->SignatureAlgorithm.pszObjId = oid;
1862         info->SignatureAlgorithm.Parameters.cbData = 0;
1863         info->SignatureAlgorithm.Parameters.pbData = NULL;
1864     }
1865     info->Issuer.cbData = pSubjectIssuerBlob->cbData;
1866     info->Issuer.pbData = pSubjectIssuerBlob->pbData;
1867     if (pStartTime)
1868         SystemTimeToFileTime(pStartTime, &info->NotBefore);
1869     else
1870         GetSystemTimeAsFileTime(&info->NotBefore);
1871     if (pEndTime)
1872         SystemTimeToFileTime(pEndTime, &info->NotAfter);
1873     else
1874     {
1875         SYSTEMTIME endTime;
1876
1877         if (FileTimeToSystemTime(&info->NotBefore, &endTime))
1878         {
1879             endTime.wYear++;
1880             SystemTimeToFileTime(&endTime, &info->NotAfter);
1881         }
1882     }
1883     info->Subject.cbData = pSubjectIssuerBlob->cbData;
1884     info->Subject.pbData = pSubjectIssuerBlob->pbData;
1885     memcpy(&info->SubjectPublicKeyInfo, pubKey,
1886      sizeof(info->SubjectPublicKeyInfo));
1887     if (pExtensions)
1888     {
1889         info->cExtension = pExtensions->cExtension;
1890         info->rgExtension = pExtensions->rgExtension;
1891     }
1892     else
1893     {
1894         info->cExtension = 0;
1895         info->rgExtension = NULL;
1896     }
1897 }
1898  
1899 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
1900 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
1901 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
1902
1903 static HCRYPTPROV CRYPT_CreateKeyProv(void)
1904 {
1905     HCRYPTPROV hProv = 0;
1906     HMODULE rpcrt = LoadLibraryA("rpcrt4");
1907
1908     if (rpcrt)
1909     {
1910         UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
1911          "UuidCreate");
1912         UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
1913          "UuidToString");
1914         RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
1915          rpcrt, "RpcStringFree");
1916
1917         if (uuidCreate && uuidToString && rpcStringFree)
1918         {
1919             UUID uuid;
1920             RPC_STATUS status = uuidCreate(&uuid);
1921
1922             if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
1923             {
1924                 unsigned char *uuidStr;
1925
1926                 status = uuidToString(&uuid, &uuidStr);
1927                 if (status == RPC_S_OK)
1928                 {
1929                     BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
1930                      MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
1931
1932                     if (ret)
1933                     {
1934                         HCRYPTKEY key;
1935
1936                         ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
1937                         if (ret)
1938                             CryptDestroyKey(key);
1939                     }
1940                     rpcStringFree(&uuidStr);
1941                 }
1942             }
1943         }
1944         FreeLibrary(rpcrt);
1945     }
1946     return hProv;
1947 }
1948
1949 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV hProv,
1950  PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
1951  PCRYPT_KEY_PROV_INFO pKeyProvInfo,
1952  PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
1953  PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
1954 {
1955     PCCERT_CONTEXT context = NULL;
1956     BOOL ret, releaseContext = FALSE;
1957     PCERT_PUBLIC_KEY_INFO pubKey = NULL;
1958     DWORD pubKeySize = 0;
1959
1960     TRACE("(0x%08lx, %p, %08lx, %p, %p, %p, %p, %p)\n", hProv,
1961      pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
1962      pExtensions, pExtensions);
1963
1964     if (!hProv)
1965     {
1966         hProv = CRYPT_CreateKeyProv();
1967         releaseContext = TRUE;
1968     }
1969
1970     CryptExportPublicKeyInfo(hProv, AT_SIGNATURE, X509_ASN_ENCODING, NULL,
1971      &pubKeySize);
1972     pubKey = CryptMemAlloc(pubKeySize);
1973     if (pubKey)
1974     {
1975         ret = CryptExportPublicKeyInfo(hProv, AT_SIGNATURE, X509_ASN_ENCODING,
1976          pubKey, &pubKeySize);
1977         if (ret)
1978         {
1979             CERT_INFO info = { 0 };
1980             CRYPT_DER_BLOB blob = { 0, NULL };
1981             BOOL ret;
1982
1983             CRYPT_MakeCertInfo(&info, pSubjectIssuerBlob, pSignatureAlgorithm,
1984              pStartTime, pEndTime, pubKey, pExtensions);
1985             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
1986              &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, (BYTE *)&blob.pbData,
1987              &blob.cbData);
1988             if (ret)
1989             {
1990                 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
1991                     context = CRYPT_CreateSignedCert(&blob, hProv,
1992                      &info.SignatureAlgorithm);
1993                 else
1994                     context = CertCreateCertificateContext(X509_ASN_ENCODING,
1995                      blob.pbData, blob.cbData);
1996                 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
1997                     CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
1998                 LocalFree(blob.pbData);
1999             }
2000         }
2001         CryptMemFree(pubKey);
2002     }
2003     if (releaseContext)
2004         CryptReleaseContext(hProv, 0);
2005     return context;
2006 }