crypt32: Check chain root's trusted status regardless of whether its signature is...
[wine] / dlls / crypt32 / chain.c
1 /*
2  * Copyright 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 #include <stdarg.h>
20 #include "windef.h"
21 #include "winbase.h"
22 #include "wincrypt.h"
23 #include "wine/debug.h"
24 #include "crypt32_private.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
27
28 #define DEFAULT_CYCLE_MODULUS 7
29
30 static HCERTCHAINENGINE CRYPT_defaultChainEngine;
31
32 /* This represents a subset of a certificate chain engine:  it doesn't include
33  * the "hOther" store described by MSDN, because I'm not sure how that's used.
34  * It also doesn't include the "hTrust" store, because I don't yet implement
35  * CTLs or complex certificate chains.
36  */
37 typedef struct _CertificateChainEngine
38 {
39     LONG       ref;
40     HCERTSTORE hRoot;
41     HCERTSTORE hWorld;
42     DWORD      dwFlags;
43     DWORD      dwUrlRetrievalTimeout;
44     DWORD      MaximumCachedCertificates;
45     DWORD      CycleDetectionModulus;
46 } CertificateChainEngine, *PCertificateChainEngine;
47
48 static inline void CRYPT_AddStoresToCollection(HCERTSTORE collection,
49  DWORD cStores, HCERTSTORE *stores)
50 {
51     DWORD i;
52
53     for (i = 0; i < cStores; i++)
54         CertAddStoreToCollection(collection, stores[i], 0, 0);
55 }
56
57 static inline void CRYPT_CloseStores(DWORD cStores, HCERTSTORE *stores)
58 {
59     DWORD i;
60
61     for (i = 0; i < cStores; i++)
62         CertCloseStore(stores[i], 0);
63 }
64
65 static const WCHAR rootW[] = { 'R','o','o','t',0 };
66
67 static BOOL CRYPT_CheckRestrictedRoot(HCERTSTORE store)
68 {
69     BOOL ret = TRUE;
70
71     if (store)
72     {
73         HCERTSTORE rootStore = CertOpenSystemStoreW(0, rootW);
74         PCCERT_CONTEXT cert = NULL, check;
75         BYTE hash[20];
76         DWORD size;
77
78         do {
79             cert = CertEnumCertificatesInStore(store, cert);
80             if (cert)
81             {
82                 size = sizeof(hash);
83
84                 ret = CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
85                  hash, &size);
86                 if (ret)
87                 {
88                     CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
89
90                     check = CertFindCertificateInStore(rootStore,
91                      cert->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH, &blob,
92                      NULL);
93                     if (!check)
94                         ret = FALSE;
95                     else
96                         CertFreeCertificateContext(check);
97                 }
98             }
99         } while (ret && cert);
100         if (cert)
101             CertFreeCertificateContext(cert);
102         CertCloseStore(rootStore, 0);
103     }
104     return ret;
105 }
106
107 BOOL WINAPI CertCreateCertificateChainEngine(PCERT_CHAIN_ENGINE_CONFIG pConfig,
108  HCERTCHAINENGINE *phChainEngine)
109 {
110     static const WCHAR caW[] = { 'C','A',0 };
111     static const WCHAR myW[] = { 'M','y',0 };
112     static const WCHAR trustW[] = { 'T','r','u','s','t',0 };
113     BOOL ret;
114
115     TRACE("(%p, %p)\n", pConfig, phChainEngine);
116
117     if (pConfig->cbSize != sizeof(*pConfig))
118     {
119         SetLastError(E_INVALIDARG);
120         return FALSE;
121     }
122     *phChainEngine = NULL;
123     ret = CRYPT_CheckRestrictedRoot(pConfig->hRestrictedRoot);
124     if (ret)
125     {
126         PCertificateChainEngine engine =
127          CryptMemAlloc(sizeof(CertificateChainEngine));
128
129         if (engine)
130         {
131             HCERTSTORE worldStores[4];
132
133             engine->ref = 1;
134             if (pConfig->hRestrictedRoot)
135                 engine->hRoot = CertDuplicateStore(pConfig->hRestrictedRoot);
136             else
137                 engine->hRoot = CertOpenSystemStoreW(0, rootW);
138             engine->hWorld = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
139              CERT_STORE_CREATE_NEW_FLAG, NULL);
140             worldStores[0] = CertDuplicateStore(engine->hRoot);
141             worldStores[1] = CertOpenSystemStoreW(0, caW);
142             worldStores[2] = CertOpenSystemStoreW(0, myW);
143             worldStores[3] = CertOpenSystemStoreW(0, trustW);
144             CRYPT_AddStoresToCollection(engine->hWorld,
145              sizeof(worldStores) / sizeof(worldStores[0]), worldStores);
146             CRYPT_AddStoresToCollection(engine->hWorld,
147              pConfig->cAdditionalStore, pConfig->rghAdditionalStore);
148             CRYPT_CloseStores(sizeof(worldStores) / sizeof(worldStores[0]),
149              worldStores);
150             engine->dwFlags = pConfig->dwFlags;
151             engine->dwUrlRetrievalTimeout = pConfig->dwUrlRetrievalTimeout;
152             engine->MaximumCachedCertificates =
153              pConfig->MaximumCachedCertificates;
154             if (pConfig->CycleDetectionModulus)
155                 engine->CycleDetectionModulus = pConfig->CycleDetectionModulus;
156             else
157                 engine->CycleDetectionModulus = DEFAULT_CYCLE_MODULUS;
158             *phChainEngine = (HCERTCHAINENGINE)engine;
159             ret = TRUE;
160         }
161         else
162             ret = FALSE;
163     }
164     return ret;
165 }
166
167 void WINAPI CertFreeCertificateChainEngine(HCERTCHAINENGINE hChainEngine)
168 {
169     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
170
171     TRACE("(%p)\n", hChainEngine);
172
173     if (engine && InterlockedDecrement(&engine->ref) == 0)
174     {
175         CertCloseStore(engine->hWorld, 0);
176         CertCloseStore(engine->hRoot, 0);
177         CryptMemFree(engine);
178     }
179 }
180
181 static HCERTCHAINENGINE CRYPT_GetDefaultChainEngine(void)
182 {
183     if (!CRYPT_defaultChainEngine)
184     {
185         CERT_CHAIN_ENGINE_CONFIG config = { 0 };
186         HCERTCHAINENGINE engine;
187
188         config.cbSize = sizeof(config);
189         CertCreateCertificateChainEngine(&config, &engine);
190         InterlockedCompareExchangePointer(&CRYPT_defaultChainEngine, engine,
191          NULL);
192         if (CRYPT_defaultChainEngine != engine)
193             CertFreeCertificateChainEngine(engine);
194     }
195     return CRYPT_defaultChainEngine;
196 }
197
198 void default_chain_engine_free(void)
199 {
200     CertFreeCertificateChainEngine(CRYPT_defaultChainEngine);
201 }
202
203 typedef struct _CertificateChain
204 {
205     CERT_CHAIN_CONTEXT context;
206     LONG ref;
207 } CertificateChain, *PCertificateChain;
208
209 static inline BOOL WINAPI CRYPT_IsCertificateSelfSigned(PCCERT_CONTEXT cert)
210 {
211     return CertCompareCertificateName(cert->dwCertEncodingType,
212      &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer);
213 }
214
215 /* Gets cert's issuer from store, and returns the validity flags associated
216  * with it.  Returns NULL if no issuer whose public key matches cert's
217  * signature could be found.
218  */
219 static PCCERT_CONTEXT CRYPT_GetIssuerFromStore(HCERTSTORE store,
220  PCCERT_CONTEXT cert, PDWORD pdwFlags)
221 {
222     PCCERT_CONTEXT issuer = NULL;
223
224     /* There might be more than issuer with the same name, so keep looking until
225      * one produces the correct signature for this cert.
226      */
227     do {
228         *pdwFlags = CERT_STORE_REVOCATION_FLAG | CERT_STORE_SIGNATURE_FLAG |
229          CERT_STORE_TIME_VALIDITY_FLAG;
230         issuer = CertGetIssuerCertificateFromStore(store, cert, issuer,
231          pdwFlags);
232     } while (issuer && (*pdwFlags & CERT_STORE_SIGNATURE_FLAG));
233     return issuer;
234 }
235
236 static BOOL CRYPT_AddCertToSimpleChain(PCERT_SIMPLE_CHAIN chain,
237  PCCERT_CONTEXT cert, DWORD dwFlags)
238 {
239     BOOL ret = FALSE;
240     PCERT_CHAIN_ELEMENT element = CryptMemAlloc(sizeof(CERT_CHAIN_ELEMENT));
241
242     if (element)
243     {
244         if (!chain->cElement)
245             chain->rgpElement = CryptMemAlloc(sizeof(PCERT_CHAIN_ELEMENT));
246         else
247             chain->rgpElement = CryptMemRealloc(chain->rgpElement,
248              (chain->cElement + 1) * sizeof(PCERT_CHAIN_ELEMENT));
249         if (chain->rgpElement)
250         {
251             memset(element, 0, sizeof(CERT_CHAIN_ELEMENT));
252             element->cbSize = sizeof(CERT_CHAIN_ELEMENT);
253             element->pCertContext = CertDuplicateCertificateContext(cert);
254             if (dwFlags & CERT_STORE_REVOCATION_FLAG &&
255              !(dwFlags & CERT_STORE_NO_CRL_FLAG))
256                 element->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_REVOKED;
257             if (dwFlags & CERT_STORE_SIGNATURE_FLAG)
258                 element->TrustStatus.dwErrorStatus |=
259                  CERT_TRUST_IS_NOT_SIGNATURE_VALID;
260             if (dwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
261                 element->TrustStatus.dwErrorStatus |=
262                  CERT_TRUST_IS_NOT_TIME_VALID;
263             if (chain->cElement)
264             {
265                 PCERT_CHAIN_ELEMENT prevElement =
266                  chain->rgpElement[chain->cElement - 1];
267
268                 /* This cert is the issuer of the previous one in the chain, so
269                  * retroactively check the previous one's time validity nesting.
270                  */
271                 if (!CertVerifyValidityNesting(
272                  prevElement->pCertContext->pCertInfo, cert->pCertInfo))
273                     prevElement->TrustStatus.dwErrorStatus |=
274                      CERT_TRUST_IS_NOT_TIME_NESTED;
275             }
276             /* FIXME: check valid usages, name constraints, and for cycles */
277             /* FIXME: initialize the rest of element */
278             chain->TrustStatus.dwErrorStatus |=
279              element->TrustStatus.dwErrorStatus;
280             chain->TrustStatus.dwInfoStatus |=
281              element->TrustStatus.dwInfoStatus;
282             chain->rgpElement[chain->cElement++] = element;
283             ret = TRUE;
284         }
285         else
286             CryptMemFree(element);
287     }
288     return ret;
289 }
290
291 static void CRYPT_FreeChainElement(PCERT_CHAIN_ELEMENT element)
292 {
293     CertFreeCertificateContext(element->pCertContext);
294     CryptMemFree(element);
295 }
296
297 static void CRYPT_FreeSimpleChain(PCERT_SIMPLE_CHAIN chain)
298 {
299     DWORD i;
300
301     for (i = 0; i < chain->cElement; i++)
302         CRYPT_FreeChainElement(chain->rgpElement[i]);
303     CryptMemFree(chain->rgpElement);
304     CryptMemFree(chain);
305 }
306
307 static BOOL CRYPT_BuildSimpleChain(HCERTCHAINENGINE hChainEngine,
308  PCCERT_CONTEXT cert, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
309  PCERT_SIMPLE_CHAIN *ppChain)
310 {
311     BOOL ret = FALSE;
312     PCertificateChainEngine engine = (PCertificateChainEngine)hChainEngine;
313     PCERT_SIMPLE_CHAIN chain;
314     HCERTSTORE world;
315
316     TRACE("(%p, %p, %p, %p)\n", hChainEngine, cert, pTime, hAdditionalStore);
317
318     world = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
319      CERT_STORE_CREATE_NEW_FLAG, NULL);
320     CertAddStoreToCollection(world, engine->hWorld, 0, 0);
321     if (cert->hCertStore)
322         CertAddStoreToCollection(world, cert->hCertStore, 0, 0);
323     if (hAdditionalStore)
324         CertAddStoreToCollection(world, hAdditionalStore, 0, 0);
325     chain = CryptMemAlloc(sizeof(CERT_SIMPLE_CHAIN));
326     if (chain)
327     {
328         memset(chain, 0, sizeof(CERT_SIMPLE_CHAIN));
329         chain->cbSize = sizeof(CERT_SIMPLE_CHAIN);
330         ret = CRYPT_AddCertToSimpleChain(chain, cert, 0);
331         while (ret && !CRYPT_IsCertificateSelfSigned(cert))
332         {
333             DWORD flags;
334             PCCERT_CONTEXT issuer = CRYPT_GetIssuerFromStore(world, cert,
335              &flags);
336
337             if (issuer)
338             {
339                 ret = CRYPT_AddCertToSimpleChain(chain, issuer, flags);
340                 cert = issuer;
341             }
342             else
343             {
344                 TRACE("Couldn't find issuer, aborting chain creation\n");
345                 ret = FALSE;
346             }
347         }
348         if (ret)
349         {
350             PCERT_CHAIN_ELEMENT rootElement =
351              chain->rgpElement[chain->cElement - 1];
352             PCCERT_CONTEXT root = rootElement->pCertContext;
353
354             if (!(ret = CRYPT_IsCertificateSelfSigned(root)))
355                 TRACE("Last certificate is not self-signed\n");
356             else
357             {
358                 rootElement->TrustStatus.dwInfoStatus |=
359                  CERT_TRUST_IS_SELF_SIGNED;
360                 if (!(ret = CryptVerifyCertificateSignatureEx(0,
361                  root->dwCertEncodingType, CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT,
362                  (void *)root, CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)root,
363                  0, NULL)))
364                 {
365                     TRACE("Last certificate's signature is invalid\n");
366                     rootElement->TrustStatus.dwErrorStatus |=
367                      CERT_TRUST_IS_NOT_SIGNATURE_VALID;
368                 }
369             }
370             if (CRYPT_IsCertificateSelfSigned(root))
371             {
372                 BYTE hash[20];
373                 DWORD size = sizeof(hash);
374                 CRYPT_HASH_BLOB blob = { sizeof(hash), hash };
375                 PCCERT_CONTEXT trustedRoot;
376
377                 CertGetCertificateContextProperty(root, CERT_HASH_PROP_ID, hash,
378                  &size);
379                 trustedRoot = CertFindCertificateInStore(engine->hRoot,
380                  root->dwCertEncodingType, 0, CERT_FIND_SHA1_HASH, &blob, NULL);
381                 if (!trustedRoot)
382                     rootElement->TrustStatus.dwErrorStatus |=
383                      CERT_TRUST_IS_UNTRUSTED_ROOT;
384                 else
385                     CertFreeCertificateContext(trustedRoot);
386             }
387             chain->TrustStatus.dwErrorStatus |=
388              rootElement->TrustStatus.dwErrorStatus;
389             chain->TrustStatus.dwInfoStatus |=
390              rootElement->TrustStatus.dwInfoStatus & ~CERT_TRUST_IS_SELF_SIGNED;
391         }
392         if (!ret)
393         {
394             CRYPT_FreeSimpleChain(chain);
395             chain = NULL;
396         }
397         *ppChain = chain;
398     }
399     CertCloseStore(world, 0);
400     return ret;
401 }
402
403 typedef struct _CERT_CHAIN_PARA_NO_EXTRA_FIELDS {
404     DWORD            cbSize;
405     CERT_USAGE_MATCH RequestedUsage;
406 } CERT_CHAIN_PARA_NO_EXTRA_FIELDS, *PCERT_CHAIN_PARA_NO_EXTRA_FIELDS;
407
408 typedef struct _CERT_CHAIN_PARA_EXTRA_FIELDS {
409     DWORD            cbSize;
410     CERT_USAGE_MATCH RequestedUsage;
411     CERT_USAGE_MATCH RequestedIssuancePolicy;
412     DWORD            dwUrlRetrievalTimeout;
413     BOOL             fCheckRevocationFreshnessTime;
414     DWORD            dwRevocationFreshnessTime;
415 } CERT_CHAIN_PARA_EXTRA_FIELDS, *PCERT_CHAIN_PARA_EXTRA_FIELDS;
416
417 BOOL WINAPI CertGetCertificateChain(HCERTCHAINENGINE hChainEngine,
418  PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore,
419  PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved,
420  PCCERT_CHAIN_CONTEXT* ppChainContext)
421 {
422     PCERT_SIMPLE_CHAIN simpleChain = NULL;
423     BOOL ret;
424
425     TRACE("(%p, %p, %p, %p, %p, %08x, %p, %p)\n", hChainEngine, pCertContext,
426      pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext);
427
428     if (!pChainPara)
429     {
430         SetLastError(E_INVALIDARG);
431         return FALSE;
432     }
433     if (ppChainContext)
434         *ppChainContext = NULL;
435     if (!hChainEngine)
436         hChainEngine = CRYPT_GetDefaultChainEngine();
437     /* FIXME: what about HCCE_LOCAL_MACHINE? */
438     /* FIXME: pChainPara is for now ignored */
439     /* FIXME: only simple chains are supported for now, as CTLs aren't
440      * supported yet.
441      */
442     if ((ret = CRYPT_BuildSimpleChain(hChainEngine, pCertContext, pTime,
443      hAdditionalStore, &simpleChain)))
444     {
445         PCertificateChain chain = CryptMemAlloc(sizeof(CertificateChain));
446
447         if (chain)
448         {
449             chain->ref = 1;
450             chain->context.cbSize = sizeof(CERT_CHAIN_CONTEXT);
451             memcpy(&chain->context.TrustStatus, &simpleChain->TrustStatus,
452              sizeof(CERT_TRUST_STATUS));
453             chain->context.cChain = 1;
454             chain->context.rgpChain = CryptMemAlloc(sizeof(PCERT_SIMPLE_CHAIN));
455             chain->context.rgpChain[0] = simpleChain;
456             chain->context.cLowerQualityChainContext = 0;
457             chain->context.rgpLowerQualityChainContext = NULL;
458             chain->context.fHasRevocationFreshnessTime = FALSE;
459             chain->context.dwRevocationFreshnessTime = 0;
460         }
461         else
462             ret = FALSE;
463         if (ppChainContext)
464             *ppChainContext = (PCCERT_CHAIN_CONTEXT)chain;
465         else
466             CertFreeCertificateChain((PCCERT_CHAIN_CONTEXT)chain);
467     }
468     TRACE("returning %d\n", ret);
469     return ret;
470 }
471
472 static void CRYPT_FreeChainContext(PCertificateChain chain)
473 {
474     DWORD i;
475
476     /* Note the chain's rgpLowerQualityChainContext isn't freed, but
477      * it's never set, either.
478      */
479     for (i = 0; i < chain->context.cChain; i++)
480         CRYPT_FreeSimpleChain(chain->context.rgpChain[i]);
481     CryptMemFree(chain->context.rgpChain);
482     CryptMemFree(chain);
483 }
484
485 void WINAPI CertFreeCertificateChain(PCCERT_CHAIN_CONTEXT pChainContext)
486 {
487     PCertificateChain chain = (PCertificateChain)pChainContext;
488
489     TRACE("(%p)\n", pChainContext);
490
491     if (chain)
492     {
493         if (InterlockedDecrement(&chain->ref) == 0)
494             CRYPT_FreeChainContext(chain);
495     }
496 }