user: Fix CopyImage function declaration.
[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 DWORD WINAPI CertGetPublicKeyLength(DWORD dwCertEncodingType,
776  PCERT_PUBLIC_KEY_INFO pPublicKey)
777 {
778     DWORD len = 0;
779
780     TRACE("(%08lx, %p)\n", dwCertEncodingType, pPublicKey);
781
782     if (dwCertEncodingType != X509_ASN_ENCODING)
783     {
784         SetLastError(ERROR_FILE_NOT_FOUND);
785         return 0;
786     }
787     if (pPublicKey->Algorithm.pszObjId &&
788      !strcmp(pPublicKey->Algorithm.pszObjId, szOID_RSA_DH))
789     {
790         FIXME("unimplemented for DH public keys\n");
791         SetLastError(CRYPT_E_ASN1_BADTAG);
792     }
793     else
794     {
795         DWORD size;
796         PBYTE buf;
797         BOOL ret = CryptDecodeObjectEx(dwCertEncodingType,
798          RSA_CSP_PUBLICKEYBLOB, pPublicKey->PublicKey.pbData,
799          pPublicKey->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &buf,
800          &size);
801
802         if (ret)
803         {
804             RSAPUBKEY *rsaPubKey = (RSAPUBKEY *)((LPBYTE)buf +
805              sizeof(BLOBHEADER));
806
807             len = rsaPubKey->bitlen;
808             LocalFree(buf);
809         }
810     }
811     return len;
812 }
813
814 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
815  DWORD dwFlags, const void *pvPara);
816
817 static BOOL compare_cert_any(PCCERT_CONTEXT pCertContext, DWORD dwType,
818  DWORD dwFlags, const void *pvPara)
819 {
820     return TRUE;
821 }
822
823 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
824  DWORD dwFlags, const void *pvPara)
825 {
826     BOOL ret;
827     BYTE hash[16];
828     DWORD size = sizeof(hash);
829
830     ret = CertGetCertificateContextProperty(pCertContext,
831      CERT_MD5_HASH_PROP_ID, hash, &size);
832     if (ret)
833     {
834         const CRYPT_HASH_BLOB *pHash = (const CRYPT_HASH_BLOB *)pvPara;
835
836         if (size == pHash->cbData)
837             ret = !memcmp(pHash->pbData, hash, size);
838         else
839             ret = FALSE;
840     }
841     return ret;
842 }
843
844 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
845  DWORD dwFlags, const void *pvPara)
846 {
847     BOOL ret;
848     BYTE hash[20];
849     DWORD size = sizeof(hash);
850
851     ret = CertGetCertificateContextProperty(pCertContext,
852      CERT_SHA1_HASH_PROP_ID, hash, &size);
853     if (ret)
854     {
855         const CRYPT_HASH_BLOB *pHash = (const CRYPT_HASH_BLOB *)pvPara;
856
857         if (size == pHash->cbData)
858             ret = !memcmp(pHash->pbData, hash, size);
859         else
860             ret = FALSE;
861     }
862     return ret;
863 }
864
865 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
866  DWORD dwFlags, const void *pvPara)
867 {
868     CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
869     BOOL ret;
870
871     if (dwType & CERT_INFO_SUBJECT_FLAG)
872         toCompare = &pCertContext->pCertInfo->Subject;
873     else
874         toCompare = &pCertContext->pCertInfo->Issuer;
875     ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
876      toCompare, blob);
877     return ret;
878 }
879
880 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
881  DWORD dwType, DWORD dwFlags, const void *pvPara)
882 {
883     CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
884
885     return CertCompareCertificateName(pCertContext->dwCertEncodingType,
886      &pCertInfo->Issuer, &pCertContext->pCertInfo->Subject);
887 }
888
889 static BOOL compare_cert_by_issuer(PCCERT_CONTEXT pCertContext,
890  DWORD dwType, DWORD dwFlags, const void *pvPara)
891 {
892     return compare_cert_by_subject_cert(pCertContext, dwType, dwFlags,
893      ((PCCERT_CONTEXT)pvPara)->pCertInfo);
894 }
895
896 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
897  DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
898  PCCERT_CONTEXT pPrevCertContext)
899 {
900     PCCERT_CONTEXT ret;
901     CertCompareFunc compare;
902
903     TRACE("(%p, %ld, %ld, %ld, %p, %p)\n", hCertStore, dwCertEncodingType,
904          dwFlags, dwType, pvPara, pPrevCertContext);
905
906     switch (dwType >> CERT_COMPARE_SHIFT)
907     {
908     case CERT_COMPARE_ANY:
909         compare = compare_cert_any;
910         break;
911     case CERT_COMPARE_MD5_HASH:
912         compare = compare_cert_by_md5_hash;
913         break;
914     case CERT_COMPARE_SHA1_HASH:
915         compare = compare_cert_by_sha1_hash;
916         break;
917     case CERT_COMPARE_NAME:
918         compare = compare_cert_by_name;
919         break;
920     case CERT_COMPARE_SUBJECT_CERT:
921         compare = compare_cert_by_subject_cert;
922         break;
923     case CERT_COMPARE_ISSUER_OF:
924         compare = compare_cert_by_issuer;
925         break;
926     default:
927         FIXME("find type %08lx unimplemented\n", dwType);
928         compare = NULL;
929     }
930
931     if (compare)
932     {
933         BOOL matches = FALSE;
934
935         ret = pPrevCertContext;
936         do {
937             ret = CertEnumCertificatesInStore(hCertStore, ret);
938             if (ret)
939                 matches = compare(ret, dwType, dwFlags, pvPara);
940         } while (ret != NULL && !matches);
941         if (!ret)
942             SetLastError(CRYPT_E_NOT_FOUND);
943     }
944     else
945     {
946         SetLastError(CRYPT_E_NOT_FOUND);
947         ret = NULL;
948     }
949     return ret;
950 }
951
952 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
953  DWORD dwCertEncodingType, PCERT_INFO pCertId)
954 {
955     TRACE("(%p, %08lx, %p)\n", hCertStore, dwCertEncodingType, pCertId);
956
957     if (!pCertId)
958     {
959         SetLastError(E_INVALIDARG);
960         return NULL;
961     }
962     return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
963      CERT_FIND_SUBJECT_CERT, pCertId, NULL);
964 }
965
966 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
967  PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
968 {
969     static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
970      CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
971
972     if (*pdwFlags & ~supportedFlags)
973     {
974         SetLastError(E_INVALIDARG);
975         return FALSE;
976     }
977     if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
978     {
979         DWORD flags = 0;
980         PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
981          NULL, &flags);
982
983         /* FIXME: what if the CRL has expired? */
984         if (crl)
985         {
986             if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
987              pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
988                 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
989         }
990         else
991             *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
992     }
993     if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
994     {
995         if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
996             *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
997     }
998     if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
999     {
1000         if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
1001          CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
1002          CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
1003             *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
1004     }
1005     return TRUE;
1006 }
1007
1008 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
1009  PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
1010  DWORD *pdwFlags)
1011 {
1012     PCCERT_CONTEXT ret;
1013
1014     TRACE("(%p, %p, %p, %08lx)\n", hCertStore, pSubjectContext,
1015      pPrevIssuerContext, *pdwFlags);
1016
1017     if (!pSubjectContext)
1018     {
1019         SetLastError(E_INVALIDARG);
1020         return NULL;
1021     }
1022
1023     ret = CertFindCertificateInStore(hCertStore,
1024      pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
1025      pSubjectContext, pPrevIssuerContext);
1026     if (ret)
1027     {
1028         if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
1029          pdwFlags))
1030         {
1031             CertFreeCertificateContext(ret);
1032             ret = NULL;
1033         }
1034     }
1035
1036     return ret;
1037 }
1038
1039 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
1040  CRYPT_ATTRIBUTE rgAttr[])
1041 {
1042     PCRYPT_ATTRIBUTE ret = NULL;
1043     DWORD i;
1044
1045     TRACE("%s %ld %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
1046
1047     if (!cAttr)
1048         return NULL;
1049     if (!pszObjId)
1050     {
1051         SetLastError(ERROR_INVALID_PARAMETER);
1052         return NULL;
1053     }
1054
1055     for (i = 0; !ret && i < cAttr; i++)
1056         if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
1057             ret = &rgAttr[i];
1058     return ret;
1059 }
1060
1061 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
1062  CERT_EXTENSION rgExtensions[])
1063 {
1064     PCERT_EXTENSION ret = NULL;
1065     DWORD i;
1066
1067     TRACE("%s %ld %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
1068
1069     if (!cExtensions)
1070         return NULL;
1071     if (!pszObjId)
1072     {
1073         SetLastError(ERROR_INVALID_PARAMETER);
1074         return NULL;
1075     }
1076
1077     for (i = 0; !ret && i < cExtensions; i++)
1078         if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
1079          rgExtensions[i].pszObjId))
1080             ret = &rgExtensions[i];
1081     return ret;
1082 }
1083
1084 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
1085 {
1086     PCERT_RDN_ATTR ret = NULL;
1087     DWORD i, j;
1088
1089     TRACE("%s %p\n", debugstr_a(pszObjId), pName);
1090
1091     if (!pszObjId)
1092     {
1093         SetLastError(ERROR_INVALID_PARAMETER);
1094         return NULL;
1095     }
1096
1097     for (i = 0; !ret && i < pName->cRDN; i++)
1098         for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
1099             if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
1100              pName->rgRDN[i].rgRDNAttr[j].pszObjId))
1101                 ret = &pName->rgRDN[i].rgRDNAttr[j];
1102     return ret;
1103 }
1104
1105 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
1106  PCERT_INFO pCertInfo)
1107 {
1108     FILETIME fileTime;
1109     LONG ret;
1110
1111     if (!pTimeToVerify)
1112     {
1113         SYSTEMTIME sysTime;
1114
1115         GetSystemTime(&sysTime);
1116         SystemTimeToFileTime(&sysTime, &fileTime);
1117         pTimeToVerify = &fileTime;
1118     }
1119     if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
1120     {
1121         ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
1122         if (ret < 0)
1123             ret = 0;
1124     }
1125     return ret;
1126 }
1127
1128 BOOL WINAPI CryptHashCertificate(HCRYPTPROV hCryptProv, ALG_ID Algid,
1129  DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
1130  DWORD *pcbComputedHash)
1131 {
1132     BOOL ret = TRUE;
1133     HCRYPTHASH hHash = 0;
1134
1135     TRACE("(%ld, %d, %08lx, %p, %ld, %p, %p)\n", hCryptProv, Algid, dwFlags,
1136      pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
1137
1138     if (!hCryptProv)
1139         hCryptProv = CRYPT_GetDefaultProvider();
1140     if (!Algid)
1141         Algid = CALG_SHA1;
1142     if (ret)
1143     {
1144         ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1145         if (ret)
1146         {
1147             ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
1148             if (ret)
1149                 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1150                  pcbComputedHash, 0);
1151             CryptDestroyHash(hHash);
1152         }
1153     }
1154     return ret;
1155 }
1156
1157 BOOL WINAPI CryptHashPublicKeyInfo(HCRYPTPROV hCryptProv, ALG_ID Algid,
1158  DWORD dwFlags, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo,
1159  BYTE *pbComputedHash, DWORD *pcbComputedHash)
1160 {
1161     BOOL ret = TRUE;
1162     HCRYPTHASH hHash = 0;
1163
1164     TRACE("(%ld, %d, %08lx, %ld, %p, %p, %p)\n", hCryptProv, Algid, dwFlags,
1165      dwCertEncodingType, pInfo, pbComputedHash, pcbComputedHash);
1166
1167     if (!hCryptProv)
1168         hCryptProv = CRYPT_GetDefaultProvider();
1169     if (!Algid)
1170         Algid = CALG_MD5;
1171     if (ret)
1172     {
1173         BYTE *buf;
1174         DWORD size = 0;
1175
1176         ret = CryptEncodeObjectEx(dwCertEncodingType, X509_PUBLIC_KEY_INFO,
1177          pInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL, &buf, &size);
1178         if (ret)
1179         {
1180             ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1181             if (ret)
1182             {
1183                 ret = CryptHashData(hHash, buf, size, 0);
1184                 if (ret)
1185                     ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1186                      pcbComputedHash, 0);
1187                 CryptDestroyHash(hHash);
1188             }
1189             LocalFree(buf);
1190         }
1191     }
1192     return ret;
1193 }
1194
1195 BOOL WINAPI CryptSignCertificate(HCRYPTPROV hCryptProv, DWORD dwKeySpec,
1196  DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
1197  DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1198  const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
1199 {
1200     BOOL ret;
1201     PCCRYPT_OID_INFO info;
1202     HCRYPTHASH hHash;
1203
1204     TRACE("(%08lx, %ld, %ld, %p, %ld, %p, %p, %p, %p)\n", hCryptProv,
1205      dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
1206      pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
1207
1208     info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1209      pSignatureAlgorithm->pszObjId, 0);
1210     if (!info)
1211     {
1212         SetLastError(NTE_BAD_ALGID);
1213         return FALSE;
1214     }
1215     if (info->dwGroupId == CRYPT_HASH_ALG_OID_GROUP_ID)
1216     {
1217         if (!hCryptProv)
1218             hCryptProv = CRYPT_GetDefaultProvider();
1219         ret = CryptCreateHash(hCryptProv, info->Algid, 0, 0, &hHash);
1220         if (ret)
1221         {
1222             ret = CryptHashData(hHash, pbEncodedToBeSigned,
1223              cbEncodedToBeSigned, 0);
1224             if (ret)
1225                 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbSignature,
1226                  pcbSignature, 0);
1227             CryptDestroyHash(hHash);
1228         }
1229     }
1230     else
1231     {
1232         if (!hCryptProv)
1233         {
1234             SetLastError(ERROR_INVALID_PARAMETER);
1235             ret = FALSE;
1236         }
1237         else
1238         {
1239             ret = CryptCreateHash(hCryptProv, info->Algid, 0, 0, &hHash);
1240             if (ret)
1241             {
1242                 ret = CryptHashData(hHash, pbEncodedToBeSigned,
1243                  cbEncodedToBeSigned, 0);
1244                 if (ret)
1245                     ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
1246                      pcbSignature);
1247                 CryptDestroyHash(hHash);
1248             }
1249         }
1250     }
1251     return ret;
1252 }
1253
1254 BOOL WINAPI CryptSignAndEncodeCertificate(HCRYPTPROV hCryptProv,
1255  DWORD dwKeySpec, DWORD dwCertEncodingType, LPCSTR lpszStructType,
1256  const void *pvStructInfo, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1257  const void *pvHashAuxInfo, PBYTE pbEncoded, DWORD *pcbEncoded)
1258 {
1259     BOOL ret;
1260     DWORD encodedSize, hashSize;
1261
1262     TRACE("(%08lx, %ld, %ld, %s, %p, %p, %p, %p, %p)\n", hCryptProv, dwKeySpec,
1263      dwCertEncodingType, debugstr_a(lpszStructType), pvStructInfo,
1264      pSignatureAlgorithm, pvHashAuxInfo, pbEncoded, pcbEncoded);
1265
1266     ret = CryptEncodeObject(dwCertEncodingType, lpszStructType, pvStructInfo,
1267      NULL, &encodedSize);
1268     if (ret)
1269     {
1270         PBYTE encoded = CryptMemAlloc(encodedSize);
1271
1272         if (encoded)
1273         {
1274             ret = CryptEncodeObject(dwCertEncodingType, lpszStructType,
1275              pvStructInfo, encoded, &encodedSize);
1276             if (ret)
1277             {
1278                 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
1279                  dwCertEncodingType, encoded, encodedSize, pSignatureAlgorithm,
1280                  pvHashAuxInfo, NULL, &hashSize);
1281                 if (ret)
1282                 {
1283                     PBYTE hash = CryptMemAlloc(hashSize);
1284
1285                     if (hash)
1286                     {
1287                         ret = CryptSignCertificate(hCryptProv, dwKeySpec,
1288                          dwCertEncodingType, encoded, encodedSize,
1289                          pSignatureAlgorithm, pvHashAuxInfo, hash, &hashSize);
1290                         if (ret)
1291                         {
1292                             CERT_SIGNED_CONTENT_INFO info = { { 0 } };
1293
1294                             info.ToBeSigned.cbData = encodedSize;
1295                             info.ToBeSigned.pbData = encoded;
1296                             memcpy(&info.SignatureAlgorithm,
1297                              pSignatureAlgorithm,
1298                              sizeof(info.SignatureAlgorithm));
1299                             info.Signature.cbData = hashSize;
1300                             info.Signature.pbData = hash;
1301                             info.Signature.cUnusedBits = 0;
1302                             ret = CryptEncodeObject(dwCertEncodingType,
1303                              X509_CERT, &info, pbEncoded, pcbEncoded);
1304                         }
1305                         CryptMemFree(hash);
1306                     }
1307                 }
1308             }
1309             CryptMemFree(encoded);
1310         }
1311     }
1312     return ret;
1313 }
1314
1315 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV hCryptProv,
1316  DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
1317  PCERT_PUBLIC_KEY_INFO pPublicKey)
1318 {
1319     return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
1320      CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, (void *)pbEncoded,
1321      CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
1322 }
1323
1324 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV hCryptProv,
1325  DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pubKeyInfo,
1326  PCERT_SIGNED_CONTENT_INFO signedCert)
1327 {
1328     BOOL ret;
1329     ALG_ID algID = CertOIDToAlgId(pubKeyInfo->Algorithm.pszObjId);
1330     HCRYPTKEY key;
1331
1332     /* Load the default provider if necessary */
1333     if (!hCryptProv)
1334         hCryptProv = CRYPT_GetDefaultProvider();
1335     ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
1336      pubKeyInfo, algID, 0, NULL, &key);
1337     if (ret)
1338     {
1339         HCRYPTHASH hash;
1340
1341         /* Some key algorithms aren't hash algorithms, so map them */
1342         if (algID == CALG_RSA_SIGN || algID == CALG_RSA_KEYX)
1343             algID = CALG_SHA1;
1344         ret = CryptCreateHash(hCryptProv, algID, 0, 0, &hash);
1345         if (ret)
1346         {
1347             ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
1348              signedCert->ToBeSigned.cbData, 0);
1349             if (ret)
1350                 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
1351                  signedCert->Signature.cbData, key, NULL, 0);
1352             CryptDestroyHash(hash);
1353         }
1354         CryptDestroyKey(key);
1355     }
1356     return ret;
1357 }
1358
1359 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV hCryptProv,
1360  DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
1361  DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
1362 {
1363     BOOL ret = TRUE;
1364     CRYPT_DATA_BLOB subjectBlob;
1365
1366     TRACE("(%08lx, %ld, %ld, %p, %ld, %p, %08lx, %p)\n", hCryptProv,
1367      dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
1368      dwFlags, pvReserved);
1369
1370     switch (dwSubjectType)
1371     {
1372     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
1373     {
1374         PCRYPT_DATA_BLOB blob = (PCRYPT_DATA_BLOB)pvSubject;
1375
1376         subjectBlob.pbData = blob->pbData;
1377         subjectBlob.cbData = blob->cbData;
1378         break;
1379     }
1380     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
1381     {
1382         PCERT_CONTEXT context = (PCERT_CONTEXT)pvSubject;
1383
1384         subjectBlob.pbData = context->pbCertEncoded;
1385         subjectBlob.cbData = context->cbCertEncoded;
1386         break;
1387     }
1388     case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
1389     {
1390         PCRL_CONTEXT context = (PCRL_CONTEXT)pvSubject;
1391
1392         subjectBlob.pbData = context->pbCrlEncoded;
1393         subjectBlob.cbData = context->cbCrlEncoded;
1394         break;
1395     }
1396     default:
1397         SetLastError(E_INVALIDARG);
1398         ret = FALSE;
1399     }
1400
1401     if (ret)
1402     {
1403         PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
1404         DWORD size = 0;
1405
1406         ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
1407          subjectBlob.pbData, subjectBlob.cbData,
1408          CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1409          (BYTE *)&signedCert, &size);
1410         if (ret)
1411         {
1412             switch (dwIssuerType)
1413             {
1414             case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
1415                 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
1416                  dwCertEncodingType, (PCERT_PUBLIC_KEY_INFO)pvIssuer,
1417                  signedCert);
1418                 break;
1419             case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
1420                 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
1421                  dwCertEncodingType,
1422                  &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
1423                  signedCert);
1424                 break;
1425             case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
1426                 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
1427                 ret = FALSE;
1428                 break;
1429             case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
1430                 if (pvIssuer)
1431                 {
1432                     SetLastError(E_INVALIDARG);
1433                     ret = FALSE;
1434                 }
1435                 else
1436                 {
1437                     FIXME("unimplemented for NULL signer\n");
1438                     SetLastError(E_INVALIDARG);
1439                     ret = FALSE;
1440                 }
1441                 break;
1442             default:
1443                 SetLastError(E_INVALIDARG);
1444                 ret = FALSE;
1445             }
1446             LocalFree(signedCert);
1447         }
1448     }
1449     return ret;
1450 }
1451
1452 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
1453  PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
1454 {
1455     PCERT_ENHKEY_USAGE usage = NULL;
1456     DWORD bytesNeeded;
1457     BOOL ret = TRUE;
1458
1459     if (!pCertContext || !pcbUsage)
1460     {
1461         SetLastError(ERROR_INVALID_PARAMETER);
1462         return FALSE;
1463     }
1464
1465     TRACE("(%p, %08lx, %p, %ld)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
1466
1467     if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
1468     {
1469         DWORD propSize = 0;
1470
1471         if (CertGetCertificateContextProperty(pCertContext,
1472          CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
1473         {
1474             LPBYTE buf = CryptMemAlloc(propSize);
1475
1476             if (buf)
1477             {
1478                 if (CertGetCertificateContextProperty(pCertContext,
1479                  CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
1480                 {
1481                     ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
1482                      X509_ENHANCED_KEY_USAGE, buf, propSize,
1483                      CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
1484                 }
1485                 CryptMemFree(buf);
1486             }
1487         }
1488     }
1489     if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
1490     {
1491         PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
1492          pCertContext->pCertInfo->cExtension,
1493          pCertContext->pCertInfo->rgExtension);
1494
1495         if (ext)
1496         {
1497             ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
1498              X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
1499              CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
1500         }
1501     }
1502     if (!usage)
1503     {
1504         /* If a particular location is specified, this should fail.  Otherwise
1505          * it should succeed with an empty usage.  (This is true on Win2k and
1506          * later, which we emulate.)
1507          */
1508         if (dwFlags)
1509         {
1510             SetLastError(CRYPT_E_NOT_FOUND);
1511             ret = FALSE;
1512         }
1513         else
1514             bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
1515     }
1516
1517     if (ret)
1518     {
1519         if (!pUsage)
1520             *pcbUsage = bytesNeeded;
1521         else if (*pcbUsage < bytesNeeded)
1522         {
1523             SetLastError(ERROR_MORE_DATA);
1524             *pcbUsage = bytesNeeded;
1525             ret = FALSE;
1526         }
1527         else
1528         {
1529             *pcbUsage = bytesNeeded;
1530             if (usage)
1531             {
1532                 DWORD i;
1533                 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
1534                  sizeof(CERT_ENHKEY_USAGE) +
1535                  usage->cUsageIdentifier * sizeof(LPSTR));
1536
1537                 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
1538                 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
1539                  sizeof(CERT_ENHKEY_USAGE));
1540                 for (i = 0; i < usage->cUsageIdentifier; i++)
1541                 {
1542                     pUsage->rgpszUsageIdentifier[i] = nextOID;
1543                     strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
1544                     nextOID += strlen(nextOID) + 1;
1545                 }
1546             }
1547             else
1548                 pUsage->cUsageIdentifier = 0;
1549         }
1550     }
1551     if (usage)
1552         LocalFree(usage);
1553     TRACE("returning %d\n", ret);
1554     return ret;
1555 }
1556
1557 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
1558  PCERT_ENHKEY_USAGE pUsage)
1559 {
1560     BOOL ret;
1561
1562     TRACE("(%p, %p)\n", pCertContext, pUsage);
1563
1564     if (pUsage)
1565     {
1566         CRYPT_DATA_BLOB blob = { 0, NULL };
1567
1568         ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
1569          pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
1570         if (ret)
1571         {
1572             ret = CertSetCertificateContextProperty(pCertContext,
1573              CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
1574             LocalFree(blob.pbData);
1575         }
1576     }
1577     else
1578         ret = CertSetCertificateContextProperty(pCertContext,
1579          CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
1580     return ret;
1581 }
1582
1583 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
1584  LPCSTR pszUsageIdentifier)
1585 {
1586     BOOL ret;
1587     DWORD size;
1588
1589     TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
1590
1591     if (CertGetEnhancedKeyUsage(pCertContext,
1592      CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
1593     {
1594         PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
1595
1596         if (usage)
1597         {
1598             ret = CertGetEnhancedKeyUsage(pCertContext,
1599              CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
1600             if (ret)
1601             {
1602                 PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
1603                  sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
1604
1605                 if (newUsage)
1606                 {
1607                     LPSTR nextOID;
1608                     DWORD i;
1609
1610                     newUsage->rgpszUsageIdentifier =
1611                      (LPSTR *)((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
1612                     nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier +
1613                      (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
1614                     for (i = 0; i < usage->cUsageIdentifier; i++)
1615                     {
1616                         newUsage->rgpszUsageIdentifier[i] = nextOID;
1617                         strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
1618                         nextOID += strlen(nextOID) + 1;
1619                     }
1620                     newUsage->rgpszUsageIdentifier[i] = nextOID;
1621                     strcpy(nextOID, pszUsageIdentifier);
1622                     newUsage->cUsageIdentifier = i + 1;
1623                     ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
1624                     CryptMemFree(newUsage);
1625                 }
1626             }
1627             CryptMemFree(usage);
1628         }
1629         else
1630             ret = FALSE;
1631     }
1632     else
1633     {
1634         PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
1635          sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
1636
1637         if (usage)
1638         {
1639             usage->rgpszUsageIdentifier =
1640              (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
1641             usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
1642              sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
1643             strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
1644             usage->cUsageIdentifier = 1;
1645             ret = CertSetEnhancedKeyUsage(pCertContext, usage);
1646             CryptMemFree(usage);
1647         }
1648         else
1649             ret = FALSE;
1650     }
1651     return ret;
1652 }
1653
1654 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
1655  LPCSTR pszUsageIdentifier)
1656 {
1657     BOOL ret;
1658     DWORD size;
1659     CERT_ENHKEY_USAGE usage;
1660
1661     TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
1662
1663     size = sizeof(usage);
1664     ret = CertGetEnhancedKeyUsage(pCertContext,
1665      CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
1666     if (!ret && GetLastError() == ERROR_MORE_DATA)
1667     {
1668         PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
1669
1670         if (pUsage)
1671         {
1672             ret = CertGetEnhancedKeyUsage(pCertContext,
1673              CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
1674             if (ret)
1675             {
1676                 if (pUsage->cUsageIdentifier)
1677                 {
1678                     DWORD i;
1679                     BOOL found = FALSE;
1680
1681                     for (i = 0; i < pUsage->cUsageIdentifier; i++)
1682                     {
1683                         if (!strcmp(pUsage->rgpszUsageIdentifier[i],
1684                          pszUsageIdentifier))
1685                             found = TRUE;
1686                         if (found && i < pUsage->cUsageIdentifier - 1)
1687                             pUsage->rgpszUsageIdentifier[i] =
1688                              pUsage->rgpszUsageIdentifier[i + 1];
1689                     }
1690                     pUsage->cUsageIdentifier--;
1691                     /* Remove the usage if it's empty */
1692                     if (pUsage->cUsageIdentifier)
1693                         ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
1694                     else
1695                         ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
1696                 }
1697             }
1698             CryptMemFree(pUsage);
1699         }
1700         else
1701             ret = FALSE;
1702     }
1703     else
1704     {
1705         /* it fit in an empty usage, therefore there's nothing to remove */
1706         ret = TRUE;
1707     }
1708     return ret;
1709 }
1710
1711 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
1712  int *cNumOIDSs, LPSTR *rghOIDs, DWORD *pcbOIDs)
1713 {
1714     BOOL ret = TRUE;
1715     DWORD i, cbOIDs = 0;
1716     BOOL allUsagesValid = TRUE;
1717     CERT_ENHKEY_USAGE validUsages = { 0, NULL };
1718
1719     TRACE("(%ld, %p, %p, %p, %ld)\n", cCerts, *rghCerts, cNumOIDSs,
1720      rghOIDs, *pcbOIDs);
1721
1722     for (i = 0; ret && i < cCerts; i++)
1723     {
1724         CERT_ENHKEY_USAGE usage;
1725         DWORD size = sizeof(usage);
1726
1727         ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
1728         /* Success is deliberately ignored: it implies all usages are valid */
1729         if (!ret && GetLastError() == ERROR_MORE_DATA)
1730         {
1731             PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
1732
1733             allUsagesValid = FALSE;
1734             if (pUsage)
1735             {
1736                 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
1737                 if (ret)
1738                 {
1739                     if (!validUsages.cUsageIdentifier)
1740                     {
1741                         DWORD j;
1742
1743                         cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
1744                         validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
1745                         for (j = 0; j < validUsages.cUsageIdentifier; j++)
1746                             cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
1747                              + 1;
1748                         validUsages.rgpszUsageIdentifier =
1749                          CryptMemAlloc(cbOIDs);
1750                         if (validUsages.rgpszUsageIdentifier)
1751                         {
1752                             LPSTR nextOID = (LPSTR)
1753                              ((LPBYTE)validUsages.rgpszUsageIdentifier +
1754                              validUsages.cUsageIdentifier * sizeof(LPSTR));
1755
1756                             for (j = 0; j < validUsages.cUsageIdentifier; j++)
1757                             {
1758                                 validUsages.rgpszUsageIdentifier[j] = nextOID;
1759                                 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
1760                                  pUsage->rgpszUsageIdentifier[j]);
1761                                 nextOID += lstrlenA(nextOID) + 1;
1762                             }
1763                         }
1764                         else
1765                             ret = FALSE;
1766                     }
1767                     else
1768                     {
1769                         DWORD j, k, validIndexes = 0, numRemoved = 0;
1770
1771                         /* Merge: build a bitmap of all the indexes of
1772                          * validUsages.rgpszUsageIdentifier that are in pUsage.
1773                          */
1774                         for (j = 0; j < pUsage->cUsageIdentifier; j++)
1775                         {
1776                             for (k = 0; k < validUsages.cUsageIdentifier; k++)
1777                             {
1778                                 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
1779                                  validUsages.rgpszUsageIdentifier[k]))
1780                                 {
1781                                     validIndexes |= (1 << k);
1782                                     break;
1783                                 }
1784                             }
1785                         }
1786                         /* Merge by removing from validUsages those that are
1787                          * not in the bitmap.
1788                          */
1789                         for (j = 0; j < validUsages.cUsageIdentifier; j++)
1790                         {
1791                             if (!(validIndexes & (1 << j)))
1792                             {
1793                                 if (j < validUsages.cUsageIdentifier - 1)
1794                                 {
1795                                     memcpy(&validUsages.rgpszUsageIdentifier[j],
1796                                      &validUsages.rgpszUsageIdentifier[j +
1797                                      numRemoved + 1],
1798                                      (validUsages.cUsageIdentifier - numRemoved
1799                                      - j - 1) * sizeof(LPSTR));
1800                                     cbOIDs -= lstrlenA(
1801                                      validUsages.rgpszUsageIdentifier[j]) + 1 +
1802                                      sizeof(LPSTR);
1803                                     numRemoved++;
1804                                 }
1805                                 else
1806                                     validUsages.cUsageIdentifier--;
1807                             }
1808                         }
1809                     }
1810                 }
1811                 CryptMemFree(pUsage);
1812             }
1813             else
1814                 ret = FALSE;
1815         }
1816     }
1817     if (ret)
1818     {
1819         if (allUsagesValid)
1820         {
1821             *cNumOIDSs = -1;
1822             *pcbOIDs = 0;
1823         }
1824         else
1825         {
1826             if (!rghOIDs || *pcbOIDs < cbOIDs)
1827             {
1828                 *pcbOIDs = cbOIDs;
1829                 SetLastError(ERROR_MORE_DATA);
1830                 ret = FALSE;
1831             }
1832             else
1833             {
1834                 LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
1835                  validUsages.cUsageIdentifier * sizeof(LPSTR));
1836
1837                 *pcbOIDs = cbOIDs;
1838                 *cNumOIDSs = validUsages.cUsageIdentifier;
1839                 for (i = 0; i < validUsages.cUsageIdentifier; i++)
1840                 {
1841                     rghOIDs[i] = nextOID;
1842                     lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
1843                     nextOID += lstrlenA(nextOID) + 1;
1844                 }
1845             }
1846         }
1847     }
1848     CryptMemFree(validUsages.rgpszUsageIdentifier);
1849     return ret;
1850 }
1851
1852 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
1853  * pInfo is NULL, from the attributes of hProv.
1854  */
1855 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
1856  PCRYPT_KEY_PROV_INFO pInfo, HCRYPTPROV hProv)
1857 {
1858     CRYPT_KEY_PROV_INFO info = { 0 };
1859     BOOL ret;
1860
1861     if (!pInfo)
1862     {
1863         DWORD size;
1864         int len;
1865
1866         ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
1867         if (ret)
1868         {
1869             LPSTR szContainer = CryptMemAlloc(size);
1870
1871             if (szContainer)
1872             {
1873                 ret = CryptGetProvParam(hProv, PP_CONTAINER,
1874                  (BYTE *)szContainer, &size, 0);
1875                 if (ret)
1876                 {
1877                     len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
1878                      NULL, 0);
1879                     if (len)
1880                     {
1881                         info.pwszContainerName = CryptMemAlloc(len *
1882                          sizeof(WCHAR));
1883                         len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
1884                          info.pwszContainerName, len);
1885                     }
1886                 }
1887                 CryptMemFree(szContainer);
1888             }
1889         }
1890         ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
1891         if (ret)
1892         {
1893             LPSTR szProvider = CryptMemAlloc(size);
1894
1895             if (szProvider)
1896             {
1897                 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
1898                  &size, 0);
1899                 if (ret)
1900                 {
1901                     len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
1902                      NULL, 0);
1903                     if (len)
1904                     {
1905                         info.pwszProvName = CryptMemAlloc(len *
1906                          sizeof(WCHAR));
1907                         len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
1908                          info.pwszProvName, len);
1909                     }
1910                 }
1911                 CryptMemFree(szProvider);
1912             }
1913         }
1914         size = sizeof(info.dwKeySpec);
1915         ret = CryptGetProvParam(hProv, PP_KEYSPEC, (LPBYTE)&info.dwKeySpec,
1916          &size, 0);
1917         if (!ret)
1918             info.dwKeySpec = AT_SIGNATURE;
1919         size = sizeof(info.dwProvType);
1920         ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
1921          &size, 0);
1922         if (!ret)
1923             info.dwProvType = PROV_RSA_FULL;
1924         pInfo = &info;
1925     }
1926
1927     ret = CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
1928      0, pInfo);
1929
1930     if (pInfo == &info)
1931     {
1932         CryptMemFree(info.pwszContainerName);
1933         CryptMemFree(info.pwszProvName);
1934     }
1935 }
1936
1937 /* Creates a signed certificate context from the unsigned, encoded certificate
1938  * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
1939  */
1940 static PCCERT_CONTEXT CRYPT_CreateSignedCert(PCRYPT_DER_BLOB blob,
1941  HCRYPTPROV hProv, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
1942 {
1943     PCCERT_CONTEXT context = NULL;
1944     BOOL ret;
1945     DWORD sigSize = 0;
1946
1947     ret = CryptSignCertificate(hProv, AT_SIGNATURE, X509_ASN_ENCODING,
1948      blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
1949     if (ret)
1950     {
1951         LPBYTE sig = CryptMemAlloc(sigSize);
1952
1953         ret = CryptSignCertificate(hProv, AT_SIGNATURE, X509_ASN_ENCODING,
1954          blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
1955         if (ret)
1956         {
1957             CERT_SIGNED_CONTENT_INFO signedInfo;
1958             BYTE *encodedSignedCert = NULL;
1959             DWORD encodedSignedCertSize = 0;
1960
1961             signedInfo.ToBeSigned.cbData = blob->cbData;
1962             signedInfo.ToBeSigned.pbData = blob->pbData;
1963             memcpy(&signedInfo.SignatureAlgorithm, sigAlgo,
1964              sizeof(signedInfo.SignatureAlgorithm));
1965             signedInfo.Signature.cbData = sigSize;
1966             signedInfo.Signature.pbData = sig;
1967             signedInfo.Signature.cUnusedBits = 0;
1968             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
1969              &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1970              (BYTE *)&encodedSignedCert, &encodedSignedCertSize);
1971             if (ret)
1972             {
1973                 context = CertCreateCertificateContext(X509_ASN_ENCODING,
1974                  encodedSignedCert, encodedSignedCertSize);
1975                 LocalFree(encodedSignedCert);
1976             }
1977         }
1978         CryptMemFree(sig);
1979     }
1980     return context;
1981 }
1982
1983 /* Copies data from the parameters into info, where:
1984  * pSerialNumber: The serial number.  Must not be NULL.
1985  * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
1986  *                     Must not be NULL
1987  * pSignatureAlgorithm: Optional.
1988  * pStartTime: The starting time of the certificate.  If NULL, the current
1989  *             system time is used.
1990  * pEndTime: The ending time of the certificate.  If NULL, one year past the
1991  *           starting time is used.
1992  * pubKey: The public key of the certificate.  Must not be NULL.
1993  * pExtensions: Extensions to be included with the certificate.  Optional.
1994  */
1995 static void CRYPT_MakeCertInfo(PCERT_INFO info, PCRYPT_DATA_BLOB pSerialNumber,
1996  PCERT_NAME_BLOB pSubjectIssuerBlob,
1997  PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
1998  PSYSTEMTIME pEndTime, PCERT_PUBLIC_KEY_INFO pubKey,
1999  PCERT_EXTENSIONS pExtensions)
2000 {
2001     static CHAR oid[] = szOID_RSA_SHA1RSA;
2002
2003     assert(info);
2004     assert(pSerialNumber);
2005     assert(pSubjectIssuerBlob);
2006     assert(pubKey);
2007
2008     info->dwVersion = CERT_V3;
2009     info->SerialNumber.cbData = pSerialNumber->cbData;
2010     info->SerialNumber.pbData = pSerialNumber->pbData;
2011     if (pSignatureAlgorithm)
2012         memcpy(&info->SignatureAlgorithm, pSignatureAlgorithm,
2013          sizeof(info->SignatureAlgorithm));
2014     else
2015     {
2016         info->SignatureAlgorithm.pszObjId = oid;
2017         info->SignatureAlgorithm.Parameters.cbData = 0;
2018         info->SignatureAlgorithm.Parameters.pbData = NULL;
2019     }
2020     info->Issuer.cbData = pSubjectIssuerBlob->cbData;
2021     info->Issuer.pbData = pSubjectIssuerBlob->pbData;
2022     if (pStartTime)
2023         SystemTimeToFileTime(pStartTime, &info->NotBefore);
2024     else
2025         GetSystemTimeAsFileTime(&info->NotBefore);
2026     if (pEndTime)
2027         SystemTimeToFileTime(pEndTime, &info->NotAfter);
2028     else
2029     {
2030         SYSTEMTIME endTime;
2031
2032         if (FileTimeToSystemTime(&info->NotBefore, &endTime))
2033         {
2034             endTime.wYear++;
2035             SystemTimeToFileTime(&endTime, &info->NotAfter);
2036         }
2037     }
2038     info->Subject.cbData = pSubjectIssuerBlob->cbData;
2039     info->Subject.pbData = pSubjectIssuerBlob->pbData;
2040     memcpy(&info->SubjectPublicKeyInfo, pubKey,
2041      sizeof(info->SubjectPublicKeyInfo));
2042     if (pExtensions)
2043     {
2044         info->cExtension = pExtensions->cExtension;
2045         info->rgExtension = pExtensions->rgExtension;
2046     }
2047     else
2048     {
2049         info->cExtension = 0;
2050         info->rgExtension = NULL;
2051     }
2052 }
2053  
2054 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
2055 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
2056 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
2057
2058 static HCRYPTPROV CRYPT_CreateKeyProv(void)
2059 {
2060     HCRYPTPROV hProv = 0;
2061     HMODULE rpcrt = LoadLibraryA("rpcrt4");
2062
2063     if (rpcrt)
2064     {
2065         UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
2066          "UuidCreate");
2067         UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
2068          "UuidToStringA");
2069         RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
2070          rpcrt, "RpcStringFreeA");
2071
2072         if (uuidCreate && uuidToString && rpcStringFree)
2073         {
2074             UUID uuid;
2075             RPC_STATUS status = uuidCreate(&uuid);
2076
2077             if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
2078             {
2079                 unsigned char *uuidStr;
2080
2081                 status = uuidToString(&uuid, &uuidStr);
2082                 if (status == RPC_S_OK)
2083                 {
2084                     BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
2085                      MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
2086
2087                     if (ret)
2088                     {
2089                         HCRYPTKEY key;
2090
2091                         ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
2092                         if (ret)
2093                             CryptDestroyKey(key);
2094                     }
2095                     rpcStringFree(&uuidStr);
2096                 }
2097             }
2098         }
2099         FreeLibrary(rpcrt);
2100     }
2101     return hProv;
2102 }
2103
2104 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV hProv,
2105  PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
2106  PCRYPT_KEY_PROV_INFO pKeyProvInfo,
2107  PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
2108  PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
2109 {
2110     PCCERT_CONTEXT context = NULL;
2111     BOOL ret, releaseContext = FALSE;
2112     PCERT_PUBLIC_KEY_INFO pubKey = NULL;
2113     DWORD pubKeySize = 0;
2114
2115     TRACE("(0x%08lx, %p, %08lx, %p, %p, %p, %p, %p)\n", hProv,
2116      pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
2117      pExtensions, pExtensions);
2118
2119     if (!hProv)
2120     {
2121         hProv = CRYPT_CreateKeyProv();
2122         releaseContext = TRUE;
2123     }
2124
2125     CryptExportPublicKeyInfo(hProv, AT_SIGNATURE, X509_ASN_ENCODING, NULL,
2126      &pubKeySize);
2127     pubKey = CryptMemAlloc(pubKeySize);
2128     if (pubKey)
2129     {
2130         ret = CryptExportPublicKeyInfo(hProv, AT_SIGNATURE, X509_ASN_ENCODING,
2131          pubKey, &pubKeySize);
2132         if (ret)
2133         {
2134             CERT_INFO info = { 0 };
2135             CRYPT_DER_BLOB blob = { 0, NULL };
2136             BYTE serial[16];
2137             CRYPT_DATA_BLOB serialBlob = { sizeof(serial), serial };
2138
2139             CryptGenRandom(hProv, sizeof(serial), serial);
2140             CRYPT_MakeCertInfo(&info, &serialBlob, pSubjectIssuerBlob,
2141              pSignatureAlgorithm, pStartTime, pEndTime, pubKey, pExtensions);
2142             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
2143              &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, (BYTE *)&blob.pbData,
2144              &blob.cbData);
2145             if (ret)
2146             {
2147                 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
2148                     context = CRYPT_CreateSignedCert(&blob, hProv,
2149                      &info.SignatureAlgorithm);
2150                 else
2151                     context = CertCreateCertificateContext(X509_ASN_ENCODING,
2152                      blob.pbData, blob.cbData);
2153                 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
2154                     CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
2155                 LocalFree(blob.pbData);
2156             }
2157         }
2158         CryptMemFree(pubKey);
2159     }
2160     if (releaseContext)
2161         CryptReleaseContext(hProv, 0);
2162     return context;
2163 }