mshtml: Added an explicit CDECL attribute to imported functions.
[wine] / dlls / wintrust / softpub.c
1 /*
2  * Copyright 2007 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 #include <stdarg.h>
19
20 #define NONAMELESSUNION
21
22 #include "windef.h"
23 #include "winbase.h"
24 #include "wintrust.h"
25 #include "mssip.h"
26 #include "softpub.h"
27 #include "wine/debug.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(wintrust);
30
31 HRESULT WINAPI SoftpubDefCertInit(CRYPT_PROVIDER_DATA *data)
32 {
33     HRESULT ret = S_FALSE;
34
35     TRACE("(%p)\n", data);
36
37     if (data->padwTrustStepErrors &&
38      !data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_WVTINIT])
39         ret = S_OK;
40     TRACE("returning %08x\n", ret);
41     return ret;
42 }
43
44 HRESULT WINAPI SoftpubInitialize(CRYPT_PROVIDER_DATA *data)
45 {
46     HRESULT ret = S_FALSE;
47
48     TRACE("(%p)\n", data);
49
50     if (data->padwTrustStepErrors &&
51      !data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_WVTINIT])
52         ret = S_OK;
53     TRACE("returning %08x\n", ret);
54     return ret;
55 }
56
57 HRESULT WINAPI DriverInitializePolicy(CRYPT_PROVIDER_DATA *data)
58 {
59     FIXME("stub\n");
60     return S_OK;
61 }
62
63 HRESULT WINAPI DriverCleanupPolicy(CRYPT_PROVIDER_DATA *data)
64 {
65     FIXME("stub\n");
66     return S_OK;
67 }
68
69 HRESULT WINAPI DriverFinalPolicy(CRYPT_PROVIDER_DATA *data)
70 {
71     FIXME("stub\n");
72     return S_OK;
73 }
74
75 /* Assumes data->pWintrustData->u.pFile exists.  Makes sure a file handle is
76  * open for the file.
77  */
78 static DWORD SOFTPUB_OpenFile(CRYPT_PROVIDER_DATA *data)
79 {
80     DWORD err = ERROR_SUCCESS;
81
82     /* PSDK implies that all values should be initialized to NULL, so callers
83      * typically have hFile as NULL rather than INVALID_HANDLE_VALUE.  Check
84      * for both.
85      */
86     if (!data->pWintrustData->u.pFile->hFile ||
87      data->pWintrustData->u.pFile->hFile == INVALID_HANDLE_VALUE)
88     {
89         data->pWintrustData->u.pFile->hFile =
90             CreateFileW(data->pWintrustData->u.pFile->pcwszFilePath, GENERIC_READ,
91           FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
92         if (data->pWintrustData->u.pFile->hFile != INVALID_HANDLE_VALUE)
93             data->fOpenedFile = TRUE;
94         else
95             err = GetLastError();
96     }
97     if (!err)
98         GetFileTime(data->pWintrustData->u.pFile->hFile, &data->sftSystemTime,
99          NULL, NULL);
100     TRACE("returning %d\n", err);
101     return err;
102 }
103
104 /* Assumes data->pWintrustData->u.pFile exists.  Sets data->pPDSip->gSubject to
105  * the file's subject GUID.
106  */
107 static DWORD SOFTPUB_GetFileSubject(CRYPT_PROVIDER_DATA *data)
108 {
109     DWORD err = ERROR_SUCCESS;
110
111     if (!WVT_ISINSTRUCT(WINTRUST_FILE_INFO,
112      data->pWintrustData->u.pFile->cbStruct, pgKnownSubject) ||
113      !data->pWintrustData->u.pFile->pgKnownSubject)
114     {
115         if (!CryptSIPRetrieveSubjectGuid(
116          data->pWintrustData->u.pFile->pcwszFilePath,
117          data->pWintrustData->u.pFile->hFile,
118          &data->u.pPDSip->gSubject))
119             err = GetLastError();
120     }
121     else
122         data->u.pPDSip->gSubject = *data->pWintrustData->u.pFile->pgKnownSubject;
123     TRACE("returning %d\n", err);
124     return err;
125 }
126
127 /* Assumes data->u.pPDSip exists, and its gSubject member set.
128  * Allocates data->u.pPDSip->pSip and loads it, if possible.
129  */
130 static DWORD SOFTPUB_GetSIP(CRYPT_PROVIDER_DATA *data)
131 {
132     DWORD err = ERROR_SUCCESS;
133
134     data->u.pPDSip->pSip = data->psPfns->pfnAlloc(sizeof(SIP_DISPATCH_INFO));
135     if (data->u.pPDSip->pSip)
136     {
137         if (!CryptSIPLoad(&data->u.pPDSip->gSubject, 0, data->u.pPDSip->pSip))
138             err = GetLastError();
139     }
140     else
141         err = ERROR_OUTOFMEMORY;
142     TRACE("returning %d\n", err);
143     return err;
144 }
145
146 /* Assumes data->u.pPDSip has been loaded, and data->u.pPDSip->pSip allocated.
147  * Calls data->u.pPDSip->pSip->pfGet to construct data->hMsg.
148  */
149 static DWORD SOFTPUB_GetMessageFromFile(CRYPT_PROVIDER_DATA *data, HANDLE file,
150  LPCWSTR filePath)
151 {
152     DWORD err = ERROR_SUCCESS;
153     BOOL ret;
154     LPBYTE buf = NULL;
155     DWORD size = 0;
156
157     data->u.pPDSip->psSipSubjectInfo =
158      data->psPfns->pfnAlloc(sizeof(SIP_SUBJECTINFO));
159     if (!data->u.pPDSip->psSipSubjectInfo)
160         return ERROR_OUTOFMEMORY;
161
162     data->u.pPDSip->psSipSubjectInfo->cbSize = sizeof(SIP_SUBJECTINFO);
163     data->u.pPDSip->psSipSubjectInfo->pgSubjectType = &data->u.pPDSip->gSubject;
164     data->u.pPDSip->psSipSubjectInfo->hFile = file;
165     data->u.pPDSip->psSipSubjectInfo->pwsFileName = filePath;
166     data->u.pPDSip->psSipSubjectInfo->hProv = data->hProv;
167     ret = data->u.pPDSip->pSip->pfGet(data->u.pPDSip->psSipSubjectInfo,
168      &data->dwEncoding, 0, &size, 0);
169     if (!ret)
170         return TRUST_E_NOSIGNATURE;
171
172     buf = data->psPfns->pfnAlloc(size);
173     if (!buf)
174         return ERROR_OUTOFMEMORY;
175
176     ret = data->u.pPDSip->pSip->pfGet(data->u.pPDSip->psSipSubjectInfo,
177      &data->dwEncoding, 0, &size, buf);
178     if (ret)
179     {
180         data->hMsg = CryptMsgOpenToDecode(data->dwEncoding, 0, 0, data->hProv,
181          NULL, NULL);
182         if (data->hMsg)
183         {
184             ret = CryptMsgUpdate(data->hMsg, buf, size, TRUE);
185             if (!ret)
186                 err = GetLastError();
187         }
188     }
189     else
190         err = GetLastError();
191
192     data->psPfns->pfnFree(buf);
193     TRACE("returning %d\n", err);
194     return err;
195 }
196
197 static DWORD SOFTPUB_CreateStoreFromMessage(CRYPT_PROVIDER_DATA *data)
198 {
199     DWORD err = ERROR_SUCCESS;
200     HCERTSTORE store;
201
202     store = CertOpenStore(CERT_STORE_PROV_MSG, data->dwEncoding,
203      data->hProv, CERT_STORE_NO_CRYPT_RELEASE_FLAG, data->hMsg);
204     if (store)
205     {
206         if (!data->psPfns->pfnAddStore2Chain(data, store))
207             err = GetLastError();
208         CertCloseStore(store, 0);
209     }
210     else
211         err = GetLastError();
212     TRACE("returning %d\n", err);
213     return err;
214 }
215
216 static DWORD SOFTPUB_DecodeInnerContent(CRYPT_PROVIDER_DATA *data)
217 {
218     BOOL ret;
219     DWORD size, err = ERROR_SUCCESS;
220     LPSTR oid = NULL;
221     LPBYTE buf = NULL;
222
223     ret = CryptMsgGetParam(data->hMsg, CMSG_INNER_CONTENT_TYPE_PARAM, 0, NULL,
224      &size);
225     if (!ret)
226     {
227         err = GetLastError();
228         goto error;
229     }
230     oid = data->psPfns->pfnAlloc(size);
231     if (!oid)
232     {
233         err = ERROR_OUTOFMEMORY;
234         goto error;
235     }
236     ret = CryptMsgGetParam(data->hMsg, CMSG_INNER_CONTENT_TYPE_PARAM, 0, oid,
237      &size);
238     if (!ret)
239     {
240         err = GetLastError();
241         goto error;
242     }
243     ret = CryptMsgGetParam(data->hMsg, CMSG_CONTENT_PARAM, 0, NULL, &size);
244     if (!ret)
245     {
246         err = GetLastError();
247         goto error;
248     }
249     buf = data->psPfns->pfnAlloc(size);
250     if (!buf)
251     {
252         err = ERROR_OUTOFMEMORY;
253         goto error;
254     }
255     ret = CryptMsgGetParam(data->hMsg, CMSG_CONTENT_PARAM, 0, buf, &size);
256     if (!ret)
257     {
258         err = GetLastError();
259         goto error;
260     }
261     ret = CryptDecodeObject(data->dwEncoding, oid, buf, size, 0, NULL, &size);
262     if (!ret)
263     {
264         err = GetLastError();
265         goto error;
266     }
267     data->u.pPDSip->psIndirectData = data->psPfns->pfnAlloc(size);
268     if (!data->u.pPDSip->psIndirectData)
269     {
270         err = ERROR_OUTOFMEMORY;
271         goto error;
272     }
273     ret = CryptDecodeObject(data->dwEncoding, oid, buf, size, 0,
274      data->u.pPDSip->psIndirectData, &size);
275     if (!ret)
276         err = GetLastError();
277
278 error:
279     TRACE("returning %d\n", err);
280     data->psPfns->pfnFree(oid);
281     data->psPfns->pfnFree(buf);
282     return err;
283 }
284
285 static DWORD SOFTPUB_LoadCertMessage(CRYPT_PROVIDER_DATA *data)
286 {
287     DWORD err = ERROR_SUCCESS;
288
289     if (data->pWintrustData->u.pCert &&
290      WVT_IS_CBSTRUCT_GT_MEMBEROFFSET(WINTRUST_CERT_INFO,
291      data->pWintrustData->u.pCert->cbStruct, psCertContext))
292     {
293         if (data->psPfns)
294         {
295             CRYPT_PROVIDER_SGNR signer = { sizeof(signer), { 0 } };
296             DWORD i;
297             BOOL ret;
298
299             /* Add a signer with nothing but the time to verify, so we can
300              * add a cert to it
301              */
302             if (WVT_ISINSTRUCT(WINTRUST_CERT_INFO,
303              data->pWintrustData->u.pCert->cbStruct, psftVerifyAsOf) &&
304              data->pWintrustData->u.pCert->psftVerifyAsOf)
305                 data->sftSystemTime = signer.sftVerifyAsOf;
306             else
307             {
308                 SYSTEMTIME sysTime;
309
310                 GetSystemTime(&sysTime);
311                 SystemTimeToFileTime(&sysTime, &signer.sftVerifyAsOf);
312             }
313             ret = data->psPfns->pfnAddSgnr2Chain(data, FALSE, 0, &signer);
314             if (ret)
315             {
316                 ret = data->psPfns->pfnAddCert2Chain(data, 0, FALSE, 0,
317                  data->pWintrustData->u.pCert->psCertContext);
318                 if (WVT_ISINSTRUCT(WINTRUST_CERT_INFO,
319                  data->pWintrustData->u.pCert->cbStruct, pahStores))
320                         for (i = 0;
321                          ret && i < data->pWintrustData->u.pCert->chStores; i++)
322                             ret = data->psPfns->pfnAddStore2Chain(data,
323                              data->pWintrustData->u.pCert->pahStores[i]);
324             }
325             if (!ret)
326                 err = GetLastError();
327         }
328     }
329     else
330         err = ERROR_INVALID_PARAMETER;
331     return err;
332 }
333
334 static DWORD SOFTPUB_LoadFileMessage(CRYPT_PROVIDER_DATA *data)
335 {
336     DWORD err = ERROR_SUCCESS;
337
338     if (!data->pWintrustData->u.pFile)
339     {
340         err = ERROR_INVALID_PARAMETER;
341         goto error;
342     }
343     err = SOFTPUB_OpenFile(data);
344     if (err)
345         goto error;
346     err = SOFTPUB_GetFileSubject(data);
347     if (err)
348         goto error;
349     err = SOFTPUB_GetSIP(data);
350     if (err)
351         goto error;
352     err = SOFTPUB_GetMessageFromFile(data, data->pWintrustData->u.pFile->hFile,
353      data->pWintrustData->u.pFile->pcwszFilePath);
354     if (err)
355         goto error;
356     err = SOFTPUB_CreateStoreFromMessage(data);
357     if (err)
358         goto error;
359     err = SOFTPUB_DecodeInnerContent(data);
360
361 error:
362     if (err && data->fOpenedFile && data->pWintrustData->u.pFile)
363     {
364         /* The caller won't expect the file to be open on failure, so close it.
365          */
366         CloseHandle(data->pWintrustData->u.pFile->hFile);
367         data->pWintrustData->u.pFile->hFile = INVALID_HANDLE_VALUE;
368         data->fOpenedFile = FALSE;
369     }
370     return err;
371 }
372
373 static DWORD SOFTPUB_LoadCatalogMessage(CRYPT_PROVIDER_DATA *data)
374 {
375     DWORD err;
376     HANDLE catalog = INVALID_HANDLE_VALUE;
377
378     if (!data->pWintrustData->u.pCatalog)
379     {
380         SetLastError(ERROR_INVALID_PARAMETER);
381         return FALSE;
382     }
383     catalog = CreateFileW(data->pWintrustData->u.pCatalog->pcwszCatalogFilePath,
384      GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
385      NULL);
386     if (catalog == INVALID_HANDLE_VALUE)
387         return GetLastError();
388     if (!CryptSIPRetrieveSubjectGuid(
389      data->pWintrustData->u.pCatalog->pcwszCatalogFilePath, catalog,
390      &data->u.pPDSip->gSubject))
391     {
392         err = GetLastError();
393         goto error;
394     }
395     err = SOFTPUB_GetSIP(data);
396     if (err)
397         goto error;
398     err = SOFTPUB_GetMessageFromFile(data, catalog,
399      data->pWintrustData->u.pCatalog->pcwszCatalogFilePath);
400     if (err)
401         goto error;
402     err = SOFTPUB_CreateStoreFromMessage(data);
403     if (err)
404         goto error;
405     err = SOFTPUB_DecodeInnerContent(data);
406     /* FIXME: this loads the catalog file, but doesn't validate the member. */
407 error:
408     CloseHandle(catalog);
409     return err;
410 }
411
412 HRESULT WINAPI SoftpubLoadMessage(CRYPT_PROVIDER_DATA *data)
413 {
414     DWORD err = ERROR_SUCCESS;
415
416     TRACE("(%p)\n", data);
417
418     if (!data->padwTrustStepErrors)
419         return S_FALSE;
420
421     switch (data->pWintrustData->dwUnionChoice)
422     {
423     case WTD_CHOICE_CERT:
424         err = SOFTPUB_LoadCertMessage(data);
425         break;
426     case WTD_CHOICE_FILE:
427         err = SOFTPUB_LoadFileMessage(data);
428         break;
429     case WTD_CHOICE_CATALOG:
430         err = SOFTPUB_LoadCatalogMessage(data);
431         break;
432     default:
433         FIXME("unimplemented for %d\n", data->pWintrustData->dwUnionChoice);
434         err = ERROR_INVALID_PARAMETER;
435     }
436
437     if (err)
438         data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_OBJPROV] = err;
439     TRACE("returning %d (%08x)\n", !err ? S_OK : S_FALSE,
440      data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_OBJPROV]);
441     return !err ? S_OK : S_FALSE;
442 }
443
444 static CMSG_SIGNER_INFO *WINTRUST_GetSigner(CRYPT_PROVIDER_DATA *data,
445  DWORD signerIdx)
446 {
447     BOOL ret;
448     CMSG_SIGNER_INFO *signerInfo = NULL;
449     DWORD size;
450
451     ret = CryptMsgGetParam(data->hMsg, CMSG_SIGNER_INFO_PARAM, signerIdx,
452      NULL, &size);
453     if (ret)
454     {
455         signerInfo = data->psPfns->pfnAlloc(size);
456         if (signerInfo)
457         {
458             ret = CryptMsgGetParam(data->hMsg, CMSG_SIGNER_INFO_PARAM,
459              signerIdx, signerInfo, &size);
460             if (!ret)
461             {
462                 data->psPfns->pfnFree(signerInfo);
463                 signerInfo = NULL;
464             }
465         }
466         else
467             SetLastError(ERROR_OUTOFMEMORY);
468     }
469     return signerInfo;
470 }
471
472 static DWORD WINTRUST_SaveSigner(CRYPT_PROVIDER_DATA *data, DWORD signerIdx)
473 {
474     DWORD err;
475     CMSG_SIGNER_INFO *signerInfo = WINTRUST_GetSigner(data, signerIdx);
476
477     if (signerInfo)
478     {
479         CRYPT_PROVIDER_SGNR sgnr = { sizeof(sgnr), { 0 } };
480
481         sgnr.psSigner = signerInfo;
482         sgnr.sftVerifyAsOf = data->sftSystemTime;
483         if (!data->psPfns->pfnAddSgnr2Chain(data, FALSE, signerIdx, &sgnr))
484             err = GetLastError();
485         else
486             err = ERROR_SUCCESS;
487     }
488     else
489         err = GetLastError();
490     return err;
491 }
492
493 static CERT_INFO *WINTRUST_GetSignerCertInfo(CRYPT_PROVIDER_DATA *data,
494  DWORD signerIdx)
495 {
496     BOOL ret;
497     CERT_INFO *certInfo = NULL;
498     DWORD size;
499
500     ret = CryptMsgGetParam(data->hMsg, CMSG_SIGNER_CERT_INFO_PARAM, signerIdx,
501      NULL, &size);
502     if (ret)
503     {
504         certInfo = data->psPfns->pfnAlloc(size);
505         if (certInfo)
506         {
507             ret = CryptMsgGetParam(data->hMsg, CMSG_SIGNER_CERT_INFO_PARAM,
508              signerIdx, certInfo, &size);
509             if (!ret)
510             {
511                 data->psPfns->pfnFree(certInfo);
512                 certInfo = NULL;
513             }
514         }
515         else
516             SetLastError(ERROR_OUTOFMEMORY);
517     }
518     return certInfo;
519 }
520
521 static DWORD WINTRUST_VerifySigner(CRYPT_PROVIDER_DATA *data, DWORD signerIdx)
522 {
523     DWORD err;
524     CERT_INFO *certInfo = WINTRUST_GetSignerCertInfo(data, signerIdx);
525
526     if (certInfo)
527     {
528         PCCERT_CONTEXT subject = CertGetSubjectCertificateFromStore(
529          data->pahStores[0], data->dwEncoding, certInfo);
530
531         if (subject)
532         {
533             CMSG_CTRL_VERIFY_SIGNATURE_EX_PARA para = { sizeof(para), 0,
534              signerIdx, CMSG_VERIFY_SIGNER_CERT, (LPVOID)subject };
535
536             if (!CryptMsgControl(data->hMsg, 0, CMSG_CTRL_VERIFY_SIGNATURE_EX,
537              &para))
538                 err = TRUST_E_CERT_SIGNATURE;
539             else
540             {
541                 data->psPfns->pfnAddCert2Chain(data, signerIdx, FALSE, 0,
542                  subject);
543                 err = ERROR_SUCCESS;
544             }
545             CertFreeCertificateContext(subject);
546         }
547         else
548             err = TRUST_E_NO_SIGNER_CERT;
549         data->psPfns->pfnFree(certInfo);
550     }
551     else
552         err = GetLastError();
553     return err;
554 }
555
556 HRESULT WINAPI SoftpubLoadSignature(CRYPT_PROVIDER_DATA *data)
557 {
558     DWORD err;
559
560     TRACE("(%p)\n", data);
561
562     if (!data->padwTrustStepErrors)
563         return S_FALSE;
564
565     if (data->hMsg)
566     {
567         DWORD signerCount, size;
568
569         size = sizeof(signerCount);
570         if (CryptMsgGetParam(data->hMsg, CMSG_SIGNER_COUNT_PARAM, 0,
571          &signerCount, &size))
572         {
573             DWORD i;
574
575             err = ERROR_SUCCESS;
576             for (i = 0; !err && i < signerCount; i++)
577             {
578                 if (!(err = WINTRUST_SaveSigner(data, i)))
579                     err = WINTRUST_VerifySigner(data, i);
580             }
581         }
582         else
583             err = TRUST_E_NOSIGNATURE;
584     }
585     else
586         err = ERROR_SUCCESS;
587     if (err)
588         data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_SIGPROV] = err;
589     return !err ? S_OK : S_FALSE;
590 }
591
592 static DWORD WINTRUST_TrustStatusToConfidence(DWORD errorStatus)
593 {
594     DWORD confidence = 0;
595
596     confidence = 0;
597     if (!(errorStatus & CERT_TRUST_IS_NOT_SIGNATURE_VALID))
598         confidence |= CERT_CONFIDENCE_SIG;
599     if (!(errorStatus & CERT_TRUST_IS_NOT_TIME_VALID))
600         confidence |= CERT_CONFIDENCE_TIME;
601     if (!(errorStatus & CERT_TRUST_IS_NOT_TIME_NESTED))
602         confidence |= CERT_CONFIDENCE_TIMENEST;
603     return confidence;
604 }
605
606 BOOL WINAPI SoftpubCheckCert(CRYPT_PROVIDER_DATA *data, DWORD idxSigner,
607  BOOL fCounterSignerChain, DWORD idxCounterSigner)
608 {
609     BOOL ret;
610
611     TRACE("(%p, %d, %d, %d)\n", data, idxSigner, fCounterSignerChain,
612      idxCounterSigner);
613
614     if (fCounterSignerChain)
615     {
616         FIXME("unimplemented for counter signers\n");
617         ret = FALSE;
618     }
619     else
620     {
621         PCERT_SIMPLE_CHAIN simpleChain =
622          data->pasSigners[idxSigner].pChainContext->rgpChain[0];
623         DWORD i;
624
625         ret = TRUE;
626         for (i = 0; i < simpleChain->cElement; i++)
627         {
628             /* Set confidence */
629             data->pasSigners[idxSigner].pasCertChain[i].dwConfidence =
630              WINTRUST_TrustStatusToConfidence(
631              simpleChain->rgpElement[i]->TrustStatus.dwErrorStatus);
632             /* Set additional flags */
633             if (!(simpleChain->rgpElement[i]->TrustStatus.dwErrorStatus &
634              CERT_TRUST_IS_UNTRUSTED_ROOT))
635                 data->pasSigners[idxSigner].pasCertChain[i].fTrustedRoot = TRUE;
636             if (simpleChain->rgpElement[i]->TrustStatus.dwInfoStatus &
637              CERT_TRUST_IS_SELF_SIGNED)
638                 data->pasSigners[idxSigner].pasCertChain[i].fSelfSigned = TRUE;
639             if (simpleChain->rgpElement[i]->TrustStatus.dwErrorStatus &
640              CERT_TRUST_IS_CYCLIC)
641                 data->pasSigners[idxSigner].pasCertChain[i].fIsCyclic = TRUE;
642         }
643     }
644     return ret;
645 }
646
647 static DWORD WINTRUST_TrustStatusToError(DWORD errorStatus)
648 {
649     DWORD error;
650
651     if (errorStatus & CERT_TRUST_IS_NOT_SIGNATURE_VALID)
652         error = TRUST_E_CERT_SIGNATURE;
653     else if (errorStatus & CERT_TRUST_IS_UNTRUSTED_ROOT)
654         error = CERT_E_UNTRUSTEDROOT;
655     else if (errorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
656         error = CERT_E_EXPIRED;
657     else if (errorStatus & CERT_TRUST_IS_NOT_TIME_NESTED)
658         error = CERT_E_VALIDITYPERIODNESTING;
659     else if (errorStatus & CERT_TRUST_IS_REVOKED)
660         error = CERT_E_REVOKED;
661     else if (errorStatus & CERT_TRUST_IS_OFFLINE_REVOCATION ||
662      errorStatus & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
663         error = CERT_E_REVOCATION_FAILURE;
664     else if (errorStatus & CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
665         error = CERT_E_WRONG_USAGE;
666     else if (errorStatus & CERT_TRUST_IS_CYCLIC)
667         error = CERT_E_CHAINING;
668     else if (errorStatus & CERT_TRUST_INVALID_EXTENSION)
669         error = CERT_E_CRITICAL;
670     else if (errorStatus & CERT_TRUST_INVALID_POLICY_CONSTRAINTS)
671         error = CERT_E_INVALID_POLICY;
672     else if (errorStatus & CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
673         error = TRUST_E_BASIC_CONSTRAINTS;
674     else if (errorStatus & CERT_TRUST_INVALID_NAME_CONSTRAINTS ||
675      errorStatus & CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT ||
676      errorStatus & CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT ||
677      errorStatus & CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT ||
678      errorStatus & CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT)
679         error = CERT_E_INVALID_NAME;
680     else if (errorStatus & CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY)
681         error = CERT_E_INVALID_POLICY;
682     else if (errorStatus)
683     {
684         FIXME("unknown error status %08x\n", errorStatus);
685         error = TRUST_E_SYSTEM_ERROR;
686     }
687     else
688         error = S_OK;
689     return error;
690 }
691
692 static DWORD WINTRUST_CopyChain(CRYPT_PROVIDER_DATA *data, DWORD signerIdx)
693 {
694     DWORD err, i;
695     PCERT_SIMPLE_CHAIN simpleChain =
696      data->pasSigners[signerIdx].pChainContext->rgpChain[0];
697
698     data->pasSigners[signerIdx].pasCertChain[0].dwConfidence =
699      WINTRUST_TrustStatusToConfidence(
700      simpleChain->rgpElement[0]->TrustStatus.dwErrorStatus);
701     data->pasSigners[signerIdx].pasCertChain[0].pChainElement =
702      simpleChain->rgpElement[0];
703     err = ERROR_SUCCESS;
704     for (i = 1; !err && i < simpleChain->cElement; i++)
705     {
706         if (data->psPfns->pfnAddCert2Chain(data, signerIdx, FALSE, 0,
707          simpleChain->rgpElement[i]->pCertContext))
708         {
709             data->pasSigners[signerIdx].pasCertChain[i].pChainElement =
710              simpleChain->rgpElement[i];
711             data->pasSigners[signerIdx].pasCertChain[i].dwConfidence =
712              WINTRUST_TrustStatusToConfidence(
713              simpleChain->rgpElement[i]->TrustStatus.dwErrorStatus);
714         }
715         else
716             err = GetLastError();
717     }
718     data->pasSigners[signerIdx].pasCertChain[simpleChain->cElement - 1].dwError
719      = WINTRUST_TrustStatusToError(
720      simpleChain->rgpElement[simpleChain->cElement - 1]->
721      TrustStatus.dwErrorStatus);
722     return err;
723 }
724
725 static void WINTRUST_CreateChainPolicyCreateInfo(
726  const CRYPT_PROVIDER_DATA *data, PWTD_GENERIC_CHAIN_POLICY_CREATE_INFO info,
727  PCERT_CHAIN_PARA chainPara)
728 {
729     chainPara->cbSize = sizeof(CERT_CHAIN_PARA);
730     if (data->pRequestUsage)
731         chainPara->RequestedUsage = *data->pRequestUsage;
732     else
733     {
734         chainPara->RequestedUsage.dwType = 0;
735         chainPara->RequestedUsage.Usage.cUsageIdentifier = 0;
736     }
737     info->u.cbSize = sizeof(WTD_GENERIC_CHAIN_POLICY_CREATE_INFO);
738     info->hChainEngine = NULL;
739     info->pChainPara = chainPara;
740     if (data->dwProvFlags & CPD_REVOCATION_CHECK_END_CERT)
741         info->dwFlags = CERT_CHAIN_REVOCATION_CHECK_END_CERT;
742     else if (data->dwProvFlags & CPD_REVOCATION_CHECK_CHAIN)
743         info->dwFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN;
744     else if (data->dwProvFlags & CPD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT)
745         info->dwFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
746     else
747         info->dwFlags = 0;
748     info->pvReserved = NULL;
749 }
750
751 static DWORD WINTRUST_CreateChainForSigner(CRYPT_PROVIDER_DATA *data,
752  DWORD signer, PWTD_GENERIC_CHAIN_POLICY_CREATE_INFO createInfo,
753  PCERT_CHAIN_PARA chainPara)
754 {
755     DWORD err = ERROR_SUCCESS;
756     HCERTSTORE store = NULL;
757
758     if (data->chStores)
759     {
760         store = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
761          CERT_STORE_CREATE_NEW_FLAG, NULL);
762         if (store)
763         {
764             DWORD i;
765
766             for (i = 0; i < data->chStores; i++)
767                 CertAddStoreToCollection(store, data->pahStores[i], 0, 0);
768         }
769         else
770             err = GetLastError();
771     }
772     if (!err)
773     {
774         /* Expect the end certificate for each signer to be the only cert in
775          * the chain:
776          */
777         if (data->pasSigners[signer].csCertChain)
778         {
779             BOOL ret;
780
781             /* Create a certificate chain for each signer */
782             ret = CertGetCertificateChain(createInfo->hChainEngine,
783              data->pasSigners[signer].pasCertChain[0].pCert,
784              &data->pasSigners[signer].sftVerifyAsOf, store,
785              chainPara, createInfo->dwFlags, createInfo->pvReserved,
786              &data->pasSigners[signer].pChainContext);
787             if (ret)
788             {
789                 if (data->pasSigners[signer].pChainContext->cChain != 1)
790                 {
791                     FIXME("unimplemented for more than 1 simple chain\n");
792                     err = E_NOTIMPL;
793                 }
794                 else
795                 {
796                     if (!(err = WINTRUST_CopyChain(data, signer)))
797                     {
798                         if (data->psPfns->pfnCertCheckPolicy)
799                         {
800                             ret = data->psPfns->pfnCertCheckPolicy(data, signer,
801                              FALSE, 0);
802                             if (!ret)
803                                 err = GetLastError();
804                         }
805                         else
806                             TRACE(
807                              "no cert check policy, skipping policy check\n");
808                     }
809                 }
810             }
811             else
812                 err = GetLastError();
813         }
814         CertCloseStore(store, 0);
815     }
816     return err;
817 }
818
819 HRESULT WINAPI WintrustCertificateTrust(CRYPT_PROVIDER_DATA *data)
820 {
821     DWORD err;
822
823     TRACE("(%p)\n", data);
824
825     if (!data->csSigners)
826         err = TRUST_E_NOSIGNATURE;
827     else
828     {
829         DWORD i;
830         WTD_GENERIC_CHAIN_POLICY_CREATE_INFO createInfo;
831         CERT_CHAIN_PARA chainPara;
832
833         WINTRUST_CreateChainPolicyCreateInfo(data, &createInfo, &chainPara);
834         err = ERROR_SUCCESS;
835         for (i = 0; !err && i < data->csSigners; i++)
836             err = WINTRUST_CreateChainForSigner(data, i, &createInfo,
837              &chainPara);
838     }
839     if (err)
840         data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_CERTPROV] = err;
841     TRACE("returning %d (%08x)\n", !err ? S_OK : S_FALSE,
842      data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_CERTPROV]);
843     return !err ? S_OK : S_FALSE;
844 }
845
846 HRESULT WINAPI GenericChainCertificateTrust(CRYPT_PROVIDER_DATA *data)
847 {
848     DWORD err;
849     WTD_GENERIC_CHAIN_POLICY_DATA *policyData =
850      data->pWintrustData->pPolicyCallbackData;
851
852     TRACE("(%p)\n", data);
853
854     if (policyData && policyData->u.cbSize !=
855      sizeof(WTD_GENERIC_CHAIN_POLICY_CREATE_INFO))
856     {
857         err = ERROR_INVALID_PARAMETER;
858         goto end;
859     }
860     if (!data->csSigners)
861         err = TRUST_E_NOSIGNATURE;
862     else
863     {
864         DWORD i;
865         WTD_GENERIC_CHAIN_POLICY_CREATE_INFO createInfo, *pCreateInfo;
866         CERT_CHAIN_PARA chainPara, *pChainPara;
867
868         if (policyData)
869         {
870             pCreateInfo = policyData->pSignerChainInfo;
871             pChainPara = pCreateInfo->pChainPara;
872         }
873         else
874         {
875             WINTRUST_CreateChainPolicyCreateInfo(data, &createInfo, &chainPara);
876             pChainPara = &chainPara;
877             pCreateInfo = &createInfo;
878         }
879         err = ERROR_SUCCESS;
880         for (i = 0; !err && i < data->csSigners; i++)
881             err = WINTRUST_CreateChainForSigner(data, i, pCreateInfo,
882              pChainPara);
883     }
884
885 end:
886     if (err)
887         data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_CERTPROV] = err;
888     TRACE("returning %d (%08x)\n", !err ? S_OK : S_FALSE,
889      data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_CERTPROV]);
890     return !err ? S_OK : S_FALSE;
891 }
892
893 HRESULT WINAPI SoftpubAuthenticode(CRYPT_PROVIDER_DATA *data)
894 {
895     BOOL ret;
896     CERT_CHAIN_POLICY_STATUS policyStatus = { sizeof(policyStatus), 0 };
897
898     TRACE("(%p)\n", data);
899
900     if (data->pWintrustData->dwUIChoice != WTD_UI_NONE)
901         FIXME("unimplemented for UI choice %d\n",
902          data->pWintrustData->dwUIChoice);
903     if (!data->csSigners)
904     {
905         ret = FALSE;
906         policyStatus.dwError = TRUST_E_NOSIGNATURE;
907     }
908     else
909     {
910         DWORD i;
911
912         ret = TRUE;
913         for (i = 0; ret && i < data->csSigners; i++)
914         {
915             BYTE hash[20];
916             DWORD size = sizeof(hash);
917
918             /* First make sure cert isn't disallowed */
919             if ((ret = CertGetCertificateContextProperty(
920              data->pasSigners[i].pasCertChain[0].pCert,
921              CERT_SIGNATURE_HASH_PROP_ID, hash, &size)))
922             {
923                 static const WCHAR disallowedW[] =
924                  { 'D','i','s','a','l','l','o','w','e','d',0 };
925                 HCERTSTORE disallowed = CertOpenStore(CERT_STORE_PROV_SYSTEM_W,
926                  X509_ASN_ENCODING, 0, CERT_SYSTEM_STORE_CURRENT_USER,
927                  disallowedW);
928
929                 if (disallowed)
930                 {
931                     PCCERT_CONTEXT found = CertFindCertificateInStore(
932                      disallowed, X509_ASN_ENCODING, 0, CERT_FIND_SIGNATURE_HASH,
933                      hash, NULL);
934
935                     if (found)
936                     {
937                         /* Disallowed!  Can't verify it. */
938                         policyStatus.dwError = TRUST_E_SUBJECT_NOT_TRUSTED;
939                         ret = FALSE;
940                         CertFreeCertificateContext(found);
941                     }
942                     CertCloseStore(disallowed, 0);
943                 }
944             }
945             if (ret)
946             {
947                 CERT_CHAIN_POLICY_PARA policyPara = { sizeof(policyPara), 0 };
948
949                 if (data->dwRegPolicySettings & WTPF_TRUSTTEST)
950                     policyPara.dwFlags |= CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG;
951                 if (data->dwRegPolicySettings & WTPF_TESTCANBEVALID)
952                     policyPara.dwFlags |= CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG;
953                 if (data->dwRegPolicySettings & WTPF_IGNOREEXPIRATION)
954                     policyPara.dwFlags |=
955                      CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG |
956                      CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG |
957                      CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG;
958                 if (data->dwRegPolicySettings & WTPF_IGNOREREVOKATION)
959                     policyPara.dwFlags |=
960                      CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG |
961                      CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG |
962                      CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG |
963                      CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG;
964                 CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_AUTHENTICODE,
965                  data->pasSigners[i].pChainContext, &policyPara, &policyStatus);
966                 if (policyStatus.dwError != NO_ERROR)
967                     ret = FALSE;
968             }
969         }
970     }
971     if (!ret)
972         data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_POLICYPROV] =
973          policyStatus.dwError;
974     TRACE("returning %d (%08x)\n", ret ? S_OK : S_FALSE,
975      data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_POLICYPROV]);
976     return ret ? S_OK : S_FALSE;
977 }
978
979 static HRESULT WINAPI WINTRUST_DefaultPolicy(CRYPT_PROVIDER_DATA *pProvData,
980  DWORD dwStepError, DWORD dwRegPolicySettings, DWORD cSigner,
981  PWTD_GENERIC_CHAIN_POLICY_SIGNER_INFO rgpSigner, void *pvPolicyArg)
982 {
983     DWORD i;
984     CERT_CHAIN_POLICY_STATUS policyStatus = { sizeof(policyStatus), 0 };
985
986     for (i = 0; !policyStatus.dwError && i < cSigner; i++)
987     {
988         CERT_CHAIN_POLICY_PARA policyPara = { sizeof(policyPara), 0 };
989
990         if (dwRegPolicySettings & WTPF_IGNOREEXPIRATION)
991             policyPara.dwFlags |=
992              CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG |
993              CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG |
994              CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG;
995         if (dwRegPolicySettings & WTPF_IGNOREREVOKATION)
996             policyPara.dwFlags |=
997              CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG |
998              CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG |
999              CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG |
1000              CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG;
1001         CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_BASE,
1002          rgpSigner[i].pChainContext, &policyPara, &policyStatus);
1003     }
1004     return policyStatus.dwError;
1005 }
1006
1007 HRESULT WINAPI GenericChainFinalProv(CRYPT_PROVIDER_DATA *data)
1008 {
1009     HRESULT err = NO_ERROR; /* not a typo, MS confused the types */
1010     WTD_GENERIC_CHAIN_POLICY_DATA *policyData =
1011      data->pWintrustData->pPolicyCallbackData;
1012
1013     TRACE("(%p)\n", data);
1014
1015     if (data->pWintrustData->dwUIChoice != WTD_UI_NONE)
1016         FIXME("unimplemented for UI choice %d\n",
1017          data->pWintrustData->dwUIChoice);
1018     if (!data->csSigners)
1019         err = TRUST_E_NOSIGNATURE;
1020     else
1021     {
1022         PFN_WTD_GENERIC_CHAIN_POLICY_CALLBACK policyCallback;
1023         void *policyArg;
1024         WTD_GENERIC_CHAIN_POLICY_SIGNER_INFO *signers = NULL;
1025
1026         if (policyData)
1027         {
1028             policyCallback = policyData->pfnPolicyCallback;
1029             policyArg = policyData->pvPolicyArg;
1030         }
1031         else
1032         {
1033             policyCallback = WINTRUST_DefaultPolicy;
1034             policyArg = NULL;
1035         }
1036         if (data->csSigners)
1037         {
1038             DWORD i;
1039
1040             signers = data->psPfns->pfnAlloc(
1041              data->csSigners * sizeof(WTD_GENERIC_CHAIN_POLICY_SIGNER_INFO));
1042             if (signers)
1043             {
1044                 for (i = 0; i < data->csSigners; i++)
1045                 {
1046                     signers[i].u.cbSize =
1047                      sizeof(WTD_GENERIC_CHAIN_POLICY_SIGNER_INFO);
1048                     signers[i].pChainContext =
1049                      data->pasSigners[i].pChainContext;
1050                     signers[i].dwSignerType = data->pasSigners[i].dwSignerType;
1051                     signers[i].pMsgSignerInfo = data->pasSigners[i].psSigner;
1052                     signers[i].dwError = data->pasSigners[i].dwError;
1053                     if (data->pasSigners[i].csCounterSigners)
1054                         FIXME("unimplemented for counter signers\n");
1055                     signers[i].cCounterSigner = 0;
1056                     signers[i].rgpCounterSigner = NULL;
1057                 }
1058             }
1059             else
1060                 err = ERROR_OUTOFMEMORY;
1061         }
1062         if (err == NO_ERROR)
1063             err = policyCallback(data, TRUSTERROR_STEP_FINAL_POLICYPROV,
1064              data->dwRegPolicySettings, data->csSigners, signers, policyArg);
1065         data->psPfns->pfnFree(signers);
1066     }
1067     if (err != NO_ERROR)
1068         data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_POLICYPROV] = err;
1069     TRACE("returning %d (%08x)\n", err == NO_ERROR ? S_OK : S_FALSE,
1070      data->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_POLICYPROV]);
1071     return err == NO_ERROR ? S_OK : S_FALSE;
1072 }
1073
1074 HRESULT WINAPI SoftpubCleanup(CRYPT_PROVIDER_DATA *data)
1075 {
1076     DWORD i, j;
1077
1078     for (i = 0; i < data->csSigners; i++)
1079     {
1080         for (j = 0; j < data->pasSigners[i].csCertChain; j++)
1081             CertFreeCertificateContext(data->pasSigners[i].pasCertChain[j].pCert);
1082         data->psPfns->pfnFree(data->pasSigners[i].pasCertChain);
1083         data->psPfns->pfnFree(data->pasSigners[i].psSigner);
1084         CertFreeCertificateChain(data->pasSigners[i].pChainContext);
1085     }
1086     data->psPfns->pfnFree(data->pasSigners);
1087
1088     for (i = 0; i < data->chStores; i++)
1089         CertCloseStore(data->pahStores[i], 0);
1090     data->psPfns->pfnFree(data->pahStores);
1091
1092     if (data->u.pPDSip)
1093     {
1094         data->psPfns->pfnFree(data->u.pPDSip->pSip);
1095         data->psPfns->pfnFree(data->u.pPDSip->pCATSip);
1096         data->psPfns->pfnFree(data->u.pPDSip->psSipSubjectInfo);
1097         data->psPfns->pfnFree(data->u.pPDSip->psSipCATSubjectInfo);
1098         data->psPfns->pfnFree(data->u.pPDSip->psIndirectData);
1099     }
1100
1101     CryptMsgClose(data->hMsg);
1102
1103     if (data->fOpenedFile &&
1104      data->pWintrustData->dwUnionChoice == WTD_CHOICE_FILE)
1105         CloseHandle(data->pWintrustData->u.pFile->hFile);
1106
1107     return S_OK;
1108 }
1109
1110 HRESULT WINAPI HTTPSCertificateTrust(CRYPT_PROVIDER_DATA *data)
1111 {
1112     FIXME("(%p)\n", data);
1113     return S_OK;
1114 }
1115
1116 HRESULT WINAPI HTTPSFinalProv(CRYPT_PROVIDER_DATA *data)
1117 {
1118     FIXME("(%p)\n", data);
1119     return S_OK;
1120 }