VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/crypto/pkcs7-verify.cpp@ 84379

Last change on this file since 84379 was 84331, checked in by vboxsync, 5 years ago

IPRT: RISKY: rtCrPkcs7VerifySignerInfo should pass trusted certificates to the path machinery too, they could be expired and otherwise unsuitable. bugref:9699

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 40.8 KB
Line 
1/* $Id: pkcs7-verify.cpp 84331 2020-05-18 13:38:38Z vboxsync $ */
2/** @file
3 * IPRT - Crypto - PKCS \#7, Verification
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#include "internal/iprt.h"
32#include <iprt/crypto/pkcs7.h>
33
34#include <iprt/err.h>
35#include <iprt/mem.h>
36#include <iprt/string.h>
37#include <iprt/crypto/digest.h>
38#include <iprt/crypto/key.h>
39#include <iprt/crypto/pkix.h>
40#include <iprt/crypto/store.h>
41#include <iprt/crypto/x509.h>
42
43#ifdef IPRT_WITH_OPENSSL
44# include "internal/iprt-openssl.h"
45# include <openssl/pkcs7.h>
46# include <openssl/x509.h>
47# include <openssl/err.h>
48#endif
49
50
51
52#ifdef IPRT_WITH_OPENSSL
53static int rtCrPkcs7VerifySignedDataUsingOpenSsl(PCRTCRPKCS7CONTENTINFO pContentInfo, uint32_t fFlags,
54 RTCRSTORE hAdditionalCerts, RTCRSTORE hTrustedCerts,
55 void const *pvContent, size_t cbContent, PRTERRINFO pErrInfo)
56{
57 RT_NOREF_PV(fFlags);
58
59 /*
60 * Verify using OpenSSL. ERR_PUT_error
61 */
62 unsigned char const *pbRawContent;
63 uint32_t cbRawContent;
64 void *pvFree;
65 int rcOssl = RTAsn1EncodeQueryRawBits(RTCrPkcs7ContentInfo_GetAsn1Core(pContentInfo),
66 (const uint8_t **)&pbRawContent, &cbRawContent, &pvFree, pErrInfo);
67 AssertRCReturn(rcOssl, rcOssl);
68
69 PKCS7 *pOsslPkcs7 = NULL;
70 PKCS7 *pOsslPkcs7Ret = d2i_PKCS7(&pOsslPkcs7, &pbRawContent, cbRawContent);
71
72 RTMemTmpFree(pvFree);
73
74 if (pOsslPkcs7Ret != NULL)
75 {
76 STACK_OF(X509) *pAddCerts = NULL;
77 if (hAdditionalCerts != NIL_RTCRSTORE)
78 rcOssl = RTCrStoreConvertToOpenSslCertStack(hAdditionalCerts, 0, (void **)&pAddCerts, pErrInfo);
79 else
80 {
81 pAddCerts = sk_X509_new_null();
82 rcOssl = RT_LIKELY(pAddCerts != NULL) ? VINF_SUCCESS : VERR_NO_MEMORY;
83 }
84 if (RT_SUCCESS(rcOssl))
85 {
86 PCRTCRPKCS7SETOFCERTS pCerts = &pContentInfo->u.pSignedData->Certificates;
87 for (uint32_t i = 0; i < pCerts->cItems; i++)
88 if (pCerts->papItems[i]->enmChoice == RTCRPKCS7CERTCHOICE_X509)
89 rtCrOpenSslAddX509CertToStack(pAddCerts, pCerts->papItems[i]->u.pX509Cert, NULL);
90
91 X509_STORE *pTrustedCerts = NULL;
92 if (hTrustedCerts != NIL_RTCRSTORE)
93 rcOssl = RTCrStoreConvertToOpenSslCertStore(hTrustedCerts, 0, (void **)&pTrustedCerts, pErrInfo);
94 if (RT_SUCCESS(rcOssl))
95 {
96 rtCrOpenSslInit();
97
98 BIO *pBioContent = BIO_new_mem_buf((void *)pvContent, (int)cbContent);
99 if (pBioContent)
100 {
101 uint32_t fOsslFlags = PKCS7_NOCHAIN;
102 fOsslFlags |= PKCS7_NOVERIFY; // temporary hack.
103 if (PKCS7_verify(pOsslPkcs7, pAddCerts, pTrustedCerts, pBioContent, NULL /*out*/, fOsslFlags))
104 rcOssl = VINF_SUCCESS;
105 else
106 {
107 rcOssl = RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_OSSL_VERIFY_FAILED, "PKCS7_verify failed: ");
108 if (pErrInfo)
109 ERR_print_errors_cb(rtCrOpenSslErrInfoCallback, pErrInfo);
110 }
111 BIO_free(pBioContent);
112 }
113 if (pTrustedCerts)
114 X509_STORE_free(pTrustedCerts);
115 }
116 else
117 rcOssl = RTErrInfoSet(pErrInfo, rcOssl, "RTCrStoreConvertToOpenSslCertStack failed");
118 if (pAddCerts)
119 sk_X509_pop_free(pAddCerts, X509_free);
120 }
121 else
122 rcOssl = RTErrInfoSet(pErrInfo, rcOssl, "RTCrStoreConvertToOpenSslCertStack failed");
123 PKCS7_free(pOsslPkcs7);
124 }
125 else
126 {
127 rcOssl = RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_OSSL_D2I_FAILED, "d2i_PKCS7 failed");
128 if (pErrInfo)
129 ERR_print_errors_cb(rtCrOpenSslErrInfoCallback, pErrInfo);
130 }
131
132 return rcOssl;
133}
134#endif /* IPRT_WITH_OPENSSL */
135
136
137
138static int rtCrPkcs7VerifyCertUsageTimstamping(PCRTCRX509CERTIFICATE pCert, PRTERRINFO pErrInfo)
139{
140 if (!(pCert->TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_EXT_KEY_USAGE))
141 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_KEY_USAGE_MISMATCH, "No extended key usage certificate attribute.");
142 if (!(pCert->TbsCertificate.T3.fExtKeyUsage & (RTCRX509CERT_EKU_F_TIMESTAMPING | RTCRX509CERT_EKU_F_MS_TIMESTAMP_SIGNING)))
143 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_KEY_USAGE_MISMATCH, "fExtKeyUsage=%#x, missing %#x (time stamping)",
144 pCert->TbsCertificate.T3.fExtKeyUsage,
145 RTCRX509CERT_EKU_F_TIMESTAMPING | RTCRX509CERT_EKU_F_MS_TIMESTAMP_SIGNING);
146 return VINF_SUCCESS;
147}
148
149
150static int rtCrPkcs7VerifyCertUsageDigitalSignature(PCRTCRX509CERTIFICATE pCert, PRTERRINFO pErrInfo)
151{
152 if ( (pCert->TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_KEY_USAGE)
153 && !(pCert->TbsCertificate.T3.fKeyUsage & RTCRX509CERT_KEY_USAGE_F_DIGITAL_SIGNATURE))
154 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_KEY_USAGE_MISMATCH, "fKeyUsage=%#x, missing %#x",
155 pCert->TbsCertificate.T3.fKeyUsage, RTCRX509CERT_KEY_USAGE_F_DIGITAL_SIGNATURE);
156 return VINF_SUCCESS;
157}
158
159
160/**
161 * @callback_method_impl{RTCRPKCS7VERIFYCERTCALLBACK,
162 * Default implementation that checks for the DigitalSignature KeyUsage bit.}
163 */
164RTDECL(int) RTCrPkcs7VerifyCertCallbackDefault(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
165 void *pvUser, PRTERRINFO pErrInfo)
166{
167 RT_NOREF_PV(hCertPaths); RT_NOREF_PV(pvUser);
168 int rc = VINF_SUCCESS;
169
170 if (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA)
171 rc = rtCrPkcs7VerifyCertUsageDigitalSignature(pCert, pErrInfo);
172
173 if ( (fFlags & RTCRPKCS7VCC_F_TIMESTAMP)
174 && RT_SUCCESS(rc))
175 rc = rtCrPkcs7VerifyCertUsageTimstamping(pCert, pErrInfo);
176
177 return rc;
178}
179
180
181/**
182 * @callback_method_impl{RTCRPKCS7VERIFYCERTCALLBACK,
183 * Standard code signing. Use this for Microsoft SPC.}
184 */
185RTDECL(int) RTCrPkcs7VerifyCertCallbackCodeSigning(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
186 void *pvUser, PRTERRINFO pErrInfo)
187{
188 RT_NOREF_PV(hCertPaths); RT_NOREF_PV(pvUser);
189 int rc = VINF_SUCCESS;
190 if (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA)
191 {
192 /*
193 * If KeyUsage is present it must include digital signature.
194 */
195 rc = rtCrPkcs7VerifyCertUsageDigitalSignature(pCert, pErrInfo);
196 if (RT_SUCCESS(rc))
197 {
198 /*
199 * The extended usage 'code signing' must be present.
200 */
201 if (!(pCert->TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_EXT_KEY_USAGE))
202 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_KEY_USAGE_MISMATCH, "No extended key usage certificate attribute.");
203 if (!(pCert->TbsCertificate.T3.fExtKeyUsage & RTCRX509CERT_EKU_F_CODE_SIGNING))
204 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_KEY_USAGE_MISMATCH, "fExtKeyUsage=%#x, missing %#x",
205 pCert->TbsCertificate.T3.fExtKeyUsage, RTCRX509CERT_EKU_F_CODE_SIGNING);
206 }
207 }
208
209 /*
210 * Timestamping too?
211 */
212 if ( (fFlags & RTCRPKCS7VCC_F_TIMESTAMP)
213 && RT_SUCCESS(rc))
214 rc = rtCrPkcs7VerifyCertUsageTimstamping(pCert, pErrInfo);
215
216 return rc;
217}
218
219
220/**
221 * Deals with authenticated attributes.
222 *
223 * When authenticated attributes are present (checked by caller) we must:
224 * - fish out the content type and check it against the content inof,
225 * - fish out the message digest among and check it against *phDigest,
226 * - compute the message digest of the authenticated attributes and
227 * replace *phDigest with this for the signature verification.
228 *
229 * @returns IPRT status code.
230 * @param pSignerInfo The signer info being verified.
231 * @param pSignedData The signed data.
232 * @param phDigest On input this is the digest of the content. On
233 * output it will (on success) be a reference to
234 * the message digest of the authenticated
235 * attributes. The input reference is consumed.
236 * The caller shall release the output reference.
237 * @param fFlags Flags.
238 * @param pErrInfo Extended error info, optional.
239 */
240static int rtCrPkcs7VerifySignerInfoAuthAttribs(PCRTCRPKCS7SIGNERINFO pSignerInfo, PCRTCRPKCS7SIGNEDDATA pSignedData,
241 PRTCRDIGEST phDigest, uint32_t fFlags, PRTERRINFO pErrInfo)
242{
243 /*
244 * Scan the attributes and validate the two required attributes
245 * (RFC-2315, chapter 9.2, fourth bullet). Checking that we've got exactly
246 * one of each of them is checked by the santiy checker function, so we'll
247 * just assert that it did it's job here.
248 */
249 uint32_t cContentTypes = 0;
250 uint32_t cMessageDigests = 0;
251 uint32_t i = pSignerInfo->AuthenticatedAttributes.cItems;
252 while (i-- > 0)
253 {
254 PCRTCRPKCS7ATTRIBUTE pAttrib = pSignerInfo->AuthenticatedAttributes.papItems[i];
255
256 if (RTAsn1ObjId_CompareWithString(&pAttrib->Type, RTCR_PKCS9_ID_CONTENT_TYPE_OID) == 0)
257 {
258 AssertReturn(!cContentTypes, VERR_CR_PKCS7_INTERNAL_ERROR);
259 AssertReturn(pAttrib->enmType == RTCRPKCS7ATTRIBUTETYPE_OBJ_IDS, VERR_CR_PKCS7_INTERNAL_ERROR);
260 AssertReturn(pAttrib->uValues.pObjIds->cItems == 1, VERR_CR_PKCS7_INTERNAL_ERROR);
261
262 if ( !(fFlags & RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE) /* See note about microsoft below. */
263 && RTAsn1ObjId_Compare(pAttrib->uValues.pObjIds->papItems[0], &pSignedData->ContentInfo.ContentType) != 0)
264 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_CONTENT_TYPE_ATTRIB_MISMATCH,
265 "Expected content-type %s, found %s", pAttrib->uValues.pObjIds->papItems[0]->szObjId,
266 pSignedData->ContentInfo.ContentType.szObjId);
267 cContentTypes++;
268 }
269 else if (RTAsn1ObjId_CompareWithString(&pAttrib->Type, RTCR_PKCS9_ID_MESSAGE_DIGEST_OID) == 0)
270 {
271 AssertReturn(!cMessageDigests, VERR_CR_PKCS7_INTERNAL_ERROR);
272 AssertReturn(pAttrib->enmType == RTCRPKCS7ATTRIBUTETYPE_OCTET_STRINGS, VERR_CR_PKCS7_INTERNAL_ERROR);
273 AssertReturn(pAttrib->uValues.pOctetStrings->cItems == 1, VERR_CR_PKCS7_INTERNAL_ERROR);
274
275 if (!RTCrDigestMatch(*phDigest,
276 pAttrib->uValues.pOctetStrings->papItems[0]->Asn1Core.uData.pv,
277 pAttrib->uValues.pOctetStrings->papItems[0]->Asn1Core.cb))
278 {
279 size_t cbHash = RTCrDigestGetHashSize(*phDigest);
280 if (cbHash != pAttrib->uValues.pOctetStrings->papItems[0]->Asn1Core.cb)
281 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_MESSAGE_DIGEST_ATTRIB_MISMATCH,
282 "Authenticated message-digest attribute mismatch: cbHash=%#zx cbValue=%#x",
283 cbHash, pAttrib->uValues.pOctetStrings->papItems[0]->Asn1Core.cb);
284 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_MESSAGE_DIGEST_ATTRIB_MISMATCH,
285 "Authenticated message-digest attribute mismatch (cbHash=%#zx):\n"
286 "signed: %.*Rhxs\n"
287 "our: %.*Rhxs\n",
288 cbHash,
289 cbHash, pAttrib->uValues.pOctetStrings->papItems[0]->Asn1Core.uData.pv,
290 cbHash, RTCrDigestGetHash(*phDigest));
291 }
292 cMessageDigests++;
293 }
294 }
295
296 /*
297 * Full error reporting here as we don't currently extensively santiy check
298 * counter signatures.
299 * Note! Microsoft includes content info in their timestamp counter signatures,
300 * at least for vista, despite the RFC-3852 stating counter signatures
301 * "MUST NOT contain a content-type".
302 */
303 if (RT_UNLIKELY( cContentTypes != 1
304 && !(fFlags & RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE)))
305 return RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_MISSING_CONTENT_TYPE_ATTRIB,
306 "Missing authenticated content-type attribute.");
307 if (RT_UNLIKELY(cMessageDigests != 1))
308 return RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_MISSING_MESSAGE_DIGEST_ATTRIB,
309 "Missing authenticated message-digest attribute.");
310
311 /*
312 * Calculate the digest of the authenticated attributes for use in the
313 * signature validation.
314 */
315 if ( pSignerInfo->DigestAlgorithm.Parameters.enmType != RTASN1TYPE_NULL
316 && pSignerInfo->DigestAlgorithm.Parameters.enmType != RTASN1TYPE_NOT_PRESENT)
317 return RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_DIGEST_PARAMS_NOT_IMPL, "Digest algorithm has unsupported parameters");
318
319 RTCRDIGEST hDigest;
320 int rc = RTCrDigestCreateByObjId(&hDigest, &pSignerInfo->DigestAlgorithm.Algorithm);
321 if (RT_SUCCESS(rc))
322 {
323 RTCrDigestRelease(*phDigest);
324 *phDigest = hDigest;
325
326 /* ASSUMES that the attributes are encoded according to DER. */
327 uint8_t const *pbData;
328 uint32_t cbData;
329 void *pvFree = NULL;
330 rc = RTAsn1EncodeQueryRawBits(RTCrPkcs7Attributes_GetAsn1Core(&pSignerInfo->AuthenticatedAttributes),
331 &pbData, &cbData, &pvFree, pErrInfo);
332 if (RT_SUCCESS(rc))
333 {
334 uint8_t bSetOfTag = ASN1_TAG_SET | ASN1_TAGCLASS_UNIVERSAL | ASN1_TAGFLAG_CONSTRUCTED;
335 rc = RTCrDigestUpdate(hDigest, &bSetOfTag, sizeof(bSetOfTag)); /* Replace the implict tag with a SET-OF tag. */
336 if (RT_SUCCESS(rc))
337 rc = RTCrDigestUpdate(hDigest, pbData + sizeof(bSetOfTag), cbData - sizeof(bSetOfTag)); /* Skip the implicit tag. */
338 if (RT_SUCCESS(rc))
339 rc = RTCrDigestFinal(hDigest, NULL, 0);
340 RTMemTmpFree(pvFree);
341 }
342 }
343 return rc;
344}
345
346
347/**
348 * Find the handle to the digest given by the specified SignerInfo.
349 *
350 * @returns IPRT status code
351 * @param phDigest Where to return a referenced digest handle on
352 * success.
353 * @param pSignedData The signed data structure.
354 * @param pSignerInfo The signer info.
355 * @param pahDigests Array of content digests that runs parallel to
356 * pSignedData->DigestAlgorithms.
357 * @param pErrInfo Where to store additional error details,
358 * optional.
359 */
360static int rtCrPkcs7VerifyFindDigest(PRTCRDIGEST phDigest, PCRTCRPKCS7SIGNEDDATA pSignedData,
361 PCRTCRPKCS7SIGNERINFO pSignerInfo, PRTCRDIGEST pahDigests, PRTERRINFO pErrInfo)
362{
363 uint32_t iDigest = pSignedData->DigestAlgorithms.cItems;
364 while (iDigest-- > 0)
365 if (RTCrX509AlgorithmIdentifier_Compare(pSignedData->DigestAlgorithms.papItems[iDigest],
366 &pSignerInfo->DigestAlgorithm) == 0)
367 {
368 RTCRDIGEST hDigest = pahDigests[iDigest];
369 uint32_t cRefs = RTCrDigestRetain(hDigest);
370 AssertReturn(cRefs != UINT32_MAX, VERR_CR_PKCS7_INTERNAL_ERROR);
371 *phDigest = hDigest;
372 return VINF_SUCCESS;
373 }
374 *phDigest = NIL_RTCRDIGEST; /* Make gcc happy. */
375 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_DIGEST_ALGO_NOT_FOUND_IN_LIST,
376 "SignerInfo.DigestAlgorithm %s not found.",
377 pSignerInfo->DigestAlgorithm.Algorithm.szObjId);
378}
379
380
381/**
382 * Verifies one signature on a PKCS \#7 SignedData.
383 *
384 * @returns IPRT status code.
385 * @param pSignerInfo The signature.
386 * @param pSignedData The SignedData.
387 * @param hDigests The digest corresponding to
388 * pSignerInfo->DigestAlgorithm.
389 * @param fFlags Verficiation flags.
390 * @param hAdditionalCerts Store containing optional certificates,
391 * optional.
392 * @param hTrustedCerts Store containing trusted certificates, required.
393 * @param pValidationTime The time we're supposed to validate the
394 * certificates chains at.
395 * @param pfnVerifyCert Signing certificate verification callback.
396 * @param fVccFlags Signing certificate verification callback flags.
397 * @param pvUser Callback parameter.
398 * @param pErrInfo Where to store additional error details,
399 * optional.
400 */
401static int rtCrPkcs7VerifySignerInfo(PCRTCRPKCS7SIGNERINFO pSignerInfo, PCRTCRPKCS7SIGNEDDATA pSignedData,
402 RTCRDIGEST hDigest, uint32_t fFlags, RTCRSTORE hAdditionalCerts, RTCRSTORE hTrustedCerts,
403 PCRTTIMESPEC pValidationTime, PFNRTCRPKCS7VERIFYCERTCALLBACK pfnVerifyCert,
404 uint32_t fVccFlags, void *pvUser, PRTERRINFO pErrInfo)
405{
406 /*
407 * Locate the certificate used for signing.
408 */
409 PCRTCRCERTCTX pSignerCertCtx = NULL;
410 PCRTCRX509CERTIFICATE pSignerCert = NULL;
411 RTCRSTORE hSignerCertSrc = hTrustedCerts;
412 if (hSignerCertSrc != NIL_RTCRSTORE)
413 pSignerCertCtx = RTCrStoreCertByIssuerAndSerialNo(hSignerCertSrc, &pSignerInfo->IssuerAndSerialNumber.Name,
414 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
415 if (!pSignerCertCtx)
416 {
417 hSignerCertSrc = hAdditionalCerts;
418 if (hSignerCertSrc != NIL_RTCRSTORE)
419 pSignerCertCtx = RTCrStoreCertByIssuerAndSerialNo(hSignerCertSrc, &pSignerInfo->IssuerAndSerialNumber.Name,
420 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
421 }
422 if (pSignerCertCtx)
423 pSignerCert = pSignerCertCtx->pCert;
424 else
425 {
426 hSignerCertSrc = NULL;
427 pSignerCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSignedData->Certificates,
428 &pSignerInfo->IssuerAndSerialNumber.Name,
429 &pSignerInfo->IssuerAndSerialNumber.SerialNumber);
430 if (!pSignerCert)
431 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_SIGNED_DATA_CERT_NOT_FOUND,
432 "Certificate not found: serial=%.*Rhxs",
433 pSignerInfo->IssuerAndSerialNumber.SerialNumber.Asn1Core.cb,
434 pSignerInfo->IssuerAndSerialNumber.SerialNumber.Asn1Core.uData.pv);
435 }
436
437 /*
438 * If not a trusted certificate, we'll have to build certificate paths
439 * and verify them. If no valid paths are found, this step will fail.
440 */
441 int rc = VINF_SUCCESS;
442 if ( /*( hSignerCertSrc == NIL_RTCRSTORE
443 || hSignerCertSrc != hTrustedCerts )
444 &&*/ /** @todo 'hSignerCertSrc != hTrustedCerts' ain't making sense wrt pValidationTime */
445 !(fFlags & RTCRPKCS7VERIFY_SD_F_TRUST_ALL_CERTS) )
446 {
447 RTCRX509CERTPATHS hCertPaths;
448 rc = RTCrX509CertPathsCreate(&hCertPaths, pSignerCert);
449 if (RT_SUCCESS(rc))
450 {
451 rc = RTCrX509CertPathsSetValidTimeSpec(hCertPaths, pValidationTime);
452 if (hTrustedCerts != NIL_RTCRSTORE && RT_SUCCESS(rc))
453 rc = RTCrX509CertPathsSetTrustedStore(hCertPaths, hTrustedCerts);
454 if (hAdditionalCerts != NIL_RTCRSTORE && RT_SUCCESS(rc))
455 rc = RTCrX509CertPathsSetUntrustedStore(hCertPaths, hAdditionalCerts);
456 if (pSignedData->Certificates.cItems > 0 && RT_SUCCESS(rc))
457 rc = RTCrX509CertPathsSetUntrustedSet(hCertPaths, &pSignedData->Certificates);
458 if (RT_SUCCESS(rc))
459 {
460 rc = RTCrX509CertPathsBuild(hCertPaths, pErrInfo);
461 if (RT_SUCCESS(rc))
462 rc = RTCrX509CertPathsValidateAll(hCertPaths, NULL, pErrInfo);
463
464 /*
465 * Check that the certificate purpose and whatnot matches what
466 * is being signed.
467 */
468 if (RT_SUCCESS(rc))
469 rc = pfnVerifyCert(pSignerCert, hCertPaths, fVccFlags, pvUser, pErrInfo);
470 }
471 else
472 RTErrInfoSetF(pErrInfo, rc, "Error configuring path builder: %Rrc", rc);
473 RTCrX509CertPathsRelease(hCertPaths);
474 }
475 }
476 /*
477 * Check that the certificate purpose matches what is signed.
478 */
479 else
480 rc = pfnVerifyCert(pSignerCert, NIL_RTCRX509CERTPATHS, fVccFlags, pvUser, pErrInfo);
481
482 /*
483 * Reference the digest so we can safely replace with one on the
484 * authenticated attributes below.
485 */
486 if ( RT_SUCCESS(rc)
487 && RTCrDigestRetain(hDigest) != UINT32_MAX)
488 {
489 /*
490 * If there are authenticated attributes, we've got more work before we
491 * can verify the signature.
492 */
493 if ( RT_SUCCESS(rc)
494 && RTCrPkcs7Attributes_IsPresent(&pSignerInfo->AuthenticatedAttributes))
495 rc = rtCrPkcs7VerifySignerInfoAuthAttribs(pSignerInfo, pSignedData, &hDigest, fFlags, pErrInfo);
496
497 /*
498 * Verify the signature.
499 */
500 if (RT_SUCCESS(rc))
501 {
502 RTCRKEY hKey;
503 rc = RTCrKeyCreateFromSubjectPublicKeyInfo(&hKey, &pSignerCert->TbsCertificate.SubjectPublicKeyInfo,
504 pErrInfo, "pkcs7");
505 if (RT_SUCCESS(rc))
506 {
507 RTCRPKIXSIGNATURE hSignature;
508 rc = RTCrPkixSignatureCreateByObjId(&hSignature, &pSignerInfo->DigestEncryptionAlgorithm.Algorithm,
509 hKey, &pSignerInfo->DigestEncryptionAlgorithm.Parameters, false /*fSigning*/);
510 RTCrKeyRelease(hKey);
511 if (RT_SUCCESS(rc))
512 {
513 /** @todo Check that DigestEncryptionAlgorithm is compatible with hSignature
514 * (this is not vital). */
515 rc = RTCrPkixSignatureVerifyOctetString(hSignature, hDigest, &pSignerInfo->EncryptedDigest);
516 if (RT_FAILURE(rc))
517 rc = RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_SIGNATURE_VERIFICATION_FAILED,
518 "Signature verficiation failed: %Rrc", rc);
519 RTCrPkixSignatureRelease(hSignature);
520 }
521 else
522 rc = RTErrInfoSetF(pErrInfo, rc, "Failure to instantiate public key algorithm [IPRT]: %s (%s)",
523 pSignerCert->TbsCertificate.SubjectPublicKeyInfo.Algorithm.Algorithm.szObjId,
524 pSignerInfo->DigestEncryptionAlgorithm.Algorithm.szObjId);
525 }
526 }
527
528 RTCrDigestRelease(hDigest);
529 }
530 else if (RT_SUCCESS(rc))
531 rc = VERR_CR_PKCS7_INTERNAL_ERROR;
532 RTCrCertCtxRelease(pSignerCertCtx);
533 return rc;
534}
535
536
537/**
538 * Verifies a counter signature.
539 *
540 * @returns IPRT status code.
541 * @param pCounterSignerInfo The counter signature.
542 * @param pPrimarySignerInfo The primary signature (can be a counter
543 * signature too if nested).
544 * @param pSignedData The SignedData.
545 * @param fFlags Verficiation flags.
546 * @param hAdditionalCerts Store containing optional certificates,
547 * optional.
548 * @param hTrustedCerts Store containing trusted certificates, required.
549 * @param pValidationTime The time we're supposed to validate the
550 * certificates chains at.
551 * @param pfnVerifyCert Signing certificate verification callback.
552 * @param fVccFlags Signing certificate verification callback flags.
553 * @param pvUser Callback parameter.
554 * @param pErrInfo Where to store additional error details,
555 * optional.
556 */
557static int rtCrPkcs7VerifyCounterSignerInfo(PCRTCRPKCS7SIGNERINFO pCounterSignerInfo, PCRTCRPKCS7SIGNERINFO pPrimarySignerInfo,
558 PCRTCRPKCS7SIGNEDDATA pSignedData, uint32_t fFlags,
559 RTCRSTORE hAdditionalCerts, RTCRSTORE hTrustedCerts, PCRTTIMESPEC pValidationTime,
560 PFNRTCRPKCS7VERIFYCERTCALLBACK pfnVerifyCert, uint32_t fVccFlags,
561 void *pvUser, PRTERRINFO pErrInfo)
562{
563 /*
564 * Calculate the digest we need to verify.
565 */
566 RTCRDIGEST hDigest;
567 int rc = RTCrDigestCreateByObjId(&hDigest, &pCounterSignerInfo->DigestAlgorithm.Algorithm);
568 if (RT_SUCCESS(rc))
569 {
570 rc = RTCrDigestUpdate(hDigest,
571 pPrimarySignerInfo->EncryptedDigest.Asn1Core.uData.pv,
572 pPrimarySignerInfo->EncryptedDigest.Asn1Core.cb);
573 if (RT_SUCCESS(rc))
574 rc = RTCrDigestFinal(hDigest, NULL, 0);
575 if (RT_SUCCESS(rc))
576 {
577 /*
578 * Pass it on to the common SignerInfo verifier function.
579 */
580 rc = rtCrPkcs7VerifySignerInfo(pCounterSignerInfo, pSignedData, hDigest,
581 fFlags | RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE,
582 hAdditionalCerts, hTrustedCerts, pValidationTime,
583 pfnVerifyCert, fVccFlags, pvUser, pErrInfo);
584
585 }
586 else
587 rc = RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_DIGEST_CALC_ERROR,
588 "Hashing for counter signature failed unexpectedly: %Rrc", rc);
589 RTCrDigestRelease(hDigest);
590 }
591 else
592 rc = RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_DIGEST_CREATE_ERROR, "Error creating digest for '%s': %Rrc",
593 pCounterSignerInfo->DigestAlgorithm.Algorithm.szObjId, rc);
594
595 return rc;
596}
597
598
599/**
600 * Worker.
601 */
602static int rtCrPkcs7VerifySignedDataEx(PCRTCRPKCS7CONTENTINFO pContentInfo, uint32_t fFlags,
603 RTCRSTORE hAdditionalCerts, RTCRSTORE hTrustedCerts,
604 PCRTTIMESPEC pValidationTime,
605 PFNRTCRPKCS7VERIFYCERTCALLBACK pfnVerifyCert, void *pvUser,
606 void const *pvContent, size_t cbContent, PRTERRINFO pErrInfo)
607{
608 /*
609 * Check and adjust the input.
610 */
611 if (pfnVerifyCert)
612 AssertPtrReturn(pfnVerifyCert, VERR_INVALID_POINTER);
613 else
614 pfnVerifyCert = RTCrPkcs7VerifyCertCallbackDefault;
615
616 if (!RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
617 return RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_NOT_SIGNED_DATA, "Not PKCS #7 SignedData.");
618 PCRTCRPKCS7SIGNEDDATA pSignedData = pContentInfo->u.pSignedData;
619 int rc = RTCrPkcs7SignedData_CheckSanity(pSignedData, 0, pErrInfo, "");
620 if (RT_FAILURE(rc))
621 return rc;
622
623 /*
624 * Hash the content info.
625 */
626 /* Check that there aren't too many or too few hash algorithms for our
627 implementation and purposes. */
628 RTCRDIGEST ahDigests[2];
629 uint32_t const cDigests = pSignedData->DigestAlgorithms.cItems;
630 if (!cDigests) /** @todo we might have to support this... */
631 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_NO_DIGEST_ALGORITHMS, "No digest algorithms");
632
633 if (cDigests > RT_ELEMENTS(ahDigests))
634 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_TOO_MANY_DIGEST_ALGORITHMS,
635 "Too many digest algorithm: cAlgorithms=%u", cDigests);
636
637 /* Create the message digest calculators. */
638 rc = VERR_CR_PKCS7_NO_DIGEST_ALGORITHMS;
639 uint32_t i;
640 for (i = 0; i < cDigests; i++)
641 {
642 rc = RTCrDigestCreateByObjId(&ahDigests[i], &pSignedData->DigestAlgorithms.papItems[i]->Algorithm);
643 if (RT_FAILURE(rc))
644 {
645 rc = RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_DIGEST_CREATE_ERROR, "Error creating digest for '%s': %Rrc",
646 pSignedData->DigestAlgorithms.papItems[i]->Algorithm.szObjId, rc);
647 break;
648 }
649 }
650 if (RT_SUCCESS(rc))
651 {
652 /* Hash the content. */
653 for (i = 0; i < cDigests && RT_SUCCESS(rc); i++)
654 {
655 rc = RTCrDigestUpdate(ahDigests[i], pvContent, cbContent);
656 if (RT_SUCCESS(rc))
657 rc = RTCrDigestFinal(ahDigests[i], NULL, 0);
658 }
659 if (RT_SUCCESS(rc))
660 {
661 /*
662 * Validate the signed infos. The flags may select one particular entry.
663 */
664 RTTIMESPEC const GivenValidationTime = *pValidationTime;
665 uint32_t fPrimaryVccFlags = !(fFlags & RTCRPKCS7VERIFY_SD_F_USAGE_TIMESTAMPING)
666 ? RTCRPKCS7VCC_F_SIGNED_DATA : RTCRPKCS7VCC_F_TIMESTAMP;
667 uint32_t cItems = pSignedData->SignerInfos.cItems;
668 i = 0;
669 if (fFlags & RTCRPKCS7VERIFY_SD_F_HAS_SIGNER_INDEX)
670 {
671 i = (fFlags & RTCRPKCS7VERIFY_SD_F_SIGNER_INDEX_MASK) >> RTCRPKCS7VERIFY_SD_F_SIGNER_INDEX_SHIFT;
672 cItems = RT_MIN(cItems, i + 1);
673 }
674 rc = VERR_CR_PKCS7_NO_SIGNER_INFOS;
675 for (; i < cItems; i++)
676 {
677 PCRTCRPKCS7SIGNERINFO pSignerInfo = pSignedData->SignerInfos.papItems[i];
678 RTCRDIGEST hThisDigest = NIL_RTCRDIGEST; /* (gcc maybe incredible stupid.) */
679 rc = rtCrPkcs7VerifyFindDigest(&hThisDigest, pSignedData, pSignerInfo, ahDigests, pErrInfo);
680 if (RT_FAILURE(rc))
681 break;
682
683 /*
684 * See if we can find a trusted signing time.
685 * (Note that while it would make sense splitting up this function,
686 * we need to carry a lot of arguments around, so better not.)
687 */
688 bool fDone = false;
689 PCRTCRPKCS7SIGNERINFO pSigningTimeSigner = NULL;
690 PCRTASN1TIME pSignedTime;
691 while ( !fDone
692 && (pSignedTime = RTCrPkcs7SignerInfo_GetSigningTime(pSignerInfo, &pSigningTimeSigner)) != NULL)
693 {
694 RTTIMESPEC ThisValidationTime;
695 if (RT_LIKELY(RTTimeImplode(&ThisValidationTime, &pSignedTime->Time)))
696 {
697 if (pSigningTimeSigner == pSignerInfo)
698 {
699 if (fFlags & RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY)
700 continue;
701 rc = rtCrPkcs7VerifySignerInfo(pSignerInfo, pSignedData, hThisDigest, fFlags,
702 hAdditionalCerts, hTrustedCerts, &ThisValidationTime,
703 pfnVerifyCert, fPrimaryVccFlags | RTCRPKCS7VCC_F_TIMESTAMP,
704 pvUser, pErrInfo);
705 }
706 else
707 {
708 rc = VINF_SUCCESS;
709 if (!(fFlags & RTCRPKCS7VERIFY_SD_F_USE_SIGNING_TIME_UNVERIFIED))
710 rc = rtCrPkcs7VerifyCounterSignerInfo(pSigningTimeSigner, pSignerInfo, pSignedData,
711 fFlags & ~RTCRPKCS7VERIFY_SD_F_UPDATE_VALIDATION_TIME,
712 hAdditionalCerts, hTrustedCerts, &ThisValidationTime,
713 pfnVerifyCert, RTCRPKCS7VCC_F_TIMESTAMP, pvUser, pErrInfo);
714 if (RT_SUCCESS(rc))
715 rc = rtCrPkcs7VerifySignerInfo(pSignerInfo, pSignedData, hThisDigest, fFlags, hAdditionalCerts,
716 hTrustedCerts, &ThisValidationTime,
717 pfnVerifyCert, fPrimaryVccFlags, pvUser, pErrInfo);
718 }
719 fDone = RT_SUCCESS(rc)
720 || (fFlags & RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT);
721 if ((fFlags & RTCRPKCS7VERIFY_SD_F_UPDATE_VALIDATION_TIME) && fDone)
722 *(PRTTIMESPEC)pValidationTime = ThisValidationTime;
723 }
724 else
725 {
726 rc = RTErrInfoSet(pErrInfo, VERR_INTERNAL_ERROR_3, "RTTimeImplode failed");
727 fDone = true;
728 }
729 }
730
731 /*
732 * If not luck, check for microsoft timestamp counter signatures.
733 */
734 if (!fDone && !(fFlags & RTCRPKCS7VERIFY_SD_F_IGNORE_MS_TIMESTAMP))
735 {
736 PCRTCRPKCS7CONTENTINFO pSignedTimestamp = NULL;
737 pSignedTime = RTCrPkcs7SignerInfo_GetMsTimestamp(pSignerInfo, &pSignedTimestamp);
738 if (pSignedTime)
739 {
740 RTTIMESPEC ThisValidationTime;
741 if (RT_LIKELY(RTTimeImplode(&ThisValidationTime, &pSignedTime->Time)))
742 {
743 rc = VINF_SUCCESS;
744 if (!(fFlags & RTCRPKCS7VERIFY_SD_F_USE_MS_TIMESTAMP_UNVERIFIED))
745 rc = RTCrPkcs7VerifySignedData(pSignedTimestamp,
746 fFlags | RTCRPKCS7VERIFY_SD_F_IGNORE_MS_TIMESTAMP
747 | RTCRPKCS7VERIFY_SD_F_USAGE_TIMESTAMPING,
748 hAdditionalCerts, hTrustedCerts, &ThisValidationTime,
749 pfnVerifyCert, pvUser, pErrInfo);
750
751 if (RT_SUCCESS(rc))
752 rc = rtCrPkcs7VerifySignerInfo(pSignerInfo, pSignedData, hThisDigest, fFlags, hAdditionalCerts,
753 hTrustedCerts, &ThisValidationTime,
754 pfnVerifyCert, fPrimaryVccFlags, pvUser, pErrInfo);
755 fDone = RT_SUCCESS(rc)
756 || (fFlags & RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT);
757 if ((fFlags & RTCRPKCS7VERIFY_SD_F_UPDATE_VALIDATION_TIME) && fDone)
758 *(PRTTIMESPEC)pValidationTime = ThisValidationTime;
759 }
760 else
761 {
762 rc = RTErrInfoSet(pErrInfo, VERR_INTERNAL_ERROR_3, "RTTimeImplode failed");
763 fDone = true;
764 }
765
766 }
767 }
768
769 /*
770 * No valid signing time found, use the one specified instead.
771 */
772 if (!fDone)
773 rc = rtCrPkcs7VerifySignerInfo(pSignerInfo, pSignedData, hThisDigest, fFlags, hAdditionalCerts, hTrustedCerts,
774 &GivenValidationTime, pfnVerifyCert, fPrimaryVccFlags, pvUser, pErrInfo);
775 RTCrDigestRelease(hThisDigest);
776 if (RT_FAILURE(rc))
777 break;
778 }
779 }
780 else
781 rc = RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_DIGEST_CALC_ERROR,
782 "Hashing content failed unexpectedly (i=%u): %Rrc", i, rc);
783
784 /* Clean up digests. */
785 i = cDigests;
786 }
787 while (i-- > 0)
788 {
789 int rc2 = RTCrDigestRelease(ahDigests[i]);
790 AssertRC(rc2);
791 }
792
793
794#ifdef IPRT_WITH_OPENSSL
795 /*
796 * Verify using OpenSSL and combine the results (should be identical).
797 */
798 /** @todo figure out how to verify MS timstamp signatures using OpenSSL. */
799 if (fFlags & RTCRPKCS7VERIFY_SD_F_USAGE_TIMESTAMPING)
800 return rc;
801 /** @todo figure out if we can verify just one signer info item using OpenSSL. */
802 if (!(fFlags & RTCRPKCS7VERIFY_SD_F_HAS_SIGNER_INDEX) && pSignedData->SignerInfos.cItems > 1)
803 return rc;
804
805 int rcOssl = rtCrPkcs7VerifySignedDataUsingOpenSsl(pContentInfo, fFlags, hAdditionalCerts, hTrustedCerts,
806 pvContent, cbContent, RT_SUCCESS(rc) ? pErrInfo : NULL);
807 if (RT_SUCCESS(rcOssl) && RT_SUCCESS(rc))
808 return rc;
809// AssertMsg(RT_FAILURE_NP(rcOssl) && RT_FAILURE_NP(rc), ("%Rrc, %Rrc\n", rcOssl, rc));
810 if (RT_FAILURE(rc))
811 return rc;
812 return rcOssl;
813#else
814 return rc;
815#endif
816}
817
818
819RTDECL(int) RTCrPkcs7VerifySignedData(PCRTCRPKCS7CONTENTINFO pContentInfo, uint32_t fFlags,
820 RTCRSTORE hAdditionalCerts, RTCRSTORE hTrustedCerts,
821 PCRTTIMESPEC pValidationTime, PFNRTCRPKCS7VERIFYCERTCALLBACK pfnVerifyCert, void *pvUser,
822 PRTERRINFO pErrInfo)
823{
824 /*
825 * Find the content and pass it on to common worker.
826 */
827 if (!RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
828 return RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_NOT_SIGNED_DATA, "Not PKCS #7 SignedData.");
829
830 /* Exactly what the content is, is for some stupid reason unnecessarily complicated. */
831 PCRTCRPKCS7SIGNEDDATA pSignedData = pContentInfo->u.pSignedData;
832 void const *pvContent = pSignedData->ContentInfo.Content.Asn1Core.uData.pv;
833 uint32_t cbContent = pSignedData->ContentInfo.Content.Asn1Core.cb;
834 if (pSignedData->ContentInfo.Content.pEncapsulated)
835 {
836 pvContent = pSignedData->ContentInfo.Content.pEncapsulated->uData.pv;
837 cbContent = pSignedData->ContentInfo.Content.pEncapsulated->cb;
838 }
839
840 return rtCrPkcs7VerifySignedDataEx(pContentInfo, fFlags, hAdditionalCerts, hTrustedCerts, pValidationTime,
841 pfnVerifyCert, pvUser, pvContent, cbContent, pErrInfo);
842}
843
844
845RTDECL(int) RTCrPkcs7VerifySignedDataWithExternalData(PCRTCRPKCS7CONTENTINFO pContentInfo, uint32_t fFlags,
846 RTCRSTORE hAdditionalCerts, RTCRSTORE hTrustedCerts,
847 PCRTTIMESPEC pValidationTime,
848 PFNRTCRPKCS7VERIFYCERTCALLBACK pfnVerifyCert, void *pvUser,
849 void const *pvData, size_t cbData, PRTERRINFO pErrInfo)
850{
851 /*
852 * Require 'data' as inner content type.
853 */
854 if (!RTCrPkcs7ContentInfo_IsSignedData(pContentInfo))
855 return RTErrInfoSet(pErrInfo, VERR_CR_PKCS7_NOT_SIGNED_DATA, "Not PKCS #7 SignedData.");
856 PCRTCRPKCS7SIGNEDDATA pSignedData = pContentInfo->u.pSignedData;
857
858 if (RTAsn1ObjId_CompareWithString(&pSignedData->ContentInfo.ContentType, RTCR_PKCS7_DATA_OID) != 0)
859 return RTErrInfoSetF(pErrInfo, VERR_CR_PKCS7_NOT_DATA,
860 "The signedData content type is %s, expected 'data' (%s)",
861 pSignedData->ContentInfo.ContentType.szObjId, RTCR_PKCS7_DATA_OID);
862
863 return rtCrPkcs7VerifySignedDataEx(pContentInfo, fFlags, hAdditionalCerts, hTrustedCerts, pValidationTime,
864 pfnVerifyCert, pvUser, pvData, cbData, pErrInfo);
865}
866
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette