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