Botan 3.14.1
Crypto and TLS for C&
x509path.cpp
Go to the documentation of this file.
1/*
2* X.509 Certificate Path Validation
3* (C) 2010,2011,2012,2014,2016,2026 Jack Lloyd
4* (C) 2017 Fabian Weissberg, Rohde & Schwarz Cybersecurity
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/x509path.h>
10
11#include <botan/assert.h>
12#include <botan/ocsp.h>
13#include <botan/pk_keys.h>
14#include <botan/x509_ext.h>
15#include <botan/internal/concat_util.h>
16#include <botan/internal/x509_utils.h>
17#include <algorithm>
18#include <chrono>
19#include <iterator>
20#include <set>
21#include <span>
22#include <sstream>
23#include <string>
24#include <unordered_set>
25#include <vector>
26
27#if defined(BOTAN_HAS_ONLINE_REVOCATION_CHECKS)
28 #include <botan/uri.h>
29 #include <botan/internal/http_util.h>
30 #include <future>
31#endif
32
33namespace Botan {
34
35namespace {
36
37constexpr size_t PathBuildingDfsBudget = 300;
38constexpr size_t PathBuildingMaximumChainLength = 16;
39constexpr size_t PathBuildingVerificationBudget = 200;
40constexpr size_t PathBuildingMaxPathsExamined = 50;
41
42struct CrlApplicability {
43 bool usable; // RFC 5280 6.3.3(b) gate: can be searched for a revocation entry
44 bool full_coverage; // can also serve as VALID_CRL_CHECKED non-revocation evidence
45};
46
47/*
48* Single-pass evaluation of how this CRL applies to this cert. Combines:
49* - 6.3.3(b)(1)/(b)(2)(i) name match (via distribution_point_match)
50* - 6.3.3(b)(2)(ii)-(iv) IDP scope booleans
51* - the (currently unsupported) indirect-CRL gate from (f)-(g)
52* - 6.3.3(d)(3) DP-reasons / IDP-onlySomeReasons full-coverage check
53* Computing the two answers together keeps their matching rules in sync and
54* avoids re-walking the cert's CDP. `full_coverage` is reported only when
55* `usable` is true; reason-mask accumulation across multiple CRLs per
56* 6.3.3(d)-(l) is not implemented, so a reason-limited CRL never alone
57* certifies full coverage.
58*/
59CrlApplicability crl_applicability_for(const X509_CRL& crl, const X509_Certificate& subject) {
60 /*
61 * RFC 5280 6.3.3
62 *
63 * (b) Verify the issuer and scope of the complete CRL as follows:
64 *
65 * (1) If the DP includes cRLIssuer, then verify that the issuer
66 * field in the complete CRL matches cRLIssuer in the DP and
67 * that the complete CRL contains an issuing distribution
68 * point extension with the indirectCRL boolean asserted.
69 * Otherwise, verify that the CRL issuer matches the
70 * certificate issuer.
71 *
72 * (2) If the complete CRL includes an issuing distribution point
73 * (IDP) CRL extension, check the following:
74 *
75 * (i) If the distribution point name is present in the IDP CRL
76 * extension and the distribution field is present in the
77 * DP, then verify that one of the names in the IDP matches
78 * one of the names in the DP. If the distribution point
79 * name is present in the IDP CRL extension and the
80 * distribution field is omitted from the DP, then verify
81 * that one of the names in the IDP matches one of the names
82 * in the cRLIssuer field of the DP.
83 *
84 * (ii) If the onlyContainsUserCerts boolean is asserted in the
85 * IDP CRL extension, verify that the certificate does not
86 * include the basic constraints extension with the cA
87 * boolean asserted.
88 *
89 * (iii) If the onlyContainsCACerts boolean is asserted in the
90 * IDP CRL extension, verify that the certificate
91 * includes the basic constraints extension with the cA
92 * boolean asserted.
93 *
94 * (iv) Verify that the onlyContainsAttributeCerts boolean is not
95 * asserted.
96 */
97 const auto match = distribution_point_match(crl, subject);
98 if(!match.any) {
99 return {false, false};
100 }
101
102 const auto* idp = crl.extensions().get_extension_object_as<Cert_Extension::CRL_Issuing_Distribution_Point>();
103 if(idp == nullptr) {
104 return {true, match.any_with_absent_reasons};
105 }
106
107 // X509_Certificate::is_CA_cert has additional gates (KU + EKU) besides the basicConstraints
108 const bool basicConstraints_isCa = [&]() {
109 if(const auto* ext = subject.v3_extensions().get_extension_object_as<Cert_Extension::Basic_Constraints>()) {
110 return ext->get_is_ca();
111 } else {
112 return false;
113 }
114 }();
115
116 // step (ii)
117 if(idp->only_contains_user_certs() && basicConstraints_isCa) {
118 return {false, false};
119 }
120
121 // step (iii)
122 if(idp->only_contains_ca_certs() && !basicConstraints_isCa) {
123 return {false, false};
124 }
125
126 // step (iv)
127 if(idp->only_contains_attribute_certs()) {
128 return {false, false};
129 }
130
131 /*
132 * RFC 5280 6.3.3(f)-(g) requires validating the cRLIssuer's certification
133 * path and verifying the CRL signature with that key when indirectCRL is
134 * asserted. PKIX::check_crl currently verifies the CRL signature against
135 * the cert's direct issuer key only, so an indirect CRL cannot be
136 * evaluated correctly. Reject as inapplicable rather than risk a
137 * misleading status.
138 */
139 if(idp->indirect_crl()) {
140 return {false, false};
141 }
142
143 /*
144 * Full reason coverage additionally requires the IDP to omit onlySomeReasons.
145 * RFC 5280 6.3.3(d) computes the reason mask per (DP, IDP) pair, so a CRL
146 * that is reason-limited on either side cannot alone prove non-revocation
147 * across every reason; reason-mask accumulation across multiple CRLs per
148 * 6.3.3(d)-(l) is not yet implemented.
149 */
150 const bool only_some_reasons = idp->only_some_reasons().has_value();
151 const bool full = match.any_with_absent_reasons && !only_some_reasons;
152 return {true, full};
153}
154
155/**
156 * Lazy DFS iterator that yields certificate paths one at a time.
157 *
158 * Build all possible certificate paths from the end certificate to self-signed trusted roots.
159 *
160 * Basically, a DFS is performed starting from the end certificate. A stack (vector)
161 * serves to control the DFS. At the beginning of each iteration, a pair is popped from
162 * the stack that contains (1) the next certificate to add to the path (2) a bool that
163 * indicates if the certificate is part of a trusted certstore. Ideally, we follow the
164 * unique issuer of the current certificate until a trusted root is reached. However, the
165 * issuer DN + authority key id need not be unique among the certificates used for
166 * building the path. In such a case, we consider all the matching issuers by pushing
167 * <IssuerCert, trusted?> on the stack for each of them.
168 *
169 * Each call to next() resumes the search and returns the next discovered path, or nullopt
170 * when the search space is exhausted.
171*/
172class CertificatePathBuilder final {
173 public:
174 CertificatePathBuilder(const std::vector<Certificate_Store*>& trusted_certstores,
175 const X509_Certificate& end_entity,
176 std::span<const X509_Certificate> end_entity_extra,
177 size_t dfs_budget,
178 bool require_self_signed) :
179 m_trusted_certstores(trusted_certstores),
180 m_require_self_signed(require_self_signed),
181 m_dfs_budget(dfs_budget) {
182 BOTAN_ARG_CHECK(m_dfs_budget > 0, "DFS budget must be non-zero");
183
184 if(std::ranges::any_of(trusted_certstores, [](auto* ptr) { return ptr == nullptr; })) {
185 throw Invalid_Argument("Certificate store list must not contain nullptr");
186 }
187
188 for(const auto& cert : end_entity_extra) {
189 if(!cert_in_any_trusted_store(cert)) {
190 m_ee_extras.add_certificate(cert);
191 }
192 }
193
194 m_stack.push_back({end_entity, cert_in_any_trusted_store(end_entity)});
195 }
196
197 std::optional<std::vector<X509_Certificate>> next() {
198 while(!m_stack.empty()) {
199 if(m_dfs_budget == 0) {
200 // Intentionally overwrite any previous builder error
202 return std::nullopt;
203 }
204
205 BOTAN_ASSERT_NOMSG(m_dfs_budget > 0);
206 m_dfs_budget -= 1;
207
208 auto [last, trusted] = std::move(m_stack.back()); // move before pop_back
209 m_stack.pop_back();
210
211 // Found a deletion marker that guides the DFS, backtracking
212 if(!last.has_value()) {
213 m_certs_seen.erase(m_path_so_far.back().tag());
214 m_path_so_far.pop_back();
215 continue;
216 }
217
218 // Certificate already seen in this path?
219 const auto tag = last->tag();
220 if(m_certs_seen.contains(tag)) {
221 if(!m_error.has_value()) {
223 }
224 continue;
225 }
226
227 // A valid path has been discovered. It includes endpoints that may end
228 // with either a self-signed or a non-self-signed certificate. For
229 // certificates that are not self-signed, additional paths could
230 // potentially extend from the current one.
231 if(trusted) {
232 auto path = m_path_so_far;
233 path.push_back(*last);
234 push_issuers(*last);
235
236 if(!m_require_self_signed || last->is_self_signed()) {
237 return path;
238 }
239
240 /*
241 This unconditionally overwrites the error because it's likely the most
242 informative error in this context - we found a path that seemed entirely
243 suitable, except that self-signed roots are required so it was skipped.
244 */
246 continue;
247 }
248
249 if(last->is_self_signed()) {
250 if(!m_error.has_value()) {
252 }
253 continue;
254 }
255
256 push_issuers(*last);
257 }
258
259 return std::nullopt;
260 }
261
262 /**
263 * Return the first error encountered during path building
264 *
265 * Only used as a last resort if there were no successful paths
266 */
267 Certificate_Status_Code error() const {
268 if(m_error.has_value()) {
269 // Confirm it is an actual error code and not accidentally OK...
270 BOTAN_ASSERT_NOMSG(static_cast<uint32_t>(m_error.value()) >= 3000);
271 return m_error.value();
272 } else {
274 }
275 }
276
277 private:
278 bool cert_in_any_trusted_store(const X509_Certificate& cert) const {
279 return std::ranges::any_of(m_trusted_certstores,
280 [&](const Certificate_Store* store) { return store->contains(cert); });
281 }
282
283 void push_issuers(const X509_Certificate& cert) {
284 const X509_DN& issuer_dn = cert.issuer_dn();
285 const std::vector<uint8_t>& auth_key_id = cert.authority_key_id();
286
287 // Common case is a single trusted store; steal its buffer and only
288 // move-append if multiple stores return matches.
289 std::vector<X509_Certificate> trusted_issuers;
290 for(const Certificate_Store* store : m_trusted_certstores) {
291 auto new_issuers = store->find_all_certs(issuer_dn, auth_key_id);
292 if(trusted_issuers.empty()) {
293 trusted_issuers = std::move(new_issuers);
294 } else {
295 trusted_issuers.insert(trusted_issuers.end(),
296 std::make_move_iterator(new_issuers.begin()),
297 std::make_move_iterator(new_issuers.end()));
298 }
299 }
300
301 // Search the supplemental certs
302 const std::vector<X509_Certificate> misc_issuers = m_ee_extras.find_all_certs(issuer_dn, auth_key_id);
303
304 // If we could not find any issuers, the current path ends here
305 if(trusted_issuers.empty() && misc_issuers.empty()) {
306 if(!m_error.has_value()) {
308 }
309 return;
310 }
311
312 m_path_so_far.push_back(cert);
313 m_certs_seen.emplace(cert.tag());
314
315 // Push a deletion marker on the stack for backtracking later
316 m_stack.push_back({std::nullopt, false});
317
318 // The stack is LIFO so push trusted issuers last; preferring them
319 // keeps the DFS from wandering through cross-signed CAs when the
320 // trust anchor issued the certificate directly.
321 for(const auto& misc : misc_issuers) {
322 m_stack.push_back({misc, false});
323 }
324 for(const auto& trusted_cert : trusted_issuers) {
325 m_stack.push_back({trusted_cert, true});
326 }
327 }
328
329 const std::vector<Certificate_Store*> m_trusted_certstores;
330 const bool m_require_self_signed;
331 Certificate_Store_In_Memory m_ee_extras;
332 std::vector<std::pair<std::optional<X509_Certificate>, bool>> m_stack;
333 std::vector<X509_Certificate> m_path_so_far;
334 std::unordered_set<X509_Certificate::Tag, X509_Certificate::TagHash> m_certs_seen;
335 std::optional<Certificate_Status_Code> m_error;
336 size_t m_dfs_budget = 0;
337};
338
339} // namespace
340
341/*
342* PKIX path validation
343*/
344CertificatePathStatusCodes PKIX::check_chain(const std::vector<X509_Certificate>& cert_path,
345 std::chrono::system_clock::time_point ref_time,
346 std::string_view hostname,
347 Usage_Type usage,
348 const Path_Validation_Restrictions& restrictions) {
349 if(cert_path.empty()) {
350 throw Invalid_Argument("PKIX::check_chain cert_path empty");
351 }
352
353 const bool is_end_entity_trust_anchor = (cert_path.size() == 1);
354
355 const X509_Time validation_time(ref_time);
356
357 CertificatePathStatusCodes cert_status(cert_path.size());
358
359 // Before anything else verify the entire chain of signatures
360 // starting from the certificate issued by the trust anchor and
361 // working towards the leaf. This precludes denial of service
362 // attacks based on long certificate chains which are valid except
363 // for the final forged (invalid) signature purportedly by the
364 // trust root.
365 //
366 // The trust anchor's own signature is not checked. RFC 5280 6.1.1:
367 // "The trust anchor information is trusted because it was
368 // delivered to the path processing procedure by some trustworthy
369 // out-of-band procedure."
370 for(size_t i = cert_path.size() - 1; i-- > 0;) {
371 std::set<Certificate_Status_Code>& status = cert_status.at(i);
372
373 const X509_Certificate& subject = cert_path[i];
374 const X509_Certificate& issuer = cert_path[i + 1];
375
376 // Check the signature algorithm is known
377 if(!subject.signature_algorithm().oid().registered_oid()) {
379 } else {
380 std::unique_ptr<Public_Key> issuer_key;
381 try {
382 issuer_key = issuer.subject_public_key();
383 } catch(...) {
385 }
386
387 if(issuer_key) {
388 if(issuer_key->estimated_strength() < restrictions.minimum_key_strength()) {
390 }
391
392 const auto sig_status = subject.verify_signature(*issuer_key);
393
394 if(sig_status.first != Certificate_Status_Code::VERIFIED) {
395 status.insert(sig_status.first);
396 } else {
397 // Signature is valid, check if hash used was acceptable
398 const std::string hash_used_for_signature = sig_status.second;
399 BOTAN_ASSERT_NOMSG(!hash_used_for_signature.empty());
400 const auto& trusted_hashes = restrictions.trusted_hashes();
401
402 if(!trusted_hashes.empty() && !trusted_hashes.contains(hash_used_for_signature)) {
404 }
405 }
406 }
407 }
408
409 // If any of the signatures were invalid, return immediately; we know the
410 // chain is invalid and signature failure is always considered the most
411 // critical result. This does mean other problems in the certificate (eg
412 // expired) will not be reported, but we'd have to assume any such data is
413 // anyway arbitrary considering we couldn't verify the signature chain
414 for(const auto s : status) {
415 // This ignores errors relating to the key or hash being weak since
416 // these are somewhat advisory
417 if(static_cast<uint32_t>(s) >= 5000) {
418 return cert_status;
419 }
420 }
421 }
422
423 if(!hostname.empty() && !cert_path[0].matches_dns_name(hostname)) {
424 cert_status[0].insert(Certificate_Status_Code::CERT_NAME_NOMATCH);
425 }
426
427 if(!cert_path[0].allowed_usage(usage)) {
428 if(usage == Usage_Type::OCSP_RESPONDER) {
430 }
431 cert_status[0].insert(Certificate_Status_Code::INVALID_USAGE);
432 }
433
434 if(cert_path[0].has_constraints(Key_Constraints::KeyCertSign) && cert_path[0].is_CA_cert() == false) {
435 /*
436 "If the keyCertSign bit is asserted, then the cA bit in the
437 basic constraints extension (Section 4.2.1.9) MUST also be
438 asserted." - RFC 5280
439
440 We don't bother doing this check on the rest of the path since they
441 must have the cA bit asserted or the validation will fail anyway.
442 */
443 cert_status[0].insert(Certificate_Status_Code::INVALID_USAGE);
444 }
445
446 for(size_t i = 0; i != cert_path.size(); ++i) {
447 std::set<Certificate_Status_Code>& status = cert_status.at(i);
448
449 const bool at_trust_anchor = (i == cert_path.size() - 1);
450
451 const X509_Certificate& subject = cert_path[i];
452 const auto issuer = [&]() -> std::optional<X509_Certificate> {
453 if(!at_trust_anchor) {
454 return cert_path[i + 1];
455 } else if(subject.is_self_signed()) {
456 return cert_path[i];
457 } else {
458 return {}; // Non self-signed trust anchors have no checkable issuers.
459 }
460 }();
461
462 if(restrictions.require_self_signed_trust_anchors() && !issuer.has_value()) {
464 }
465
466 // This should never happen; it indicates a bug in path building
467 if(issuer.has_value() && subject.issuer_dn() != issuer->subject_dn()) {
469 }
470
471 // Check the serial number
472 if(subject.serial().is_negative()) {
474 }
475
476 // Check the subject's DN components' length
477
478 for(const auto& rdn : subject.subject_dn().rdns()) {
479 for(const auto& ava : rdn) {
480 const size_t dn_ub = X509_DN::lookup_ub(ava.first);
481 if(dn_ub > 0 && ava.second.size() > dn_ub) {
483 }
484 }
485 }
486
487 // If so configured, allow trust anchors outside the validity period with
488 // a warning rather than a hard error
489 const bool enforce_validity_period = !at_trust_anchor || !restrictions.ignore_trusted_root_time_range();
490 // Check all certs for valid time range
491 if(validation_time < subject.not_before()) {
492 if(enforce_validity_period) {
494 } else {
495 status.insert(Certificate_Status_Code::TRUSTED_CERT_NOT_YET_VALID); // only warn
496 }
497 }
498
499 if(validation_time > subject.not_after()) {
500 if(enforce_validity_period) {
502 } else {
503 status.insert(Certificate_Status_Code::TRUSTED_CERT_HAS_EXPIRED); // only warn
504 }
505 }
506
507 // Check issuer constraints
508 if(issuer.has_value() && !issuer->is_CA_cert() && !is_end_entity_trust_anchor) {
510 }
511
512 // Check cert extensions
513
514 if(subject.x509_version() == 1) {
515 if(subject.v2_issuer_key_id().empty() == false || subject.v2_subject_key_id().empty() == false) {
517 }
518 }
519
520 const Extensions& extensions = subject.v3_extensions();
521 if(subject.x509_version() < 3 && !extensions.get_extension_oids().empty()) {
523 }
524
525 extensions.validate(subject, issuer, cert_path, cert_status, i);
526 }
527
528 // path len check
529 size_t max_path_length = cert_path.size();
530 for(size_t i = cert_path.size() - 1; i > 0; --i) {
531 std::set<Certificate_Status_Code>& status = cert_status.at(i);
532 const X509_Certificate& subject = cert_path[i];
533
534 /*
535 * If the certificate was not self-issued, verify that max_path_length is
536 * greater than zero and decrement max_path_length by 1.
537 */
538 if(subject.subject_dn() != subject.issuer_dn()) {
539 if(max_path_length > 0) {
540 max_path_length -= 1;
541 } else {
543 }
544 }
545
546 /*
547 * If pathLenConstraint is present in the certificate and is less than max_path_length,
548 * set max_path_length to the value of pathLenConstraint.
549 */
550 if(auto path_len_constraint = subject.path_length_constraint()) {
551 max_path_length = std::min(max_path_length, *path_len_constraint);
552 }
553 }
554
555 return cert_status;
556}
557
558namespace {
559
560Certificate_Status_Code verify_ocsp_signing_cert(const X509_Certificate& signing_cert,
561 const X509_Certificate& ca,
562 const std::vector<X509_Certificate>& extra_certs,
563 const std::vector<Certificate_Store*>& certstores,
564 std::chrono::system_clock::time_point ref_time,
565 const Path_Validation_Restrictions& restrictions) {
566 // RFC 6960 4.2.2.2
567 // [Applications] MUST reject the response if the certificate
568 // required to validate the signature on the response does not
569 // meet at least one of the following criteria:
570 //
571 // 1. Matches a local configuration of OCSP signing authority
572 // for the certificate in question, or
573 if(const auto* trusted_responders = restrictions.trusted_ocsp_responders()) {
574 if(trusted_responders->contains(signing_cert)) {
576 }
577 }
578
579 // RFC 6960 4.2.2.2
580 //
581 // 2. Is the certificate of the CA that issued the certificate
582 // in question, or
583 if(signing_cert == ca) {
585 }
586
587 // RFC 6960 4.2.2.2
588 //
589 // 3. Includes a value of id-kp-OCSPSigning in an extended key
590 // usage extension and is issued by the CA that issued the
591 // certificate in question as stated above.
592
593 // Verify the delegated responder was issued by the CA that issued
594 // the certificate in question (the EKU and signature chain are
595 // verified by the path validation below).
596 //
597 // RFC 6960 4.2.2.2 again
598 //
599 // Systems relying on OCSP responses MUST recognize a delegation
600 // certificate as being issued by the CA that issued the
601 // certificate in question only if the delegation certificate
602 // and the certificate being checked for revocation were signed
603 // by the same key.
604 if(signing_cert.issuer_dn() != ca.subject_dn()) {
606 } else {
607 // If both key identifiers are available, verify they match to
608 // handle CAs that share a subject DN but have different keys
609 // (eg re-keyed or cross-certified CAs).
610 const auto& aki = signing_cert.authority_key_id();
611 const auto& ski = ca.subject_key_id();
612 if(!aki.empty() && !ski.empty() && aki != ski) {
614 }
615 }
616
617 try {
618 const auto ca_pub_key = ca.subject_public_key();
619 if(!ca_pub_key || !signing_cert.check_signature(*ca_pub_key)) {
621 }
622 } catch(...) {
624 }
625
626 // TODO: Implement OCSP revocation check of OCSP signer certificate
627 // Note: This needs special care to prevent endless loops on specifically
628 // forged chains of OCSP responses referring to each other.
629 //
630 // RFC 6960 4.2.2.2.1 seems to imply that generally OCSP checking of OCSP
631 // signers is not realistic; it suggests either using the nocheck extension,
632 // "using CRL Distribution Points if the check should be done using CRLs",
633 // or just punts with
634 // A CA may choose not to specify any method of revocation checking
635 // for the responder's certificate, in which case it would be up to
636 // the OCSP client's local security policy to decide whether that
637 // certificate should be checked for revocation or not.
638 //
639 // Currently, we're disabling OCSP-based revocation checks by setting the
640 // timeout to 0. Additionally, the library's API would not allow an
641 // application to pass in the required "second order" OCSP responses. I.e.
642 // "second order" OCSP checks would need to rely on `check_ocsp_online()`
643 // which is not an option for some applications (e.g. that require a proxy
644 // for external HTTP requests).
645 const auto ocsp_timeout = std::chrono::milliseconds::zero();
646 const auto relaxed_restrictions =
647 Path_Validation_Restrictions(false /* do not enforce revocation data */,
648 restrictions.minimum_key_strength(),
649 false /* OCSP is not available, so don't try for intermediates */,
650 restrictions.trusted_hashes(),
651 /* max_ocsp_age */ std::chrono::seconds(0),
652 /* trusted_responders */ {},
653 restrictions.ignore_trusted_root_time_range(),
655 restrictions.accept_ocsp_softfail());
656
657 const auto validation_result = x509_path_validate(concat(std::vector{signing_cert}, extra_certs),
658 relaxed_restrictions,
659 certstores,
660 {} /* hostname */,
662 ref_time,
663 ocsp_timeout);
664
665 return validation_result.result();
666}
667
668std::set<Certificate_Status_Code> evaluate_ocsp_response(const OCSP::Response& ocsp_response,
669 const X509_Certificate& subject,
670 const X509_Certificate& ca,
671 const std::vector<X509_Certificate>& cert_path,
672 const std::vector<Certificate_Store*>& certstores,
673 std::chrono::system_clock::time_point ref_time,
674 const Path_Validation_Restrictions& restrictions) {
675 // Handle softfail conditions (eg. OCSP unavailable)
676 if(auto dummy_status = ocsp_response.dummy_status()) {
677 return {dummy_status.value()};
678 }
679
680 // Find the certificate that signed this OCSP response
681 auto signing_cert = ocsp_response.find_signing_certificate(ca, restrictions.trusted_ocsp_responders());
682 if(!signing_cert) {
684 }
685
686 // Verify the signing certificate is trusted
687 const auto cert_status = verify_ocsp_signing_cert(
688 signing_cert.value(), ca, concat(ocsp_response.certificates(), cert_path), certstores, ref_time, restrictions);
691 }
692
693 // Verify the cryptographic signature on the OCSP response
694 const auto sig_status = ocsp_response.verify_signature(signing_cert.value(), restrictions);
696 return {sig_status};
697 }
698
699 // All checks passed, return the certificate's revocation status
700 return {ocsp_response.status_for(ca, subject, ref_time, restrictions.max_ocsp_age())};
701}
702
703} // namespace
704
705CertificatePathStatusCodes PKIX::check_ocsp(const std::vector<X509_Certificate>& cert_path,
706 const std::vector<std::optional<OCSP::Response>>& ocsp_responses,
707 const std::vector<Certificate_Store*>& certstores,
708 std::chrono::system_clock::time_point ref_time,
709 const Path_Validation_Restrictions& restrictions) {
710 if(cert_path.empty()) {
711 throw Invalid_Argument("PKIX::check_ocsp cert_path empty");
712 }
713
714 CertificatePathStatusCodes cert_status(cert_path.size() - 1);
715
716 for(size_t i = 0; i != cert_path.size() - 1; ++i) {
717 const X509_Certificate& subject = cert_path.at(i);
718 const X509_Certificate& ca = cert_path.at(i + 1);
719
720 if(subject.skip_revocation_check()) {
721 continue;
722 }
723
724 if(i < ocsp_responses.size() && ocsp_responses.at(i).has_value() &&
725 ocsp_responses.at(i)->status() == OCSP::Response_Status_Code::Successful) {
726 try {
727 cert_status.at(i) = evaluate_ocsp_response(
728 ocsp_responses.at(i).value(), subject, ca, cert_path, certstores, ref_time, restrictions);
729 } catch(Exception&) {
730 cert_status.at(i).insert(Certificate_Status_Code::OCSP_RESPONSE_INVALID);
731 }
732 }
733 }
734
735 return cert_status;
736}
737
738CertificatePathStatusCodes PKIX::check_crl(const std::vector<X509_Certificate>& cert_path,
739 const std::vector<std::optional<X509_CRL>>& crls,
740 std::chrono::system_clock::time_point ref_time) {
741 return PKIX::check_crl(cert_path, crls, ref_time, Path_Validation_Restrictions());
742}
743
744CertificatePathStatusCodes PKIX::check_crl(const std::vector<X509_Certificate>& cert_path,
745 const std::vector<std::optional<X509_CRL>>& crls,
746 std::chrono::system_clock::time_point ref_time,
747 const Path_Validation_Restrictions& restrictions) {
748 if(cert_path.empty()) {
749 throw Invalid_Argument("PKIX::check_crl cert_path empty");
750 }
751
752 CertificatePathStatusCodes cert_status(cert_path.size());
753 const X509_Time validation_time(ref_time);
754
755 for(size_t i = 0; i != cert_path.size() - 1; ++i) {
756 std::set<Certificate_Status_Code>& status = cert_status.at(i);
757
758 if(cert_path.at(i).skip_revocation_check()) {
759 continue;
760 }
761
762 if(i < crls.size() && crls[i].has_value()) {
763 const X509_Certificate& subject = cert_path.at(i);
764 const X509_Certificate& ca = cert_path.at(i + 1);
765
766 // RFC 5280 6.3.3 step (b)(2): if the CRL's IDP scope or
767 // distributionPoint name excludes this certificate, do not use it
768 // to determine revocation status. Treat as if no CRL was supplied
769 // so the caller's policy (strict revocation or soft fail) decides
770 // the outcome.
771 const auto applic = crl_applicability_for(*crls[i], subject);
772 if(!applic.usable) {
773 continue;
774 }
775
778 }
779
780 if(validation_time < crls[i]->this_update()) {
782 }
783
784 if(crls[i]->next_update().time_is_set() && validation_time > crls[i]->next_update()) {
786 }
787
788 const auto ca_key = ca.subject_public_key();
789 const auto sig_status = crls[i]->verify_signature(*ca_key);
790 const auto& trusted_hashes = restrictions.trusted_hashes();
791
792 if(sig_status.first != Certificate_Status_Code::VERIFIED) {
794 } else if(!trusted_hashes.empty() && !trusted_hashes.contains(sig_status.second)) {
796 } else {
797 /*
798 RFC 5280 5.2 "If a CRL contains a critical extension that the
799 application cannot process, then the application MUST NOT use that
800 CRL to determine the status of certificates."
801
802 RFC 5280 5.3 "If a CRL contains a critical CRL entry extension that
803 the application cannot process, then the application MUST NOT use
804 that CRL to determine the status of any certificates."
805 */
806 const bool crl_is_not_usable = crls[i]->has_unknown_critical_extension();
807
808 if(crl_is_not_usable) {
810 } else if(crls[i]->is_revoked(subject)) {
811 // A reason-limited CRL that lists the cert still proves the
812 // cert is revoked (the cert was revoked for whichever reason
813 // the CRL covers). Surface CERT_IS_REVOKED regardless of
814 // full-coverage status.
816 } else if(applic.full_coverage) {
817 // Cert not listed AND the CRL covers every reason: positive
818 // non-revocation evidence.
820 }
821 // else: cert not listed but CRL only covers some reasons. No
822 // positive evidence is recorded; the caller's policy (strict
823 // revocation -> NO_REVOCATION_DATA, soft fail -> validates)
824 // decides what happens next.
825 }
826 }
827 }
828
829 while(!cert_status.empty() && cert_status.back().empty()) {
830 cert_status.pop_back();
831 }
832
833 return cert_status;
834}
835
836CertificatePathStatusCodes PKIX::check_crl(const std::vector<X509_Certificate>& cert_path,
837 const std::vector<Certificate_Store*>& certstores,
838 std::chrono::system_clock::time_point ref_time) {
839 return PKIX::check_crl(cert_path, certstores, ref_time, Path_Validation_Restrictions());
840}
841
842CertificatePathStatusCodes PKIX::check_crl(const std::vector<X509_Certificate>& cert_path,
843 const std::vector<Certificate_Store*>& certstores,
844 std::chrono::system_clock::time_point ref_time,
845 const Path_Validation_Restrictions& restrictions) {
846 if(cert_path.empty()) {
847 throw Invalid_Argument("PKIX::check_crl cert_path empty");
848 }
849
850 if(certstores.empty()) {
851 throw Invalid_Argument("PKIX::check_crl certstores empty");
852 }
853
854 std::vector<std::optional<X509_CRL>> crls(cert_path.size());
855
856 for(size_t i = 0; i != cert_path.size(); ++i) {
857 if(cert_path[i].skip_revocation_check()) {
858 continue;
859 }
860 for(const auto* certstore : certstores) {
861 crls[i] = certstore->find_crl_for(cert_path[i]);
862 if(crls[i]) {
863 break;
864 }
865 }
866 }
867
868 return PKIX::check_crl(cert_path, crls, ref_time, restrictions);
869}
870
871#if defined(BOTAN_HAS_ONLINE_REVOCATION_CHECKS)
872
873CertificatePathStatusCodes PKIX::check_ocsp_online(const std::vector<X509_Certificate>& cert_path,
874 const std::vector<Certificate_Store*>& trusted_certstores,
875 std::chrono::system_clock::time_point ref_time,
876 std::chrono::milliseconds timeout,
877 const Path_Validation_Restrictions& restrictions) {
878 if(cert_path.empty()) {
879 throw Invalid_Argument("PKIX::check_ocsp_online cert_path empty");
880 }
881
882 std::vector<std::future<std::optional<OCSP::Response>>> ocsp_response_futures;
883
884 size_t to_ocsp = 1;
885
886 if(restrictions.ocsp_all_intermediates()) {
887 to_ocsp = cert_path.size() - 1;
888 }
889 if(cert_path.size() == 1) {
890 to_ocsp = 0;
891 }
892
893 for(size_t i = 0; i < to_ocsp; ++i) {
894 const auto& subject = cert_path.at(i);
895 const auto& issuer = cert_path.at(i + 1);
896
897 if(subject.skip_revocation_check()) {
898 ocsp_response_futures.emplace_back(
899 std::async(std::launch::deferred, []() -> std::optional<OCSP::Response> { return std::nullopt; }));
900 } else {
901 const auto ocsp_urls = URI::filter_scheme("http", subject.ocsp_responder_uris());
902
903 if(ocsp_urls.empty()) {
904 ocsp_response_futures.emplace_back(std::async(std::launch::deferred, []() -> std::optional<OCSP::Response> {
906 }));
907 } else {
908 const auto ocsp_req = OCSP::Request(issuer, subject);
909 ocsp_response_futures.emplace_back(
910 std::async(std::launch::async, [ocsp_urls, ocsp_req, timeout]() -> std::optional<OCSP::Response> {
911 HTTP::Response http;
912 try {
913 http = HTTP::POST_sync(ocsp_urls[0],
914 "application/ocsp-request",
915 ocsp_req.BER_encode(),
917
918 if(http.status_code() != 200) {
920 }
921
922 OCSP::Response response(http.body());
923
924 /*
925 * RFC 6960 2.3: "In case of errors, the OCSP responder may return an
926 * error message. These messages are not signed." Since such responses
927 * (eg tryLater) carry no revocation information, treat them the same
928 * as the server being unavailable.
929 */
930 if(response.status() != OCSP::Response_Status_Code::Successful) {
932 }
933
934 return response;
935 } catch(std::exception&) {
937 }
938 }));
939 }
940 }
941 }
942
943 std::vector<std::optional<OCSP::Response>> ocsp_responses;
944 ocsp_responses.reserve(ocsp_response_futures.size());
945
946 for(auto& ocsp_response_future : ocsp_response_futures) {
947 ocsp_responses.push_back(ocsp_response_future.get());
948 }
949
950 return PKIX::check_ocsp(cert_path, ocsp_responses, trusted_certstores, ref_time, restrictions);
951}
952
953CertificatePathStatusCodes PKIX::check_crl_online(const std::vector<X509_Certificate>& cert_path,
954 const std::vector<Certificate_Store*>& certstores,
956 std::chrono::system_clock::time_point ref_time,
957 std::chrono::milliseconds timeout) {
958 return PKIX::check_crl_online(cert_path, certstores, crl_store, ref_time, timeout, Path_Validation_Restrictions());
959}
960
961CertificatePathStatusCodes PKIX::check_crl_online(const std::vector<X509_Certificate>& cert_path,
962 const std::vector<Certificate_Store*>& certstores,
964 std::chrono::system_clock::time_point ref_time,
965 std::chrono::milliseconds timeout,
966 const Path_Validation_Restrictions& restrictions) {
967 if(cert_path.empty()) {
968 throw Invalid_Argument("PKIX::check_crl_online cert_path empty");
969 }
970 if(certstores.empty()) {
971 throw Invalid_Argument("PKIX::check_crl_online certstores empty");
972 }
973
974 std::vector<std::future<std::optional<X509_CRL>>> future_crls;
975 std::vector<std::optional<X509_CRL>> crls(cert_path.size());
976
977 for(size_t i = 0; i != cert_path.size(); ++i) {
978 const auto& cert = cert_path.at(i);
979
980 if(cert.skip_revocation_check()) {
981 future_crls.emplace_back(
982 std::async(std::launch::deferred, []() -> std::optional<X509_CRL> { return std::nullopt; }));
983 continue;
984 }
985
986 for(const auto* certstore : certstores) {
987 crls[i] = certstore->find_crl_for(cert);
988 if(crls[i].has_value()) {
989 break;
990 }
991 }
992
993 // TODO: check if CRL is expired and re-request?
994
995 // Only request if we don't already have a CRL
996 if(crls[i]) {
997 /*
998 We already have a CRL, so just insert this empty one to hold a place in the vector
999 so that indexes match up
1000 */
1001 future_crls.emplace_back(std::future<std::optional<X509_CRL>>());
1002 } else {
1003 const auto cdp_uris = URI::filter_scheme("http", cert.crl_distribution_point_uris());
1004
1005 if(cdp_uris.empty()) {
1006 future_crls.emplace_back(std::async(std::launch::deferred, []() -> std::optional<X509_CRL> {
1007 throw Not_Implemented("No CRL distribution point for this certificate");
1008 }));
1009 } else {
1010 future_crls.emplace_back(std::async(std::launch::async, [cdp_uris, timeout]() -> std::optional<X509_CRL> {
1011 const auto http = HTTP::GET_sync(
1012 cdp_uris[0], HTTP::RequestLimits().set_timeout(timeout).set_max_body_size(32 * 1024 * 1024));
1013
1014 http.throw_unless_ok();
1015 // check the mime type?
1016 return X509_CRL(http.body());
1017 }));
1018 }
1019 }
1020 }
1021
1022 for(size_t i = 0; i != future_crls.size(); ++i) {
1023 if(future_crls[i].valid()) {
1024 try {
1025 crls[i] = future_crls[i].get();
1026 } catch(std::exception&) {
1027 // crls[i] left null
1028 // todo: log exception e.what() ?
1029 }
1030 }
1031 }
1032
1033 auto crl_status = PKIX::check_crl(cert_path, crls, ref_time, restrictions);
1034
1035 if(crl_store != nullptr) {
1036 for(size_t i = 0; i != crl_status.size(); ++i) {
1037 if(crl_status[i].contains(Certificate_Status_Code::VALID_CRL_CHECKED)) {
1038 // better be non-null, we supposedly validated it
1039 BOTAN_ASSERT_NOMSG(crls[i].has_value());
1040 crl_store->add_crl(*crls[i]);
1041 }
1042 }
1043 }
1044
1045 return crl_status;
1046}
1047
1048#endif
1049
1050Certificate_Status_Code PKIX::build_certificate_path(std::vector<X509_Certificate>& cert_path,
1051 const std::vector<Certificate_Store*>& trusted_certstores,
1052 const X509_Certificate& end_entity,
1053 const std::vector<X509_Certificate>& end_entity_extra,
1054 std::optional<size_t> max_paths) {
1055 if(max_paths.has_value() && max_paths.value() == 0) {
1057 }
1058
1059 CertificatePathBuilder builder(
1060 trusted_certstores, end_entity, end_entity_extra, PathBuildingDfsBudget, /*require_self_signed=*/false);
1061
1062 std::vector<X509_Certificate> first_path;
1063 size_t paths_examined = 0;
1064
1065 while(auto path = builder.next()) {
1066 BOTAN_ASSERT_NOMSG(path->empty() == false);
1067
1068 if(max_paths.has_value() && paths_examined >= max_paths.value()) {
1069 break;
1070 }
1071 paths_examined += 1;
1072
1073 // Prefer paths ending in self-signed certificates.
1074 if(path->back().is_self_signed()) {
1075 cert_path.insert(cert_path.end(), path->begin(), path->end());
1077 }
1078
1079 // Save the first path for later just in case we find nothing better
1080 if(first_path.empty()) {
1081 first_path = std::move(*path);
1082 }
1083 }
1084
1085 if(!first_path.empty()) {
1086 // We found a path, it's not self-signed but it's as good as can be formed...
1087 cert_path.insert(cert_path.end(), first_path.begin(), first_path.end());
1089 }
1090
1091 // Failed to build any path at all
1092 return builder.error();
1093}
1094
1095Certificate_Status_Code PKIX::build_all_certificate_paths(std::vector<std::vector<X509_Certificate>>& cert_paths_out,
1096 const std::vector<Certificate_Store*>& trusted_certstores,
1097 const X509_Certificate& end_entity,
1098 const std::vector<X509_Certificate>& end_entity_extra,
1099 std::optional<size_t> max_paths) {
1100 if(!cert_paths_out.empty()) {
1101 throw Invalid_Argument("PKIX::build_all_certificate_paths: cert_paths_out must be empty");
1102 }
1103 CertificatePathBuilder builder(
1104 trusted_certstores, end_entity, end_entity_extra, PathBuildingDfsBudget, /*require_self_signed=*/false);
1105
1106 while(auto path = builder.next()) {
1107 BOTAN_ASSERT_NOMSG(path->empty() == false);
1108 if(max_paths.has_value() && cert_paths_out.size() >= max_paths.value()) {
1109 // More paths exist than the caller permitted us to enumerate
1111 }
1112 cert_paths_out.push_back(std::move(*path));
1113 }
1114
1115 if(!cert_paths_out.empty()) {
1116 // Was able to generate at least one potential path
1118 } else {
1119 // Could not construct any potentially valid path...
1120 return builder.error();
1121 }
1122}
1123
1125 const CertificatePathStatusCodes& crl_status,
1126 const CertificatePathStatusCodes& ocsp_status,
1127 const Path_Validation_Restrictions& restrictions) {
1128 if(chain_status.empty()) {
1129 throw Invalid_Argument("PKIX::merge_revocation_status chain_status was empty");
1130 }
1131
1132 for(size_t i = 0; i != chain_status.size() - 1; ++i) {
1133 bool had_crl = false;
1134 bool had_ocsp = false;
1135
1136 // RFC 5280 6.3.3 treats revocation status as determined once cert_status
1137 // is not UNREVOKED, so CERT_IS_REVOKED (whether from CRL or OCSP) is
1138 // revocation evidence on a par with VALID_CRL_CHECKED / OCSP_RESPONSE_GOOD;
1139 // omitting it would surface a spurious NO_REVOCATION_DATA alongside the
1140 // revocation, e.g. when a reason-limited CRL lists the cert.
1141 if(i < crl_status.size() && !crl_status[i].empty()) {
1142 for(auto&& code : crl_status[i]) {
1144 had_crl = true;
1145 }
1146 chain_status[i].insert(code);
1147 }
1148 }
1149
1150 if(i < ocsp_status.size() && !ocsp_status[i].empty()) {
1151 for(auto&& code : ocsp_status[i]) {
1152 const bool was_definitive =
1154
1155 const bool was_softfail = code == Certificate_Status_Code::OCSP_NO_REVOCATION_URL ||
1158
1159 const bool accepted_softfail = was_softfail && restrictions.accept_ocsp_softfail();
1160
1161 if(was_definitive || accepted_softfail) {
1162 had_ocsp = true;
1163 }
1164
1165 chain_status[i].insert(code);
1166 }
1167 }
1168
1169 if(had_crl == false && had_ocsp == false) {
1170 if((restrictions.require_revocation_information() && i == 0) ||
1171 (restrictions.ocsp_all_intermediates() && i > 0)) {
1172 chain_status[i].insert(Certificate_Status_Code::NO_REVOCATION_DATA);
1173 }
1174 }
1175 }
1176}
1177
1179 if(cert_status.empty()) {
1180 throw Invalid_Argument("PKIX::overall_status empty cert status");
1181 }
1182
1184
1185 // take the "worst" error as overall
1186 for(const std::set<Certificate_Status_Code>& s : cert_status) {
1187 if(!s.empty()) {
1188 const auto worst = *s.rbegin();
1189 // Leave informative OCSP/CRL confirmations on cert-level status only
1191 overall_status = worst;
1192 }
1193 }
1194 }
1195 return overall_status;
1196}
1197
1198Path_Validation_Result x509_path_validate(const std::vector<X509_Certificate>& end_certs,
1199 const Path_Validation_Restrictions& restrictions,
1200 const std::vector<Certificate_Store*>& trusted_roots,
1201 std::string_view hostname,
1202 Usage_Type usage,
1203 std::chrono::system_clock::time_point ref_time,
1204 std::chrono::milliseconds ocsp_timeout,
1205 const std::vector<std::optional<OCSP::Response>>& ocsp_resp) {
1206 if(end_certs.empty()) {
1207 throw Invalid_Argument("x509_path_validate called with no subjects");
1208 }
1209
1210 const X509_Certificate& end_entity = end_certs[0];
1211 const auto end_entity_extra = std::span<const X509_Certificate>(end_certs).subspan(1);
1212
1213 const bool require_self_signed = restrictions.require_self_signed_trust_anchors();
1214
1215 CertificatePathBuilder builder(
1216 trusted_roots, end_entity, end_entity_extra, PathBuildingDfsBudget, require_self_signed);
1217
1218 std::optional<Path_Validation_Result> first_path_error;
1219 size_t paths_checked = 0;
1220 size_t certs_checked = 0;
1221
1222 while(auto cert_path = builder.next()) {
1223 BOTAN_ASSERT_NOMSG(cert_path->empty() == false);
1224
1225 if(cert_path->size() > PathBuildingMaximumChainLength) {
1226 continue;
1227 }
1228
1229 paths_checked += 1;
1230 certs_checked += cert_path->size();
1231 if(paths_checked > PathBuildingMaxPathsExamined || certs_checked > PathBuildingVerificationBudget) {
1233 break;
1234 }
1235
1236 CertificatePathStatusCodes status = PKIX::check_chain(*cert_path, ref_time, hostname, usage, restrictions);
1237
1238 // Skip revocation checks if the chain already has fatal errors.
1240 const CertificatePathStatusCodes crl_status =
1241 PKIX::check_crl(*cert_path, trusted_roots, ref_time, restrictions);
1242
1243 CertificatePathStatusCodes ocsp_status;
1244
1245 if(!ocsp_resp.empty()) {
1246 ocsp_status = PKIX::check_ocsp(*cert_path, ocsp_resp, trusted_roots, ref_time, restrictions);
1247 }
1248
1249 if(ocsp_timeout != std::chrono::milliseconds(0)) {
1250 const size_t to_online = restrictions.ocsp_all_intermediates() ? (cert_path->size() - 1) : 1;
1251 bool need_online = false;
1252 for(size_t i = 0; i < to_online; ++i) {
1253 if((*cert_path)[i].skip_revocation_check()) {
1254 continue;
1255 }
1256 if(i >= ocsp_status.size() || ocsp_status[i].empty()) {
1257 need_online = true;
1258 break;
1259 }
1260 }
1261
1262 if(need_online) {
1263#if defined(BOTAN_TARGET_OS_HAS_THREADS) && defined(BOTAN_HAS_HTTP_UTIL)
1264 auto online_status =
1265 PKIX::check_ocsp_online(*cert_path, trusted_roots, ref_time, ocsp_timeout, restrictions);
1266 if(ocsp_status.size() < online_status.size()) {
1267 ocsp_status.resize(online_status.size());
1268 }
1269 for(size_t i = 0; i < online_status.size(); ++i) {
1270 if(ocsp_status[i].empty()) {
1271 ocsp_status[i] = std::move(online_status[i]);
1272 }
1273 }
1274#else
1275 if(ocsp_status.size() < to_online) {
1276 ocsp_status.resize(to_online);
1277 }
1278 for(size_t i = 0; i < to_online; ++i) {
1279 if(ocsp_status[i].empty()) {
1280 ocsp_status[i].insert(Certificate_Status_Code::OCSP_NO_HTTP);
1281 }
1282 }
1283#endif
1284 }
1285 }
1286
1287 PKIX::merge_revocation_status(status, crl_status, ocsp_status, restrictions);
1288
1289 // merge_revocation_status flags NO_REVOCATION_DATA when require_revocation
1290 // is set; clear it for certs where RFC 9608 Section 4 says to skip the check.
1291 for(size_t i = 0; i + 1 < cert_path->size() && i < status.size(); ++i) {
1292 if((*cert_path)[i].skip_revocation_check()) {
1294 }
1295 }
1296 }
1297
1298 Path_Validation_Result pvd(status, std::move(*cert_path));
1299 if(pvd.successful_validation()) {
1300 return pvd;
1301 } else if(!first_path_error.has_value()) {
1302 // Save the errors from the first path we attempted
1303 first_path_error = std::move(pvd);
1304 }
1305 }
1306
1307 if(first_path_error.has_value()) {
1308 // We found at least one path, but none of them verified
1309 // Return arbitrarily the error from the first path attempted
1310 return first_path_error.value();
1311 } else {
1312 // Failed to build any path at all
1313 return Path_Validation_Result(builder.error());
1314 }
1315}
1316
1318 const Path_Validation_Restrictions& restrictions,
1319 const std::vector<Certificate_Store*>& trusted_roots,
1320 std::string_view hostname,
1321 Usage_Type usage,
1322 std::chrono::system_clock::time_point when,
1323 std::chrono::milliseconds ocsp_timeout,
1324 const std::vector<std::optional<OCSP::Response>>& ocsp_resp) {
1325 std::vector<X509_Certificate> certs;
1326 certs.push_back(end_cert);
1327 return x509_path_validate(certs, restrictions, trusted_roots, hostname, usage, when, ocsp_timeout, ocsp_resp);
1328}
1329
1330Path_Validation_Result x509_path_validate(const std::vector<X509_Certificate>& end_certs,
1331 const Path_Validation_Restrictions& restrictions,
1332 const Certificate_Store& store,
1333 std::string_view hostname,
1334 Usage_Type usage,
1335 std::chrono::system_clock::time_point when,
1336 std::chrono::milliseconds ocsp_timeout,
1337 const std::vector<std::optional<OCSP::Response>>& ocsp_resp) {
1338 std::vector<Certificate_Store*> trusted_roots;
1339 trusted_roots.push_back(const_cast<Certificate_Store*>(&store));
1340
1341 return x509_path_validate(end_certs, restrictions, trusted_roots, hostname, usage, when, ocsp_timeout, ocsp_resp);
1342}
1343
1345 const Path_Validation_Restrictions& restrictions,
1346 const Certificate_Store& store,
1347 std::string_view hostname,
1348 Usage_Type usage,
1349 std::chrono::system_clock::time_point when,
1350 std::chrono::milliseconds ocsp_timeout,
1351 const std::vector<std::optional<OCSP::Response>>& ocsp_resp) {
1352 std::vector<X509_Certificate> certs;
1353 certs.push_back(end_cert);
1354
1355 std::vector<Certificate_Store*> trusted_roots;
1356 trusted_roots.push_back(const_cast<Certificate_Store*>(&store));
1357
1358 return x509_path_validate(certs, restrictions, trusted_roots, hostname, usage, when, ocsp_timeout, ocsp_resp);
1359}
1360
1362 size_t key_strength,
1363 bool ocsp_intermediates,
1364 std::chrono::seconds max_ocsp_age,
1365 std::unique_ptr<Certificate_Store> trusted_ocsp_responders,
1368 bool accept_ocsp_softfail) :
1369 m_require_revocation_information(require_rev),
1370 m_ocsp_all_intermediates(ocsp_intermediates),
1371 m_minimum_key_strength(key_strength),
1372 m_max_ocsp_age(max_ocsp_age),
1373 m_trusted_ocsp_responders(std::move(trusted_ocsp_responders)),
1374 m_ignore_trusted_root_time_range(ignore_trusted_root_time_range),
1375 m_require_self_signed_trust_anchors(require_self_signed_trust_anchors),
1376 m_accept_ocsp_softfail(accept_ocsp_softfail) {
1377 if(key_strength <= 80) {
1378 m_trusted_hashes.insert("SHA-1");
1379 }
1380
1381 m_trusted_hashes.insert("SHA-224");
1382 m_trusted_hashes.insert("SHA-256");
1383 m_trusted_hashes.insert("SHA-384");
1384 m_trusted_hashes.insert("SHA-512");
1385 m_trusted_hashes.insert("SHAKE-256(512)"); // Dilithium/ML-DSA
1386 m_trusted_hashes.insert("SHAKE-256(912)"); // Ed448
1387
1388 // SLH-DSA-SHAKE reports the H_msg output length, which depends on the parameter set
1389 m_trusted_hashes.insert("SHAKE-256(240)"); // SLH-DSA-SHAKE-128s
1390 m_trusted_hashes.insert("SHAKE-256(272)"); // SLH-DSA-SHAKE-128f
1391 m_trusted_hashes.insert("SHAKE-256(312)"); // SLH-DSA-SHAKE-192s
1392 m_trusted_hashes.insert("SHAKE-256(336)"); // SLH-DSA-SHAKE-192f
1393 m_trusted_hashes.insert("SHAKE-256(376)"); // SLH-DSA-SHAKE-256s
1394 m_trusted_hashes.insert("SHAKE-256(392)"); // SLH-DSA-SHAKE-256f
1395
1396 // Hashes used by HSS-LMS and XMSS parameter sets
1397 m_trusted_hashes.insert("SHAKE-128(256)"); // XMSS-SHAKE_*_256
1398 m_trusted_hashes.insert("SHAKE-256(192)"); // HSS-LMS and XMSS with SHAKE-256/192
1399 m_trusted_hashes.insert("SHAKE-256(256)"); // HSS-LMS and XMSS with SHAKE-256/256
1400 m_trusted_hashes.insert("Truncated(SHA-256,192)"); // HSS-LMS and XMSS with SHA-256/192
1401}
1402
1403namespace {
1404CertificatePathStatusCodes find_warnings(const CertificatePathStatusCodes& all_statuses) {
1406 for(const auto& status_set_i : all_statuses) {
1407 std::set<Certificate_Status_Code> warning_set_i;
1408 for(const auto& code : status_set_i) {
1411 warning_set_i.insert(code);
1412 }
1413 }
1414 warnings.push_back(warning_set_i);
1415 }
1416 return warnings;
1417}
1418} // namespace
1419
1421 std::vector<X509_Certificate>&& cert_chain) :
1422 m_all_status(std::move(status)),
1423 m_warnings(find_warnings(m_all_status)),
1424 m_cert_path(std::move(cert_chain)),
1425 m_overall(PKIX::overall_status(m_all_status)) {}
1426
1428 if(m_cert_path.empty()) {
1429 throw Invalid_State("Path_Validation_Result::trust_root no path set");
1430 }
1432 throw Invalid_State("Path_Validation_Result::trust_root meaningless with invalid status");
1433 }
1434
1435 return m_cert_path[m_cert_path.size() - 1];
1436}
1437
1442
1444 for(const auto& status_set_i : m_warnings) {
1445 if(!status_set_i.empty()) {
1446 return false;
1447 }
1448 }
1449 return true;
1450}
1451
1453 return m_warnings;
1454}
1455
1457 return status_string(result());
1458}
1459
1461 if(const char* s = to_string(code)) {
1462 return s;
1463 }
1464
1465 return "Unknown error";
1466}
1467
1469 const std::string sep(", ");
1470 std::ostringstream oss;
1471 for(size_t i = 0; i < m_warnings.size(); i++) {
1472 for(const auto code : m_warnings[i]) {
1473 oss << "[" << std::to_string(i) << "] " << status_string(code) << sep;
1474 }
1475 }
1476
1477 std::string res = oss.str();
1478 // remove last sep
1479 if(res.size() >= sep.size()) {
1480 res = res.substr(0, res.size() - sep.size());
1481 }
1482 return res;
1483}
1484} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
const OID & oid() const
Definition asn1_obj.h:688
const std::optional< ReasonFlags > & only_some_reasons() const
Definition x509_ext.h:736
void validate(const X509_Certificate &subject, const std::optional< X509_Certificate > &issuer, const std::vector< X509_Certificate > &cert_path, std::vector< std::set< Certificate_Status_Code > > &cert_status, size_t pos) const
Definition x509_ext.cpp:271
const std::vector< OID > & get_extension_oids() const
Definition pkix_types.h:901
RequestLimits & set_timeout(std::chrono::milliseconds t)
Definition http_util.h:115
RequestLimits & set_max_body_size(size_t n)
Definition http_util.h:120
static Response dummy_server_not_available_response()
Definition ocsp.h:296
static Response dummy_no_revocation_url_response()
Definition ocsp.h:304
bool registered_oid() const
Definition asn1_oid.cpp:153
BOTAN_FUTURE_EXPLICIT Path_Validation_Restrictions(bool require_rev=false, size_t minimum_key_strength=110, bool ocsp_all_intermediates=false, std::chrono::seconds max_ocsp_age=std::chrono::hours(24 *7), std::unique_ptr< Certificate_Store > trusted_ocsp_responders=nullptr, bool ignore_trusted_root_time_range=false, bool require_self_signed_trust_anchors=true, bool accept_ocsp_softfail=false)
bool require_revocation_information() const
Definition x509path.h:123
const std::set< std::string > & trusted_hashes() const
Definition x509path.h:134
std::chrono::seconds max_ocsp_age() const
Definition x509path.h:145
bool ignore_trusted_root_time_range() const
Definition x509path.h:165
bool require_self_signed_trust_anchors() const
Definition x509path.h:175
const Certificate_Store * trusted_ocsp_responders() const
Definition x509path.h:152
Certificate_Status_Code result() const
Definition x509path.h:229
Path_Validation_Result(CertificatePathStatusCodes status, std::vector< X509_Certificate > &&cert_chain)
static const char * status_string(Certificate_Status_Code code)
const X509_Certificate & trust_root() const
std::string result_string() const
std::string warnings_string() const
CertificatePathStatusCodes warnings() const
static std::vector< URI > filter_scheme(std::string_view scheme, std::span< const URI > uris)
Definition uri.cpp:366
const X509_DN & subject_dn() const
Definition x509cert.cpp:458
bool skip_revocation_check() const
Definition x509cert.cpp:450
const X509_Serial_Number & serial() const
Definition x509cert.cpp:442
const X509_Time & not_after() const
Definition x509cert.cpp:390
const std::vector< uint8_t > & authority_key_id() const
Definition x509cert.cpp:430
const std::vector< uint8_t > & subject_key_id() const
Definition x509cert.cpp:434
std::optional< size_t > path_length_constraint() const
Definition x509cert.cpp:497
const Extensions & v3_extensions() const
Definition x509cert.cpp:517
bool allowed_usage(Key_Constraints usage) const
Definition x509cert.cpp:526
const X509_DN & issuer_dn() const
Definition x509cert.cpp:454
const std::vector< uint8_t > & v2_issuer_key_id() const
Definition x509cert.cpp:398
uint32_t x509_version() const
Definition x509cert.cpp:378
bool is_self_signed() const
Definition x509cert.cpp:382
std::unique_ptr< Public_Key > subject_public_key() const
Definition x509cert.cpp:756
const std::vector< uint8_t > & v2_subject_key_id() const
Definition x509cert.cpp:402
const X509_Time & not_before() const
Definition x509cert.cpp:386
const std::vector< std::vector< std::pair< OID, ASN1_String > > > & rdns() const
Definition pkix_types.h:229
static size_t lookup_ub(const OID &oid)
const AlgorithmIdentifier & signature_algorithm() const
Definition x509_obj.cpp:73
std::pair< Certificate_Status_Code, std::string > verify_signature(const Public_Key &key) const
Definition x509_obj.cpp:130
bool check_signature(const Public_Key &key) const
Definition x509_obj.cpp:125
const char * path
Definition ffi_tls.h:139
botan_x509_crl_t crl
Definition ffi_tls.h:127
Response GET_sync(const URI &uri, const RequestLimits &limits)
Response POST_sync(const URI &uri, std::string_view content_type, const std::vector< uint8_t > &body, const RequestLimits &limits)
void merge_revocation_status(CertificatePathStatusCodes &chain_status, const CertificatePathStatusCodes &crl_status, const CertificatePathStatusCodes &ocsp_status, const Path_Validation_Restrictions &restrictions)
Certificate_Status_Code build_certificate_path(std::vector< X509_Certificate > &cert_path_out, const std::vector< Certificate_Store * > &trusted_certstores, const X509_Certificate &end_entity, const std::vector< X509_Certificate > &end_entity_extra, std::optional< size_t > max_paths=std::nullopt)
CertificatePathStatusCodes check_crl(const std::vector< X509_Certificate > &cert_path, const std::vector< std::optional< X509_CRL > > &crls, std::chrono::system_clock::time_point ref_time, const Path_Validation_Restrictions &restrictions)
Definition x509path.cpp:744
Certificate_Status_Code build_all_certificate_paths(std::vector< std::vector< X509_Certificate > > &cert_paths, const std::vector< Certificate_Store * > &trusted_certstores, const X509_Certificate &end_entity, const std::vector< X509_Certificate > &end_entity_extra, std::optional< size_t > max_paths=std::nullopt)
Certificate_Status_Code overall_status(const CertificatePathStatusCodes &cert_status)
CertificatePathStatusCodes check_ocsp(const std::vector< X509_Certificate > &cert_path, const std::vector< std::optional< OCSP::Response > > &ocsp_responses, const std::vector< Certificate_Store * > &certstores, std::chrono::system_clock::time_point ref_time, const Path_Validation_Restrictions &restrictions)
Definition x509path.cpp:705
CertificatePathStatusCodes check_chain(const std::vector< X509_Certificate > &cert_path, std::chrono::system_clock::time_point ref_time, std::string_view hostname, Usage_Type usage, const Path_Validation_Restrictions &restrictions)
Definition x509path.cpp:344
std::vector< std::set< Certificate_Status_Code > > CertificatePathStatusCodes
Definition x509path.h:29
ASN1_Time X509_Time
Definition asn1_obj.h:27
Certificate_Status_Code
Definition pkix_enums.h:21
DistributionPointMatch distribution_point_match(const X509_CRL &crl, const X509_Certificate &cert)
Definition x509_crl.cpp:458
Path_Validation_Result x509_path_validate(const std::vector< X509_Certificate > &end_certs, const Path_Validation_Restrictions &restrictions, const std::vector< Certificate_Store * > &trusted_roots, std::string_view hostname, Usage_Type usage, std::chrono::system_clock::time_point ref_time, std::chrono::milliseconds ocsp_timeout, const std::vector< std::optional< OCSP::Response > > &ocsp_resp)
constexpr auto concat(Rs &&... ranges)
Definition concat_util.h:95
std::string to_string(ErrorType type)
Convert an ErrorType to string.
Definition exceptn.cpp:13