Botan 3.14.1
Crypto and TLS for C&
x509_ext.cpp
Go to the documentation of this file.
1/*
2* X.509 Certificate Extensions
3* (C) 1999-2010,2012 Jack Lloyd
4* (C) 2016 René Korthaus, Rohde & Schwarz Cybersecurity
5* (C) 2017 Fabian Weissberg, Rohde & Schwarz Cybersecurity
6* (C) 2024 Anton Einax, Dominik Schricker
7*
8* Botan is released under the Simplified BSD License (see license.txt)
9*/
10
11#include <botan/x509_ext.h>
12
13#include <botan/assert.h>
14#include <botan/ber_dec.h>
15#include <botan/der_enc.h>
16#include <botan/hash.h>
17#include <botan/pk_keys.h>
18#include <botan/x509cert.h>
19#include <botan/internal/fmt.h>
20#include <botan/internal/int_utils.h>
21#include <botan/internal/loadstor.h>
22#include <botan/internal/x509_utils.h>
23#include <algorithm>
24#include <bit>
25#include <concepts>
26#include <optional>
27#include <set>
28#include <span>
29#include <tuple>
30#include <utility>
31
32namespace Botan {
33
34namespace {
35
36constexpr size_t MaximumKeyIdentifierLength = 64;
37
38/*
39* Encode an AlternativeName as `GeneralNames` but with an outer IMPLICIT
40* context-specific tag rather than the universal SEQUENCE tag. Used for
41* fullName [0] / cRLIssuer [2] / similar.
42*/
43void emit_general_names_implicit(DER_Encoder& der, const AlternativeName& names, uint32_t tag) {
44 // RFC 5280 4.2.1.6: GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
45 if(!names.has_items()) {
46 throw Encoding_Error("Cannot encode empty GeneralNames");
47 }
48 if(std::ranges::any_of(names.directory_names(), [](const X509_DN& dn) { return dn.empty(); })) {
49 throw Encoding_Error("GeneralNames must not contain an empty directoryName");
50 }
51 der.encode_implicit(names, ASN1_Type(tag));
52}
53
54template <std::derived_from<Certificate_Extension> T>
55auto make_extension([[maybe_unused]] const OID& oid) {
56 BOTAN_DEBUG_ASSERT(oid == T::static_oid());
57 return std::make_unique<T>();
58}
59
60std::unique_ptr<Certificate_Extension> extension_from_oid(const OID& oid) {
61 if(auto iso_ext = is_sub_element_of(oid, {2, 5, 29})) {
62 // NOLINTNEXTLINE(*-switch-missing-default-case)
63 switch(*iso_ext) {
64 case 14:
65 return make_extension<Cert_Extension::Subject_Key_ID>(oid);
66 case 15:
67 return make_extension<Cert_Extension::Key_Usage>(oid);
68 case 17:
69 return make_extension<Cert_Extension::Subject_Alternative_Name>(oid);
70 case 18:
71 return make_extension<Cert_Extension::Issuer_Alternative_Name>(oid);
72 case 19:
73 return make_extension<Cert_Extension::Basic_Constraints>(oid);
74 case 20:
75 return make_extension<Cert_Extension::CRL_Number>(oid);
76 case 21:
77 return make_extension<Cert_Extension::CRL_ReasonCode>(oid);
78 case 28:
79 return make_extension<Cert_Extension::CRL_Issuing_Distribution_Point>(oid);
80 case 30:
81 return make_extension<Cert_Extension::Name_Constraints>(oid);
82 case 31:
83 return make_extension<Cert_Extension::CRL_Distribution_Points>(oid);
84 case 32:
85 return make_extension<Cert_Extension::Certificate_Policies>(oid);
86 case 35:
87 return make_extension<Cert_Extension::Authority_Key_ID>(oid);
88 case 37:
89 return make_extension<Cert_Extension::Extended_Key_Usage>(oid);
90 case 56:
91 return make_extension<Cert_Extension::NoRevocationAvailable>(oid);
92 }
93 }
94
95 if(auto pkix_ext = is_sub_element_of(oid, {1, 3, 6, 1, 5, 5, 7, 1})) {
96 // NOLINTNEXTLINE(*-switch-missing-default-case)
97 switch(*pkix_ext) {
98 case 1:
99 return make_extension<Cert_Extension::Authority_Information_Access>(oid);
100 case 7:
101 return make_extension<Cert_Extension::IPAddressBlocks>(oid);
102 case 8:
103 return make_extension<Cert_Extension::ASBlocks>(oid);
104 case 26:
105 return make_extension<Cert_Extension::TNAuthList>(oid);
106 }
107 }
108
110 return make_extension<Cert_Extension::OCSP_NoCheck>(oid);
111 }
112
113 return nullptr; // unknown
114}
115
116} // namespace
117
118std::vector<OID> Extensions::critical_extensions() const {
119 std::vector<OID> crit;
120
121 for(const auto& oid : m_extension_oids) {
122 const auto ext_info = m_extension_info.find(oid);
123 BOTAN_ASSERT_NOMSG(ext_info != m_extension_info.end());
124 if(ext_info->second.is_critical()) {
125 crit.push_back(oid);
126 }
127 }
128
129 return crit;
130}
131
132/*
133* Create a Certificate_Extension object of some kind to handle
134*/
135std::unique_ptr<Certificate_Extension> Extensions::create_extn_obj(const OID& oid,
136 bool critical,
137 const std::vector<uint8_t>& body,
138 std::optional<Extension_Context> context) {
139 auto extn = extension_from_oid(oid);
140
141 if(!extn) {
142 // some other unknown extension type
143 extn = std::make_unique<Cert_Extension::Unknown_Extension>(oid, critical);
144 } else {
145 if(context.has_value() && !extn->is_appropriate_context(*context)) {
146 throw Decoding_Error(fmt("Extension {} is not allowed in this context", extn->oid_name()));
147 }
148
149 try {
150 extn->decode_inner(body);
151 return extn;
152 } catch(const Exception&) {
153 // OID was recognized but contents failed to decode
154 extn = std::make_unique<Cert_Extension::Unknown_Extension>(oid, critical, /*failed_to_decode=*/true);
155 }
156 }
157
158 // This is always Unknown_Extension:
159 extn->decode_inner(body);
160 return extn;
161}
162
163const Certificate_Extension& Extensions::Extensions_Info::obj() const {
164 BOTAN_ASSERT_NONNULL(m_obj.get());
165 return *m_obj;
166}
167
168/*
169* Validate the extension (the default implementation is a NOP)
170*/
172 const std::optional<X509_Certificate>& /*unused*/,
173 const std::vector<X509_Certificate>& /*unused*/,
174 std::vector<std::set<Certificate_Status_Code>>& /*unused*/,
175 size_t /*unused*/) const {}
176
177/*
178* Add a new cert
179*/
180void Extensions::add(std::unique_ptr<Certificate_Extension> extn, bool critical) {
181 // sanity check: we don't want to have the same extension more than once
182 if(m_extension_info.contains(extn->oid_of())) {
183 const std::string name = extn->oid_name();
184 throw Invalid_Argument("Extension " + name + " already present in Extensions::add");
185 }
186
187 const OID oid = extn->oid_of();
188 Extensions_Info info(critical, std::move(extn));
189 m_extension_oids.push_back(oid);
190 m_extension_info.emplace(oid, info);
191}
192
193bool Extensions::add_new(std::unique_ptr<Certificate_Extension> extn, bool critical) {
194 if(m_extension_info.contains(extn->oid_of())) {
195 return false; // already exists
196 }
197
198 const OID oid = extn->oid_of();
199 Extensions_Info info(critical, std::move(extn));
200 m_extension_oids.push_back(oid);
201 m_extension_info.emplace(oid, info);
202 return true;
203}
204
205bool Extensions::remove(const OID& oid) {
206 const bool erased = m_extension_info.erase(oid) > 0;
207
208 if(erased) {
209 m_extension_oids.erase(std::find(m_extension_oids.begin(), m_extension_oids.end(), oid));
210 }
211
212 return erased;
213}
214
215void Extensions::replace(std::unique_ptr<Certificate_Extension> extn, bool critical) {
216 // Remove it if it existed
217 remove(extn->oid_of());
218
219 const OID oid = extn->oid_of();
220 Extensions_Info info(critical, std::move(extn));
221 m_extension_oids.push_back(oid);
222 m_extension_info.emplace(oid, info);
223}
224
225bool Extensions::extension_set(const OID& oid) const {
226 return m_extension_info.contains(oid);
227}
228
230 const auto i = m_extension_info.find(oid);
231 if(i != m_extension_info.end()) {
232 return i->second.is_critical();
233 }
234 return false;
235}
236
237std::vector<uint8_t> Extensions::get_extension_bits(const OID& oid) const {
238 const auto i = m_extension_info.find(oid);
239 if(i == m_extension_info.end()) {
240 throw Invalid_Argument("Extensions::get_extension_bits no such extension set");
241 }
242
243 return i->second.bits();
244}
245
247 const auto extn = m_extension_info.find(oid);
248 if(extn == m_extension_info.end()) {
249 return nullptr;
250 }
251
252 return &extn->second.obj();
253}
254
255std::unique_ptr<Certificate_Extension> Extensions::get(const OID& oid) const {
256 if(const Certificate_Extension* ext = this->get_extension_object(oid)) {
257 return ext->copy();
258 }
259 return nullptr;
260}
261
262std::vector<std::pair<std::unique_ptr<Certificate_Extension>, bool>> Extensions::extensions() const {
263 std::vector<std::pair<std::unique_ptr<Certificate_Extension>, bool>> exts;
264 exts.reserve(m_extension_info.size());
265 for(auto&& ext : m_extension_info) {
266 exts.push_back(std::make_pair(ext.second.obj().copy(), ext.second.is_critical()));
267 }
268 return exts;
269}
270
272 const std::optional<X509_Certificate>& issuer,
273 const std::vector<X509_Certificate>& cert_path,
274 std::vector<std::set<Certificate_Status_Code>>& cert_status,
275 size_t pos) const {
276 for(const auto& ext : m_extension_info) {
277 ext.second.obj().validate(subject, issuer, cert_path, cert_status, pos);
278 }
279}
280
281std::map<OID, std::pair<std::vector<uint8_t>, bool>> Extensions::extensions_raw() const {
282 std::map<OID, std::pair<std::vector<uint8_t>, bool>> out;
283 for(auto&& ext : m_extension_info) {
284 out.emplace(ext.first, std::make_pair(ext.second.bits(), ext.second.is_critical()));
285 }
286 return out;
287}
288
289/*
290* Encode an Extensions list
291*/
292void Extensions::encode_into(DER_Encoder& to_object) const {
293 for(const auto& [oid, extn] : m_extension_info) {
294 const bool should_encode = extn.obj().should_encode();
295
296 if(should_encode) {
297 const auto is_critical = extn.is_critical() ? std::optional<bool>{true} : std::nullopt;
298 const std::vector<uint8_t>& ext_value = extn.bits();
299
300 to_object.start_sequence()
301 .encode(oid)
302 .encode_optional(is_critical)
303 .encode(ext_value, ASN1_Type::OctetString)
304 .end_cons();
305 }
306 }
307}
308
309/*
310* Decode a list of Extensions
311*/
313 decode_from(from_source, std::nullopt);
314}
315
316void Extensions::decode_from(BER_Decoder& from_source, std::optional<Extension_Context> context) {
317 m_extension_oids.clear();
318 m_extension_info.clear();
319 m_has_unknown_critical_extension = false;
320
321 BER_Decoder sequence = from_source.start_sequence();
322
323 while(sequence.more_items()) {
324 OID oid;
325 bool critical = false;
326 std::vector<uint8_t> bits;
327
328 sequence.start_sequence()
329 .decode(oid)
332 .end_cons();
333
334 auto obj = create_extn_obj(oid, critical, bits, context);
335 // Unknown_Extension is the only Certificate_Extension with an empty oid_name
336 if(critical && obj->oid_name().empty()) {
337 m_has_unknown_critical_extension = true;
338 }
339 Extensions_Info info(critical, std::move(bits), std::move(obj));
340
341 m_extension_oids.push_back(oid);
342
343 // RFC 5280 4.2: "A certificate MUST NOT include more than one
344 // instance of a particular extension."
345 if(!m_extension_info.emplace(std::move(oid), std::move(info)).second) {
346 throw Decoding_Error("Duplicate certificate extension encountered");
347 }
348 }
349 sequence.verify_end();
350}
351
352namespace Cert_Extension {
353
354bool Basic_Constraints::is_appropriate_context(Extension_Context context) const {
355 return context == Extension_Context::Certificate;
356}
357
358bool Key_Usage::is_appropriate_context(Extension_Context context) const {
359 return context == Extension_Context::Certificate;
360}
361
362bool Subject_Key_ID::is_appropriate_context(Extension_Context context) const {
363 return context == Extension_Context::Certificate;
364}
365
366bool Authority_Key_ID::is_appropriate_context(Extension_Context context) const {
367 return context == Extension_Context::Certificate || context == Extension_Context::CRL;
368}
369
370bool Subject_Alternative_Name::is_appropriate_context(Extension_Context context) const {
371 return context == Extension_Context::Certificate;
372}
373
374bool Issuer_Alternative_Name::is_appropriate_context(Extension_Context context) const {
375 return context == Extension_Context::Certificate || context == Extension_Context::CRL;
376}
377
378bool Extended_Key_Usage::is_appropriate_context(Extension_Context context) const {
379 return context == Extension_Context::Certificate;
380}
381
382bool Name_Constraints::is_appropriate_context(Extension_Context context) const {
383 return context == Extension_Context::Certificate;
384}
385
386bool Certificate_Policies::is_appropriate_context(Extension_Context context) const {
387 return context == Extension_Context::Certificate;
388}
389
390bool Authority_Information_Access::is_appropriate_context(Extension_Context context) const {
391 return context == Extension_Context::Certificate || context == Extension_Context::CRL;
392}
393
394bool CRL_Number::is_appropriate_context(Extension_Context context) const {
395 return context == Extension_Context::CRL;
396}
397
398bool CRL_ReasonCode::is_appropriate_context(Extension_Context context) const {
399 // RFC 6960 4.4.5: "All the extensions specified as CRL entry extensions
400 // -- in Section 5.3 of [RFC5280] -- are also supported as singleExtensions."
402}
403
404bool CRL_Distribution_Points::is_appropriate_context(Extension_Context context) const {
405 return context == Extension_Context::Certificate;
406}
407
408bool CRL_Issuing_Distribution_Point::is_appropriate_context(Extension_Context context) const {
409 return context == Extension_Context::CRL;
410}
411
412bool OCSP_NoCheck::is_appropriate_context(Extension_Context context) const {
413 return context == Extension_Context::Certificate;
414}
415
416bool NoRevocationAvailable::is_appropriate_context(Extension_Context context) const {
417 return context == Extension_Context::Certificate;
418}
419
420bool TNAuthList::is_appropriate_context(Extension_Context context) const {
421 return context == Extension_Context::Certificate;
422}
423
424bool IPAddressBlocks::is_appropriate_context(Extension_Context context) const {
425 return context == Extension_Context::Certificate;
426}
427
428bool ASBlocks::is_appropriate_context(Extension_Context context) const {
429 return context == Extension_Context::Certificate;
430}
431
432bool Unknown_Extension::is_appropriate_context(Extension_Context /*context*/) const {
433 return true;
434}
435
438
440 m_is_ca(is_ca), m_path_length_constraint(path_length_constraint) {
441 if(!m_is_ca && m_path_length_constraint.has_value()) {
442 // RFC 5280 Sec 4.2.1.9 "CAs MUST NOT include the pathLenConstraint field unless the cA boolean is asserted"
443 throw Invalid_Argument(
444 "Basic_Constraints nonsensical to set a path length constraint for a non-CA basicConstraints");
445 }
446}
447
448/*
449* Checked accessor for the path_length_constraint member
450*/
452 if(m_is_ca) {
453 return m_path_length_constraint.value_or(NO_CERT_PATH_LIMIT);
454 } else {
455 throw Invalid_State("Basic_Constraints::get_path_limit: Not a CA");
456 }
457}
458
459/*
460* Encode the extension
461*/
462std::vector<uint8_t> Basic_Constraints::encode_inner() const {
463 std::vector<uint8_t> output;
464
465 if(m_is_ca) {
466 DER_Encoder(output).start_sequence().encode(m_is_ca).encode_optional(m_path_length_constraint).end_cons();
467 } else {
469 }
470
471 return output;
472}
473
474/*
475* Decode the extension
476*/
477void Basic_Constraints::decode_inner(const std::vector<uint8_t>& in) {
478 /*
479 * RFC 5280 Section 4.2.1.9
480 *
481 * BasicConstraints ::= SEQUENCE {
482 * cA BOOLEAN DEFAULT FALSE,
483 * pathLenConstraint INTEGER (0..MAX) OPTIONAL }
484 */
485 BER_Decoder(in, BER_Decoder::Limits::DER())
486 .start_sequence()
487 .decode_optional(m_is_ca, ASN1_Type::Boolean, ASN1_Class::Universal, false)
488 .decode_optional(m_path_length_constraint, ASN1_Type::Integer, ASN1_Class::Universal)
489 .end_cons()
490 .verify_end();
491
492 /* RFC 5280 Section 4.2.1.9:
493 * "CAs MUST NOT include the pathLenConstraint field unless the cA boolean
494 * is asserted and the key usage extension asserts the keyCertSign bit" */
495 if(!m_is_ca && m_path_length_constraint.has_value()) {
496 throw Decoding_Error("BasicConstraints pathLenConstraint must not be present when cA is FALSE");
497 }
498}
499
500/*
501* Encode the extension
502*/
503std::vector<uint8_t> Key_Usage::encode_inner() const {
504 if(m_constraints.empty()) {
505 throw Encoding_Error("Cannot encode empty PKIX key constraints");
506 }
507
508 std::vector<uint8_t> der;
509 DER_Encoder(der).encode_named_bitstring(m_constraints.value(), 16);
510 return der;
511}
512
513/*
514* Decode the extension
515*/
516void Key_Usage::decode_inner(const std::vector<uint8_t>& in) {
517 /* RFC 5280 Section 4.2.1.3 - KeyUsage ::= BIT STRING */
518 uint64_t usage = 0;
519 BER_Decoder(in, BER_Decoder::Limits::DER())
520 .decode_named_bitstring(usage, 16, ASN1_Type::BitString, ASN1_Class::Universal)
521 .verify_end();
522
523 /* RFC 5280 Section 4.2.1.3:
524 * "When the keyUsage extension appears in a certificate, at least one of
525 * the bits MUST be set to 1." */
526 if(usage == 0) {
527 throw Decoding_Error("KeyUsage extension must have at least one bit set");
528 }
529
530 m_constraints = Key_Constraints(static_cast<uint32_t>(usage));
531}
532
533/*
534* Encode the extension
535*/
536std::vector<uint8_t> Subject_Key_ID::encode_inner() const {
537 std::vector<uint8_t> output;
538 DER_Encoder(output).encode(m_key_id, ASN1_Type::OctetString);
539 return output;
540}
541
542/*
543* Decode the extension
544*/
545void Subject_Key_ID::decode_inner(const std::vector<uint8_t>& in) {
546 /* RFC 5280 Section 4.2.1.2 - SubjectKeyIdentifier ::= KeyIdentifier */
547 BER_Decoder(in, BER_Decoder::Limits::DER()).decode(m_key_id, ASN1_Type::OctetString).verify_end();
548
549 if(m_key_id.empty()) {
550 throw Decoding_Error("SubjectKeyIdentifier must not be empty");
551 }
552 if(m_key_id.size() > MaximumKeyIdentifierLength) {
553 throw Decoding_Error(
554 fmt("SubjectKeyIdentifier length {} exceeds limit of {} bytes", m_key_id.size(), MaximumKeyIdentifierLength));
555 }
556}
557
558/*
559* Subject_Key_ID Constructor
560*/
562 /*
563 * RFC 5280 4.2.1.2:
564 * (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
565 * value of the BIT STRING subjectPublicKey (excluding the tag, length,
566 * and number of unused bits).
567 */
568 auto hash = HashFunction::create_or_throw("SHA-1");
569
570 m_key_id.resize(hash->output_length());
571
572 hash->update(pub_key.public_key_bits());
573 hash->final(m_key_id.data());
574}
575
576/*
577* Subject_Key_ID Constructor
578*/
579Subject_Key_ID::Subject_Key_ID(const std::vector<uint8_t>& pub_key, std::string_view hash_name) {
580 auto hash = HashFunction::create_or_throw(hash_name);
581
582 m_key_id.resize(hash->output_length());
583
584 hash->update(pub_key);
585 hash->final(m_key_id.data());
586
587 // Truncate longer hashes, 192 bits here seems plenty
588 const size_t max_skid_len = (192 / 8);
589 if(m_key_id.size() > max_skid_len) {
590 m_key_id.resize(max_skid_len);
591 }
592}
593
594/*
595* Encode the extension
596*/
597std::vector<uint8_t> Authority_Key_ID::encode_inner() const {
598 std::vector<uint8_t> output;
599 DER_Encoder der(output);
600 der.start_sequence();
601 if(!m_key_id.empty()) {
603 }
604 if(m_authority_cert.has_value()) {
605 emit_general_names_implicit(der, m_authority_cert->issuer, 1);
606 der.encode(m_authority_cert->serial_number.to_bigint(), ASN1_Type(2), ASN1_Class::ContextSpecific);
607 }
608 der.end_cons();
609 return output;
610}
611
612/*
613* Decode the extension
614*/
615void Authority_Key_ID::decode_inner(const std::vector<uint8_t>& in) {
616 /*
617 * RFC 5280 Section 4.2.1.1
618 *
619 * AuthorityKeyIdentifier ::= SEQUENCE {
620 * keyIdentifier [0] KeyIdentifier OPTIONAL,
621 * authorityCertIssuer [1] GeneralNames OPTIONAL,
622 * authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
623 */
624 BER_Decoder ber(in, BER_Decoder::Limits::DER());
625 BER_Decoder seq = ber.start_sequence();
626
627 m_key_id.clear();
628 m_authority_cert.reset();
629
630 bool key_id_present = false;
631 std::optional<AlternativeName> authority_cert_issuer;
632 std::optional<X509_Serial_Number> authority_cert_serial;
633
634 seq.decode_optional_field(0,
636 [&](BER_Decoder& d) {
638 key_id_present = true;
639 })
640 .decode_optional_field(1,
642 [&](BER_Decoder& d) {
643 AlternativeName names;
644 d.decode_implicit(names,
645 ASN1_Type(1),
649 authority_cert_issuer = std::move(names);
650 })
651 .decode_optional_field(2, ASN1_Class::ContextSpecific, [&](BER_Decoder& d) {
652 X509_Serial_Number serial;
653 d.decode_implicit(
655 authority_cert_serial = std::move(serial);
656 });
657
658 seq.end_cons();
659 ber.verify_end();
660
661 if(key_id_present) {
662 if(m_key_id.empty()) {
663 throw Decoding_Error("AuthorityKeyIdentifier keyIdentifier must not be empty");
664 }
665 if(m_key_id.size() > MaximumKeyIdentifierLength) {
666 throw Decoding_Error(fmt("AuthorityKeyIdentifier keyIdentifier length {} exceeds limit of {} bytes",
667 m_key_id.size(),
668 MaximumKeyIdentifierLength));
669 }
670 }
671
672 // RFC 5280 4.2.1.6: GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
673 if(authority_cert_issuer.has_value() && authority_cert_issuer->is_empty()) {
674 throw Decoding_Error("AuthorityKeyIdentifier authorityCertIssuer must contain at least one GeneralName");
675 }
676
677 /*
678 * RFC 5280 Appendix A.2:
679 *
680 * authorityCertIssuer and authorityCertSerialNumber MUST both be
681 * present or both be absent
682 */
683 if(authority_cert_issuer.has_value() != authority_cert_serial.has_value()) {
684 throw Decoding_Error(
685 "AuthorityKeyIdentifier authorityCertIssuer and authorityCertSerialNumber must both be present or absent");
686 }
687
688 if(authority_cert_issuer.has_value()) {
689 m_authority_cert =
690 Authority_Cert_Identifier{std::move(*authority_cert_issuer), std::move(*authority_cert_serial)};
691 }
692}
693
694/*
695* Encode the extension
696*/
697std::vector<uint8_t> Subject_Alternative_Name::encode_inner() const {
698 std::vector<uint8_t> output;
699 DER_Encoder(output).encode(m_alt_name);
700 return output;
701}
702
703/*
704* Encode the extension
705*/
706std::vector<uint8_t> Issuer_Alternative_Name::encode_inner() const {
707 std::vector<uint8_t> output;
708 DER_Encoder(output).encode(m_alt_name);
709 return output;
710}
711
712/*
713* Decode the extension
714*/
715void Subject_Alternative_Name::decode_inner(const std::vector<uint8_t>& in) {
716 /* RFC 5280 Section 4.2.1.6 - SubjectAltName ::= GeneralNames
717 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName */
718 BER_Decoder(in, BER_Decoder::Limits::DER()).decode(m_alt_name).verify_end();
719 if(!m_alt_name.has_items()) {
720 throw Decoding_Error("SubjectAlternativeName extension must contain at least one GeneralName");
721 }
722}
723
724/*
725* Decode the extension
726*/
727void Issuer_Alternative_Name::decode_inner(const std::vector<uint8_t>& in) {
728 /* RFC 5280 Section 4.2.1.7 - IssuerAltName ::= GeneralNames
729 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName */
730 BER_Decoder(in, BER_Decoder::Limits::DER()).decode(m_alt_name).verify_end();
731 if(!m_alt_name.has_items()) {
732 throw Decoding_Error("IssuerAlternativeName extension must contain at least one GeneralName");
733 }
734}
735
736/*
737* Encode the extension
738*/
739std::vector<uint8_t> Extended_Key_Usage::encode_inner() const {
740 std::vector<uint8_t> output;
741 DER_Encoder(output).start_sequence().encode_list(m_oids).end_cons();
742 return output;
743}
744
745/*
746* Decode the extension
747*/
748void Extended_Key_Usage::decode_inner(const std::vector<uint8_t>& in) {
749 /* RFC 5280 Section 4.2.1.12 - ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId */
750 BER_Decoder(in, BER_Decoder::Limits::DER()).decode_list(m_oids).verify_end();
751 if(m_oids.empty()) {
752 throw Decoding_Error("ExtendedKeyUsage extension must contain at least one KeyPurposeId");
753 }
754}
755
756/*
757* Encode the extension
758*/
759std::vector<uint8_t> Name_Constraints::encode_inner() const {
760 const auto& permitted = m_name_constraints.permitted();
761 const auto& excluded = m_name_constraints.excluded();
762
763 if(permitted.empty() && excluded.empty()) {
764 throw Encoding_Error("Refusing to encode empty NameConstraints");
765 }
766
767 std::vector<uint8_t> output;
768 DER_Encoder der(output);
769 der.start_sequence();
770 if(!permitted.empty()) {
771 der.start_explicit_context_specific(0).encode_list(permitted).end_cons();
772 }
773 if(!excluded.empty()) {
774 der.start_explicit_context_specific(1).encode_list(excluded).end_cons();
775 }
776 der.end_cons();
777 return output;
778}
779
780/*
781* Decode the extension
782*/
783void Name_Constraints::decode_inner(const std::vector<uint8_t>& in) {
784 /*
785 * RFC 5280 Section 4.2.1.10
786 *
787 * NameConstraints ::= SEQUENCE {
788 * permittedSubtrees [0] GeneralSubtrees OPTIONAL,
789 * excludedSubtrees [1] GeneralSubtrees OPTIONAL }
790 */
791 BER_Decoder ber(in, BER_Decoder::Limits::DER());
792 BER_Decoder inner = ber.start_sequence();
793
794 std::vector<GeneralSubtree> permitted;
795 if(inner.decode_optional_list(permitted, ASN1_Type(0), ASN1_Class::ExplicitContextSpecific)) {
796 if(permitted.empty()) {
797 throw Decoding_Error("Empty NameConstraint permitted list");
798 }
799 }
800
801 std::vector<GeneralSubtree> excluded;
802 if(inner.decode_optional_list(excluded, ASN1_Type(1), ASN1_Class::ExplicitContextSpecific)) {
803 if(excluded.empty()) {
804 throw Decoding_Error("Empty NameConstraint excluded list");
805 }
806 }
807
808 inner.end_cons();
809 ber.verify_end();
810
811 if(permitted.empty() && excluded.empty()) {
812 throw Decoding_Error("Empty NameConstraint extension");
813 }
814
815 m_name_constraints = NameConstraints(std::move(permitted), std::move(excluded));
816}
817
819 const std::optional<X509_Certificate>& /*issuer*/,
820 const std::vector<X509_Certificate>& cert_path,
821 std::vector<std::set<Certificate_Status_Code>>& cert_status,
822 size_t pos) const {
823 if(!m_name_constraints.permitted().empty() || !m_name_constraints.excluded().empty()) {
824 if(!subject.is_CA_cert()) {
825 cert_status.at(pos).insert(Certificate_Status_Code::NAME_CONSTRAINT_ERROR);
826 }
827
828 const bool issuer_name_constraint_critical = subject.is_critical("X509v3.NameConstraints");
829
830 // Check that all subordinate certs pass the name constraint
831 for(size_t j = 0; j < pos; ++j) {
832 const auto& cert = cert_path.at(j);
833
834 // RFC 5280 6.1.4(b): "Name constraints are not applied to self-issued
835 // certificates (unless the certificate is the final certificate in the path)"
836 // Position 0 is the end entity (final certificate); skip self-issued intermediates.
837 if(j > 0 && cert.issuer_dn() == cert.subject_dn()) {
838 continue;
839 }
840
841 if(!m_name_constraints.is_permitted(cert, issuer_name_constraint_critical)) {
842 cert_status.at(j).insert(Certificate_Status_Code::NAME_CONSTRAINT_ERROR);
843 continue;
844 }
845
846 if(m_name_constraints.is_excluded(cert, issuer_name_constraint_critical)) {
847 cert_status.at(j).insert(Certificate_Status_Code::NAME_CONSTRAINT_ERROR);
848 continue;
849 }
850 }
851 }
852}
853
854namespace {
855
856/*
857* A policy specifier
858*/
859class Policy_Information final : public ASN1_Object {
860 public:
861 Policy_Information() = default;
862
863 explicit Policy_Information(const OID& oid) : m_oid(oid) {}
864
865 const OID& oid() const { return m_oid; }
866
867 void encode_into(DER_Encoder& codec) const override { codec.start_sequence().encode(m_oid).end_cons(); }
868
869 void decode_from(BER_Decoder& codec) override {
870 codec.start_sequence().decode(m_oid).discard_remaining().end_cons();
871 }
872
873 private:
874 OID m_oid;
875};
876
877bool policy_oids_have_duplicate(const std::vector<OID>& oids) {
878 std::set<OID> seen;
879 for(const auto& oid : oids) {
880 if(!seen.insert(oid).second) {
881 return true;
882 }
883 }
884 return false;
885}
886
887} // namespace
888
889Certificate_Policies::Certificate_Policies(const std::vector<OID>& oids) :
890 m_oids(oids), m_has_duplicate(policy_oids_have_duplicate(m_oids)) {}
891
892/*
893* Encode the extension
894*/
895std::vector<uint8_t> Certificate_Policies::encode_inner() const {
896 std::vector<Policy_Information> policies;
897
898 policies.reserve(m_oids.size());
899 for(const auto& oid : m_oids) {
900 policies.push_back(Policy_Information(oid));
901 }
902
903 std::vector<uint8_t> output;
904 DER_Encoder(output).start_sequence().encode_list(policies).end_cons();
905 return output;
906}
907
908/*
909* Decode the extension
910*/
911void Certificate_Policies::decode_inner(const std::vector<uint8_t>& in) {
912 /* RFC 5280 Section 4.2.1.4 - CertificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation */
913 std::vector<Policy_Information> policies;
914
915 BER_Decoder(in, BER_Decoder::Limits::DER()).decode_list(policies).verify_end();
916 if(policies.empty()) {
917 throw Decoding_Error("CertificatePolicies extension must contain at least one PolicyInformation");
918 }
919 m_oids.clear();
920 for(const auto& policy : policies) {
921 m_oids.push_back(policy.oid());
922 }
923 m_has_duplicate = policy_oids_have_duplicate(m_oids);
924}
925
927 const std::optional<X509_Certificate>& /*issuer*/,
928 const std::vector<X509_Certificate>& /*cert_path*/,
929 std::vector<std::set<Certificate_Status_Code>>& cert_status,
930 size_t pos) const {
931 if(m_has_duplicate) {
932 cert_status.at(pos).insert(Certificate_Status_Code::DUPLICATE_CERT_POLICY);
933 }
934}
935
936namespace {
937
938std::vector<URI> parse_aia_uris(const std::vector<std::string>& uris, const char* context) {
939 std::vector<URI> out;
940 out.reserve(uris.size());
941 for(const auto& uri : uris) {
942 if(auto parsed = URI::from_string(uri)) {
943 out.push_back(std::move(*parsed));
944 } else {
945 throw Invalid_Argument(fmt("Invalid URI in {}", context));
946 }
947 }
948 return out;
949}
950
951// Convert the application provided URIs into AccessDescription entries
952std::vector<Authority_Information_Access::AccessDescription> uri_access_descriptions(
953 const std::vector<URI>& ocsp_responders, const std::vector<URI>& ca_issuers) {
954 std::vector<Authority_Information_Access::AccessDescription> out;
955 out.reserve(ocsp_responders.size() + ca_issuers.size());
956
957 const auto append = [&](const OID& method, const std::vector<URI>& uris) {
958 for(const auto& uri : uris) {
959 const ASN1_String value(uri.original_input(), ASN1_Type::Ia5String);
960 out.emplace_back(method,
961 ASN1_Type(6),
963 std::vector<uint8_t>(value.value().begin(), value.value().end()));
964 }
965 };
966
967 append(OID::from_string("PKIX.OCSP"), ocsp_responders);
968 append(OID::from_string("PKIX.CertificateAuthorityIssuers"), ca_issuers);
969 return out;
970}
971
972} // namespace
973
975 const std::vector<std::string>& ca_issuers) :
976 m_ca_issuers(parse_aia_uris(ca_issuers, "AuthorityInformationAccess CA issuers")) {
977 if(!ocsp.empty()) {
978 if(auto parsed = URI::from_string(ocsp)) {
979 m_ocsp_responders.push_back(std::move(*parsed));
980 } else {
981 throw Invalid_Argument("Invalid URI in AuthorityInformationAccess OCSP responder");
982 }
983 }
984 m_access_descriptions = uri_access_descriptions(m_ocsp_responders, m_ca_issuers);
985}
986
988 const std::vector<std::string>& ca_issuers) :
989 m_ocsp_responders(parse_aia_uris(ocsp_responders, "AuthorityInformationAccess OCSP responders")),
990 m_ca_issuers(parse_aia_uris(ca_issuers, "AuthorityInformationAccess CA issuers")),
991 m_access_descriptions(uri_access_descriptions(m_ocsp_responders, m_ca_issuers)) {}
992
994 std::vector<URI> ca_issuers) :
995 m_ocsp_responders(std::move(ocsp_responders)),
996 m_ca_issuers(std::move(ca_issuers)),
997 m_access_descriptions(uri_access_descriptions(m_ocsp_responders, m_ca_issuers)) {}
998
999std::vector<std::string> Authority_Information_Access::ocsp_responders() const {
1000 std::vector<std::string> out;
1001 out.reserve(m_ocsp_responders.size());
1002 for(const auto& uri : m_ocsp_responders) {
1003 out.push_back(uri.original_input());
1004 }
1005 return out;
1006}
1007
1008std::unique_ptr<Certificate_Extension> Authority_Information_Access::copy() const {
1009 return std::make_unique<Authority_Information_Access>(*this);
1010}
1011
1012namespace {
1013
1014void validate_general_name_encoding(ASN1_Type tag, ASN1_Class cls, std::span<const uint8_t> value) {
1015 // AlternativeName decodes GeneralNames; AIA accessLocation is a single GeneralName.
1016 std::vector<uint8_t> wrapped_name;
1017 DER_Encoder(wrapped_name).start_sequence().add_object(tag, cls, value).end_cons();
1018
1019 AlternativeName decoded_name;
1020 BER_Decoder(wrapped_name, BER_Decoder::Limits::DER()).decode(decoded_name).verify_end();
1021
1022 if((tag == ASN1_Type(1) || tag == ASN1_Type(2) || tag == ASN1_Type(6)) && value.empty()) {
1023 throw Decoding_Error("GeneralName IA5String value must not be empty");
1024 }
1025 if(tag == ASN1_Type(4) &&
1026 std::ranges::any_of(decoded_name.directory_names(), [](const X509_DN& dn) { return dn.empty(); })) {
1027 throw Decoding_Error("GeneralName directoryName must not be empty");
1028 }
1029}
1030
1031// Construction-time validation for an AccessDescription entering
1032// m_access_descriptions. encode_inner repeats this as a safety net; doing it
1033// here means the throw lands where the caller is building the AIA.
1034void validate_access_description(const Authority_Information_Access::AccessDescription& ad) {
1035 try {
1036 validate_general_name_encoding(ad.location_tag(), ad.location_class(), ad.location_value());
1037 } catch(const Exception&) {
1038 throw Invalid_Argument("AccessDescription accessLocation is not a valid GeneralName");
1039 }
1040}
1041
1042// Mirror the decode-time logic that populates the typed URI accessors from
1043// id-ad-ocsp / id-ad-caIssuers entries. Used by the AccessDescription-based
1044// constructor and add_access_description so the two views stay consistent.
1045// An id-ad-ocsp / id-ad-caIssuers entry whose URI fails to parse is rejected
1046// here (mirroring decode_inner) so the typed accessors and m_access_descriptions
1047// cannot disagree, and so the AIA cannot re-encode bytes that its own decoder
1048// would reject.
1049void populate_uri_view_from_access_description(const Authority_Information_Access::AccessDescription& ad,
1050 std::vector<URI>& ocsp_responders,
1051 std::vector<URI>& ca_issuers) {
1052 const auto oid_ocsp_responders = OID::from_string("PKIX.OCSP");
1053 const auto oid_ca_issuers = OID::from_string("PKIX.CertificateAuthorityIssuers");
1054 if(const auto uri_str = ad.location_as_uri_string()) {
1055 if(ad.access_method() == oid_ocsp_responders) {
1056 if(auto uri = URI::from_string(*uri_str)) {
1057 ocsp_responders.push_back(std::move(*uri));
1058 } else {
1059 throw Invalid_Argument("Invalid URI in AuthorityInformationAccess OCSP responder");
1060 }
1061 } else if(ad.access_method() == oid_ca_issuers) {
1062 if(auto uri = URI::from_string(*uri_str)) {
1063 ca_issuers.push_back(std::move(*uri));
1064 } else {
1065 throw Invalid_Argument("Invalid URI in AuthorityInformationAccess CA issuers");
1066 }
1067 }
1068 }
1069}
1070
1071} // namespace
1072
1074 m_access_descriptions(std::move(access_descriptions)) {
1075 for(const auto& ad : m_access_descriptions) {
1076 validate_access_description(ad);
1077 populate_uri_view_from_access_description(ad, m_ocsp_responders, m_ca_issuers);
1078 }
1079}
1080
1082 validate_access_description(ad);
1083 populate_uri_view_from_access_description(ad, m_ocsp_responders, m_ca_issuers);
1084 m_access_descriptions.push_back(std::move(ad));
1085}
1086
1087std::vector<std::string> Authority_Information_Access::ca_issuers() const {
1088 std::vector<std::string> out;
1089 out.reserve(m_ca_issuers.size());
1090 for(const auto& uri : m_ca_issuers) {
1091 out.push_back(uri.original_input());
1092 }
1093 return out;
1094}
1095
1097 if(m_location_class == ASN1_Class::ContextSpecific && m_location_tag == ASN1_Type(6)) {
1098 return std::string(m_location_value.begin(), m_location_value.end());
1099 }
1100 return std::nullopt;
1101}
1102
1103std::vector<uint8_t> Authority_Information_Access::encode_inner() const {
1104 std::vector<uint8_t> output;
1105 DER_Encoder der(output);
1106
1107 der.start_sequence();
1108
1109 for(const auto& ad : m_access_descriptions) {
1110 try {
1111 validate_general_name_encoding(ad.location_tag(), ad.location_class(), ad.location_value());
1112 } catch(const Exception&) {
1113 throw Encoding_Error("AccessDescription accessLocation is not a valid GeneralName");
1114 }
1115 der.start_sequence()
1116 .encode(ad.access_method())
1117 .add_object(ad.location_tag(), ad.location_class(), ad.location_value())
1118 .end_cons();
1119 }
1120
1121 der.end_cons();
1122 return output;
1123}
1124
1125void Authority_Information_Access::decode_inner(const std::vector<uint8_t>& in) {
1126 /*
1127 * RFC 5280 Section 4.2.2.1
1128 *
1129 * AuthorityInfoAccessSyntax ::= SEQUENCE SIZE (1..MAX) OF AccessDescription
1130 * AccessDescription ::= SEQUENCE {
1131 * accessMethod OBJECT IDENTIFIER,
1132 * accessLocation GeneralName }
1133 */
1134 BER_Decoder outer(in, BER_Decoder::Limits::DER());
1135 BER_Decoder ber = outer.start_sequence();
1136
1137 const OID ocsp_responder = OID::from_string("PKIX.OCSP");
1138 const OID ca_issuer = OID::from_string("PKIX.CertificateAuthorityIssuers");
1139
1140 m_access_descriptions.clear();
1141 m_ocsp_responders.clear();
1142 m_ca_issuers.clear();
1143
1144 while(ber.more_items()) {
1145 OID oid;
1146
1147 BER_Decoder info = ber.start_sequence();
1148
1149 info.decode(oid);
1150 const BER_Object name = info.get_next_object();
1151
1152 /* RFC 5280 4.2.2.1:
1153 * AccessDescription ::= SEQUENCE {
1154 * accessMethod OBJECT IDENTIFIER,
1155 * accessLocation GeneralName }
1156 */
1157 if(!name.is_set()) {
1158 throw Decoding_Error("AuthorityInformationAccess AccessDescription missing accessLocation");
1159 }
1160 validate_general_name_encoding(name.type_tag(), name.get_class(), name.data());
1161 info.end_cons();
1162
1163 m_access_descriptions.emplace_back(
1164 oid, name.type_tag(), name.get_class(), std::vector<uint8_t>(name.data().begin(), name.data().end()));
1165
1166 if(name.is_a(6, ASN1_Class::ContextSpecific)) {
1167 if(oid == ocsp_responder) {
1168 if(auto parsed = URI::from_string(ASN1::to_string(name))) {
1169 m_ocsp_responders.push_back(std::move(*parsed));
1170 } else {
1171 throw Decoding_Error("Invalid URI in AuthorityInformationAccess OCSP responder");
1172 }
1173 } else if(oid == ca_issuer) {
1174 if(auto parsed = URI::from_string(ASN1::to_string(name))) {
1175 m_ca_issuers.push_back(std::move(*parsed));
1176 } else {
1177 throw Decoding_Error("Invalid URI in AuthorityInformationAccess CA issuers");
1178 }
1179 }
1180 }
1181 }
1182
1183 ber.end_cons();
1184 outer.verify_end();
1185
1186 if(m_access_descriptions.empty()) {
1187 throw Decoding_Error("AuthorityInformationAccess extension must contain at least one AccessDescription");
1188 }
1189}
1190
1191CRL_Number::CRL_Number(BigInt n) : m_has_value(true), m_crl_number(std::move(n)) {
1192 BOTAN_ARG_CHECK(m_crl_number.signum() >= 0, "CRL number cannot be negative");
1193}
1194
1196 // This can only happen via a misuse of the CRL_Number default constructor
1197 BOTAN_STATE_CHECK(m_has_value);
1198 return m_crl_number;
1199}
1200
1201/*
1202* Checked accessor for the crl_number member
1203*/
1205 // This can only happen via a misuse of the CRL_Number default constructor
1206 BOTAN_STATE_CHECK(m_has_value);
1207 return m_crl_number.to_u32bit();
1208}
1209
1210/*
1211* Copy a CRL_Number extension
1212*/
1213std::unique_ptr<Certificate_Extension> CRL_Number::copy() const {
1214 return std::make_unique<CRL_Number>(*this);
1215}
1216
1217/*
1218* Encode the extension
1219*/
1220std::vector<uint8_t> CRL_Number::encode_inner() const {
1221 std::vector<uint8_t> output;
1222 DER_Encoder(output).encode(m_crl_number);
1223 return output;
1224}
1225
1226/*
1227* Decode the extension
1228*/
1229void CRL_Number::decode_inner(const std::vector<uint8_t>& in) {
1230 /* RFC 5280 Section 5.2.3 - CRLNumber ::= INTEGER (0..MAX) */
1232 if(m_crl_number.signum() < 0) {
1233 throw Decoding_Error("CRL number cannot be negative");
1234 }
1235 m_has_value = true;
1236}
1237
1238/*
1239* Encode the extension
1240*/
1241std::vector<uint8_t> CRL_ReasonCode::encode_inner() const {
1242 std::vector<uint8_t> output;
1243 DER_Encoder(output).encode(static_cast<size_t>(m_reason), ASN1_Type::Enumerated, ASN1_Class::Universal);
1244 return output;
1245}
1246
1247/*
1248* Decode the extension
1249*/
1250void CRL_ReasonCode::decode_inner(const std::vector<uint8_t>& in) {
1251 /*
1252 * RFC 5280 Section 5.3.1
1253 *
1254 * CRLReason ::= ENUMERATED {
1255 * unspecified (0),
1256 * keyCompromise (1),
1257 * cACompromise (2),
1258 * affiliationChanged (3),
1259 * superseded (4),
1260 * cessationOfOperation (5),
1261 * certificateHold (6),
1262 * -- value 7 is not used
1263 * removeFromCRL (8),
1264 * privilegeWithdrawn (9),
1265 * aACompromise (10) }
1266 */
1267 size_t reason_code = 0;
1268 BER_Decoder(in, BER_Decoder::Limits::DER())
1269 .decode(reason_code, ASN1_Type::Enumerated, ASN1_Class::Universal)
1270 .verify_end();
1271
1272 if(reason_code == 7 || reason_code > 10) {
1273 throw Decoding_Error(fmt("CRLReason has unknown enumeration value {}", reason_code));
1274 }
1275
1276 m_reason = static_cast<CRL_Code>(reason_code);
1277}
1278
1279namespace {
1280
1281constexpr size_t ReasonFlagsNamedBitWidth = 9;
1282
1283void emit_reason_flags_implicit(DER_Encoder& der, uint32_t tag, ReasonFlags reasons) {
1284 der.encode_named_bitstring(reasons.value(), ReasonFlagsNamedBitWidth, ASN1_Type(tag), ASN1_Class::ContextSpecific);
1285}
1286
1287ReasonFlags decode_reason_flags_implicit(BER_Decoder& decoder, uint32_t tag) {
1288 uint64_t bits = 0;
1289 decoder.decode_named_bitstring(bits, ReasonFlagsNamedBitWidth, ASN1_Type(tag), ASN1_Class::ContextSpecific);
1290 return ReasonFlags(checked_cast_to<uint16_t>(bits));
1291}
1292
1293/*
1294* RFC 5280 4.2.1.13: "If present, the cRLIssuer MUST only contain the
1295* distinguished name (DN) from the issuer field of the CRL to which the
1296* DistributionPoint is pointing."
1297*
1298* We don't know the value of the CRL issuer at this point so we can only
1299* enforce that the cRLIssuer name is exactly one non-empty DN.
1300*/
1301bool crl_issuer_is_well_formed(const AlternativeName& crl_issuer) {
1302 const auto& dn = crl_issuer.directory_names();
1303 return crl_issuer.count() == 1 && dn.size() == 1 && !dn.begin()->empty();
1304}
1305
1306std::vector<URI> crl_distribution_point_uris_from_distribution_points(
1307 const std::vector<CRL_Distribution_Points::Distribution_Point>& dps) {
1308 std::vector<URI> out;
1309 for(const auto& dp : dps) {
1310 const auto& dpn = dp.distribution_point_name();
1311 if(dpn.has_value() && dpn->full_name().has_value()) {
1312 for(const auto& uri : dpn->full_name()->uri_names()) {
1313 out.push_back(uri);
1314 }
1315 }
1316 }
1317 return out;
1318}
1319
1320} // namespace
1321
1323 BOTAN_STATE_CHECK(m_dp_name.has_value() && m_dp_name->full_name().has_value());
1324 return *m_dp_name->full_name();
1325}
1326
1327CRL_Distribution_Points::CRL_Distribution_Points(const std::vector<Distribution_Point>& points) :
1328 m_distribution_points(points),
1329 m_crl_distribution_urls(crl_distribution_point_uris_from_distribution_points(m_distribution_points)) {}
1330
1332 BOTAN_STATE_CHECK(m_dp_name.has_value() && m_dp_name->full_name().has_value());
1333 return *m_dp_name->full_name();
1334}
1335
1337 if(!m_full_name.has_value()) {
1338 throw Encoding_Error("DistributionPointName has no fullName to encode");
1339 }
1340 // fullName [0] IMPLICIT GeneralNames. emit_general_names_implicit rejects
1341 // empty AlternativeNames per RFC 5280 4.2.1.6: GeneralNames ::= SEQUENCE
1342 // SIZE (1..MAX).
1343 emit_general_names_implicit(der, *m_full_name, 0);
1344}
1345
1347 const BER_Object& obj = ber.peek_next_object();
1351 ASN1_Type(0),
1355 // RFC 5280 4.2.1.6: GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1356 if(!full_name.has_items()) {
1357 throw Decoding_Error("DistributionPointName fullName must contain at least one GeneralName");
1358 }
1359 if(std::ranges::any_of(full_name.directory_names(), [](const X509_DN& dn) { return dn.empty(); })) {
1360 throw Decoding_Error("DistributionPointName fullName must not contain an empty directoryName");
1361 }
1362 m_full_name = std::move(full_name);
1364 throw Decoding_Error("nameRelativeToCrlIssuer not supported in DistributionPointName");
1365 } else {
1366 throw Decoding_Error("DistributionPointName CHOICE is neither fullName nor nameRelativeToCRLIssuer");
1367 }
1368}
1369
1370std::vector<uint8_t> CRL_Distribution_Points::encode_inner() const {
1371 std::vector<uint8_t> output;
1372 DER_Encoder(output).start_sequence().encode_list(m_distribution_points).end_cons();
1373 return output;
1374}
1375
1376void CRL_Distribution_Points::decode_inner(const std::vector<uint8_t>& buf) {
1377 /*
1378 * RFC 5280 Section 4.2.1.13
1379 *
1380 * CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1381 */
1382 BER_Decoder(buf, BER_Decoder::Limits::DER()).decode_list(m_distribution_points).verify_end();
1383
1384 if(m_distribution_points.empty()) {
1385 throw Decoding_Error("CRLDistributionPoints extension must contain at least one DistributionPoint");
1386 }
1387
1388 m_crl_distribution_urls = crl_distribution_point_uris_from_distribution_points(m_distribution_points);
1389}
1390
1391std::vector<std::string> CRL_Distribution_Points::crl_distribution_urls() const {
1392 std::vector<std::string> out;
1393 out.reserve(m_crl_distribution_urls.size());
1394 for(const auto& uri : m_crl_distribution_urls) {
1395 out.push_back(uri.original_input());
1396 }
1397 return out;
1398}
1399
1401 /*
1402 * DistributionPoint ::= SEQUENCE {
1403 * distributionPoint [0] DistributionPointName OPTIONAL,
1404 * reasons [1] ReasonFlags OPTIONAL,
1405 * cRLIssuer [2] GeneralNames OPTIONAL }
1406 *
1407 * RFC 5280 4.2.1.13: "either distributionPoint or cRLIssuer MUST be present".
1408 */
1409 const bool has_dp_name = m_dp_name.has_value();
1410 const bool has_crl_issuer = m_crl_issuer.has_value();
1411 if(!has_dp_name && !has_crl_issuer) {
1412 throw Encoding_Error("DistributionPoint must contain either distributionPoint or cRLIssuer");
1413 }
1414 if(has_crl_issuer && !crl_issuer_is_well_formed(*m_crl_issuer)) {
1415 /* RFC 5280 4.2.1.13: "If present, the cRLIssuer MUST only contain the
1416 * distinguished name (DN) from the issuer field of the CRL". */
1417 throw Encoding_Error("cRLIssuer must contain exactly one non-empty directoryName GeneralName");
1418 }
1419
1420 der.start_sequence();
1421
1422 if(has_dp_name) {
1423 // distributionPoint [0] EXPLICIT DistributionPointName
1424 der.start_explicit_context_specific(0).encode(*m_dp_name).end_cons();
1425 }
1426
1427 if(m_reasons) {
1428 emit_reason_flags_implicit(der, 1, *m_reasons);
1429 }
1430
1431 if(has_crl_issuer) {
1432 emit_general_names_implicit(der, *m_crl_issuer, 2);
1433 }
1434
1435 der.end_cons();
1436}
1437
1439 /*
1440 * DistributionPoint ::= SEQUENCE {
1441 * distributionPoint [0] DistributionPointName OPTIONAL,
1442 * reasons [1] ReasonFlags OPTIONAL,
1443 * cRLIssuer [2] GeneralNames OPTIONAL }
1444 */
1445 BER_Decoder dp = ber.start_sequence();
1446
1447 m_dp_name.reset();
1448 m_reasons.reset();
1449 m_crl_issuer.reset();
1450
1451 // DER: these optional fields appear at most once and in increasing tag
1452 // order. Decoding them in tag order and then rejecting anything left over
1453 // (see end_cons below) catches out-of-order, duplicate, and unknown fields.
1456 [&](BER_Decoder& d) {
1459 m_dp_name = std::move(name);
1460 })
1461 .decode_optional_field(
1462 1, ASN1_Class::ContextSpecific, [&](BER_Decoder& d) { m_reasons = decode_reason_flags_implicit(d, 1); })
1463 .decode_optional_field(2, ASN1_Class::ContextSpecific | ASN1_Class::Constructed, [&](BER_Decoder& d) {
1466 ASN1_Type(2),
1470 m_crl_issuer = std::move(crl_issuer);
1471 });
1472
1473 dp.end_cons();
1474
1475 // RFC 5280 4.2.1.6: GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1476 if(m_crl_issuer.has_value() && m_crl_issuer->is_empty()) {
1477 throw Decoding_Error("cRLIssuer GeneralNames must contain at least one GeneralName");
1478 }
1479
1480 if(m_crl_issuer.has_value() && !crl_issuer_is_well_formed(*m_crl_issuer)) {
1481 /* RFC 5280 4.2.1.13: "If present, the cRLIssuer MUST only contain the
1482 * distinguished name (DN) from the issuer field of the CRL". */
1483 throw Decoding_Error("cRLIssuer must contain exactly one non-empty directoryName GeneralName");
1484 }
1485
1486 if(!m_dp_name.has_value() && !m_crl_issuer.has_value()) {
1487 throw Decoding_Error("DistributionPoint must contain either distributionPoint or cRLIssuer");
1488 }
1489}
1490
1491std::vector<uint8_t> CRL_Issuing_Distribution_Point::encode_inner() const {
1492 /* RFC 5280 Section 5.2.5
1493 *
1494 * Conforming CRL issuers MUST NOT issue CRLs where the DER encoding of the
1495 * issuing distribution point extension is an empty sequence. [...] at most one
1496 * of onlyContainsUserCerts, onlyContainsCACerts, and onlyContainsAttributeCerts
1497 * may be set to TRUE
1498 */
1499 if(!should_encode()) {
1500 throw Encoding_Error("Refusing to encode empty IssuingDistributionPoint");
1501 }
1502
1503 const size_t scope_set = static_cast<size_t>(m_only_contains_user_certs) +
1504 static_cast<size_t>(m_only_contains_ca_certs) +
1505 static_cast<size_t>(m_only_contains_attribute_certs);
1506 if(scope_set > 1) {
1507 throw Encoding_Error(
1508 "At most one of onlyContainsUserCerts, onlyContainsCACerts, onlyContainsAttributeCerts may be TRUE");
1509 }
1510
1511 const auto emit_optional_boolean_implicit = [](DER_Encoder& der, uint32_t tag, bool value) {
1512 // All of the values encoded here are DEFAULT FALSE so skip encoding if false
1513 if(value == true) {
1514 // Encode a BOOLEAN TRUE (0xFF) as [tag] IMPLICIT BOOLEAN
1515 const uint8_t val = 0xFF;
1517 }
1518 };
1519
1520 std::vector<uint8_t> output;
1521 DER_Encoder der(output);
1522 der.start_sequence();
1523
1524 if(m_dp_name.has_value()) {
1525 der.start_explicit_context_specific(0).encode(*m_dp_name).end_cons();
1526 }
1527
1528 emit_optional_boolean_implicit(der, 1, m_only_contains_user_certs);
1529 emit_optional_boolean_implicit(der, 2, m_only_contains_ca_certs);
1530
1531 if(m_only_some_reasons) {
1532 emit_reason_flags_implicit(der, 3, *m_only_some_reasons);
1533 }
1534
1535 emit_optional_boolean_implicit(der, 4, m_indirect_crl);
1536 emit_optional_boolean_implicit(der, 5, m_only_contains_attribute_certs);
1537
1538 der.end_cons();
1539 return output;
1540}
1541
1542void CRL_Issuing_Distribution_Point::decode_inner(const std::vector<uint8_t>& buf) {
1543 /*
1544 * RFC 5280 Section 5.2.5
1545 *
1546 * IssuingDistributionPoint ::= SEQUENCE {
1547 * distributionPoint [0] DistributionPointName OPTIONAL,
1548 * onlyContainsUserCerts [1] BOOLEAN DEFAULT FALSE,
1549 * onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE,
1550 * onlySomeReasons [3] ReasonFlags OPTIONAL,
1551 * indirectCRL [4] BOOLEAN DEFAULT FALSE,
1552 * onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE }
1553 */
1554 BER_Decoder outer(buf, BER_Decoder::Limits::DER());
1555 BER_Decoder seq = outer.start_sequence();
1556
1557 m_dp_name.reset();
1558 m_only_contains_user_certs = false;
1559 m_only_contains_ca_certs = false;
1560 m_only_some_reasons = {};
1561 m_indirect_crl = false;
1562 m_only_contains_attribute_certs = false;
1563
1564 auto decode_implicit_bool = [&](BER_Decoder& dec, uint32_t tag) -> bool {
1565 bool value = false;
1566 dec.decode(value, ASN1_Type(tag), ASN1_Class::ContextSpecific);
1567 return value;
1568 };
1569
1570 // DER: these optional fields appear at most once and in increasing tag
1571 // order. Decoding them in tag order and then rejecting anything left over
1572 // (see end_cons below) catches out-of-order, duplicate, and unknown fields.
1573 seq.decode_optional_field(0,
1575 [&](BER_Decoder& d) {
1576 DistributionPointName name;
1577 d.start_context_specific(0).decode(name).verify_end();
1578 m_dp_name = std::move(name);
1579 })
1580 .decode_optional_field(1,
1582 [&](BER_Decoder& d) { m_only_contains_user_certs = decode_implicit_bool(d, 1); })
1583 .decode_optional_field(
1584 2, ASN1_Class::ContextSpecific, [&](BER_Decoder& d) { m_only_contains_ca_certs = decode_implicit_bool(d, 2); })
1585 .decode_optional_field(3,
1587 [&](BER_Decoder& d) { m_only_some_reasons = decode_reason_flags_implicit(d, 3); })
1588 .decode_optional_field(
1589 4, ASN1_Class::ContextSpecific, [&](BER_Decoder& d) { m_indirect_crl = decode_implicit_bool(d, 4); })
1590 .decode_optional_field(5, ASN1_Class::ContextSpecific, [&](BER_Decoder& d) {
1591 m_only_contains_attribute_certs = decode_implicit_bool(d, 5);
1592 });
1593
1594 seq.end_cons();
1595 outer.verify_end();
1596
1597 /* RFC 5280 5.2.5: "Conforming CRLs issuers MUST NOT issue CRLs where the
1598 * DER encoding of the issuing distribution point extension is an empty
1599 * sequence." Empty here means none of the fields above were present. */
1600 if(!m_dp_name.has_value() && !m_only_contains_user_certs && !m_only_contains_ca_certs &&
1601 !m_only_some_reasons.has_value() && !m_indirect_crl && !m_only_contains_attribute_certs) {
1602 throw Decoding_Error("IssuingDistributionPoint must contain at least one field");
1603 }
1604
1605 /* RFC 5280 5.2.5: "at most one of onlyContainsUserCerts,
1606 * onlyContainsCACerts, and onlyContainsAttributeCerts may be set to TRUE." */
1607 const size_t scope_set = static_cast<size_t>(m_only_contains_user_certs) +
1608 static_cast<size_t>(m_only_contains_ca_certs) +
1609 static_cast<size_t>(m_only_contains_attribute_certs);
1610 if(scope_set > 1) {
1611 throw Decoding_Error(
1612 "IssuingDistributionPoint sets more than one of onlyContainsUserCerts/CACerts/AttributeCerts");
1613 }
1614}
1615
1617 if(spc.empty()) {
1618 throw Invalid_Argument("TNAuthList service provider code cannot be empty");
1619 }
1620 Entry entry;
1621 entry.m_type = ServiceProviderCode;
1622 // Constructing the ASN1_String checks that the code is valid IA5
1623 entry.m_data = ASN1_String(spc, ASN1_Type::Ia5String).value();
1624 return entry;
1625}
1626
1628 // count INTEGER (2..MAX)
1629 if(range.count() < 2) {
1630 throw Invalid_Argument("TNAuthList range must contain at least two numbers");
1631 }
1632 Entry entry;
1633 entry.set_range(range);
1634 return entry;
1635}
1636
1638 Entry entry;
1639 entry.m_type = TelephoneNumber;
1640 entry.m_data = tn;
1641 return entry;
1642}
1643
1645 switch(m_type) {
1649 .end_cons();
1650 return;
1655 .encode(BigInt::from_u64(range().count()))
1656 .end_cons()
1657 .end_cons();
1658 return;
1659 case TelephoneNumber:
1661 return;
1662 }
1663
1664 throw Invalid_State("TNAuthList::Entry has an invalid type");
1665}
1666
1668 const auto decode_ia5_string = [](BER_Decoder& from, std::string_view what) {
1669 ASN1_String str;
1670 from.decode(str);
1671 if(str.tagging() != ASN1_Type::Ia5String) {
1672 throw Decoding_Error(fmt("TNAuthList {} must be an IA5String", what));
1673 }
1674 return str.value();
1675 };
1676
1677 const BER_Object obj = ber.get_next_object();
1678
1679 // The TNEntry alternatives are explicitly tagged so each is constructed
1681 throw Decoding_Error(fmt("Unexpected TNEntry class tag {}", static_cast<uint32_t>(obj.get_class())));
1682 }
1683
1684 const uint32_t type_tag = static_cast<uint32_t>(obj.type_tag());
1685 BER_Decoder inner(obj, ber.limits());
1686
1687 if(type_tag == ServiceProviderCode) {
1688 m_type = ServiceProviderCode;
1689 m_data = decode_ia5_string(inner, "ServiceProviderCode");
1690 } else if(type_tag == TelephoneNumberRange) {
1692
1693 const auto start = Botan::TelephoneNumber::from_string(decode_ia5_string(range, "TelephoneNumberRange start"));
1694 if(!start.has_value()) {
1695 throw Decoding_Error("Invalid TelephoneNumberRange start");
1696 }
1697
1698 BigInt count;
1699 range.decode(count);
1700 // count INTEGER (2..MAX), but no value over 64 bits fits within a 15 digit number
1701 if(count.is_negative() || count.bits() > 64) {
1702 throw Decoding_Error("Invalid TelephoneNumberRange count");
1703 }
1704 uint64_t count_value = 0;
1705 for(size_t i = 0; i != 8; ++i) {
1706 count_value = (count_value << 8) | count.byte_at(7 - i);
1707 }
1708 if(count_value < 2) {
1709 throw Decoding_Error("Invalid TelephoneNumberRange count");
1710 }
1711
1712 auto tn_range = Botan::TelephoneNumberRange::from(*start, count_value);
1713 if(!tn_range.has_value()) {
1714 throw Decoding_Error("Invalid TelephoneNumberRange");
1715 }
1716
1717 // TelephoneNumberRange is extensible; skip any additions following count
1718 while(range.more_items()) {
1719 range.get_next_object();
1720 }
1721 range.end_cons();
1722
1723 set_range(std::move(*tn_range));
1724 } else if(type_tag == TelephoneNumber) {
1725 m_type = TelephoneNumber;
1726 auto tn = Botan::TelephoneNumber::from_string(decode_ia5_string(inner, "TelephoneNumber"));
1727 if(!tn.has_value()) {
1728 throw Decoding_Error("Invalid TelephoneNumber");
1729 }
1730 m_data = std::move(*tn);
1731 } else {
1732 throw Decoding_Error(fmt("Unexpected TNEntry type code {}", type_tag));
1733 }
1734
1735 inner.verify_end();
1736}
1737
1738TNAuthList::TNAuthList(std::vector<Entry> entries) : m_tn_entries(std::move(entries)) {
1739 if(m_tn_entries.empty()) {
1740 throw Invalid_Argument("TNAuthList requires at least one entry");
1741 }
1742}
1743
1744TNAuthList TNAuthList::from_der(std::span<const uint8_t> der) {
1745 TNAuthList list;
1746 list.decode_inner(std::vector<uint8_t>(der.begin(), der.end()));
1747 return list;
1748}
1749
1750std::vector<uint8_t> TNAuthList::encode_inner() const {
1751 std::vector<uint8_t> output;
1752 DER_Encoder(output).start_sequence().encode_list(m_tn_entries).end_cons();
1753 return output;
1754}
1755
1756void TNAuthList::decode_inner(const std::vector<uint8_t>& in) {
1757 /* RFC 8226 Section 9 - TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry */
1758 m_tn_entries.clear();
1760 if(m_tn_entries.empty()) {
1761 throw Decoding_Error("TNAuthorizationList is empty");
1762 }
1763}
1764
1767 return std::get<std::string>(m_data);
1768}
1769
1772 return std::get<Botan::TelephoneNumberRange>(m_data);
1773}
1774
1777 return std::get<Botan::TelephoneNumber>(m_data);
1778}
1779
1780void TNAuthList::Entry::set_range(Botan::TelephoneNumberRange range) {
1781 m_type = TelephoneNumberRange;
1782 m_legacy_range.clear();
1783 if(std::in_range<size_t>(range.count())) {
1784 m_legacy_range.push_back(TelephoneNumberRangeData{ASN1_String(range.start().to_string(), ASN1_Type::Ia5String),
1785 static_cast<size_t>(range.count())});
1786 }
1787 m_data = std::move(range);
1788}
1789
1792 if(m_legacy_range.empty()) {
1793 throw Invalid_State("TNAuthList range count does not fit in size_t, use range() instead");
1794 }
1795 return m_legacy_range;
1796}
1797
1798const std::string& TNAuthList::Entry::telephone_number() const {
1799 return number().to_string();
1800}
1801
1802/*
1803* RFC 9060 Section 4:
1804* "each delegate certificate MUST have a TNAuthList scope that is equal to or
1805* a subset of its parent certificate's scope: it must be "encompassed"."
1806*
1807* RFC 9060 Section 4.1:
1808* "this specification explicitly permits SPC-only parent certificates to
1809* delegate individual telephone numbers or ranges to a child certificate"
1810*/
1811bool TNAuthList::encompasses(const TNAuthList& delegate) const {
1812 // A block of numbers as (length, first, last); a number of another length is a
1813 // different number even if its value falls inside
1814 class TN_Interval final {
1815 public:
1816 explicit TN_Interval(const TelephoneNumber& tn) :
1817 m_length(tn.length()), m_first(tn.numeric_value().value()), m_last(m_first) {}
1818
1819 explicit TN_Interval(const TelephoneNumberRange& range) :
1820 m_length(range.start().length()),
1821 m_first(range.start().numeric_value().value()),
1822 m_last(m_first + range.count() - 1) {}
1823
1824 size_t length() const { return m_length; }
1825
1826 uint64_t first() const { return m_first; }
1827
1828 uint64_t last() const { return m_last; }
1829
1830 void update_last(uint64_t last) { m_last = last; }
1831
1832 bool operator<(const TN_Interval& other) const {
1833 return std::tie(m_length, m_first) < std::tie(other.m_length, other.m_first);
1834 }
1835
1836 private:
1837 size_t m_length;
1838 uint64_t m_first;
1839 uint64_t m_last;
1840 };
1841
1842 // Sort by (length, first) and coalesce overlapping or adjacent blocks of the same length
1843 const auto merge_intervals = [](std::vector<TN_Interval> intervals) {
1844 std::sort(intervals.begin(), intervals.end());
1845 std::vector<TN_Interval> merged;
1846 for(const auto& interval : intervals) {
1847 if(!merged.empty() && merged.back().length() == interval.length() &&
1848 interval.first() <= merged.back().last() + 1) {
1849 merged.back().update_last(std::max(merged.back().last(), interval.last()));
1850 } else {
1851 merged.push_back(interval);
1852 }
1853 }
1854 return merged;
1855 };
1856
1857 const auto is_covered = [](const TN_Interval& child, std::span<const TN_Interval> merged) {
1858 // The blocks are disjoint and sorted, so the only candidate is the last one starting at or before the child
1859 const auto after = std::upper_bound(merged.begin(), merged.end(), child);
1860 if(after == merged.begin()) {
1861 return false;
1862 }
1863 const TN_Interval& block = *(after - 1);
1864 return block.length() == child.length() && block.first() <= child.first() && child.last() <= block.last();
1865 };
1866
1867 std::set<std::string> spcs;
1868 std::set<TelephoneNumber> wildcards;
1869 std::vector<TN_Interval> intervals;
1870
1871 for(const auto& entry : m_tn_entries) {
1872 switch(entry.type()) {
1874 spcs.insert(entry.service_provider_code());
1875 break;
1877 if(entry.number().is_wildcard()) {
1878 wildcards.insert(entry.number());
1879 } else {
1880 intervals.emplace_back(entry.number());
1881 }
1882 break;
1884 intervals.emplace_back(entry.range());
1885 break;
1886 }
1887 }
1888
1889 const std::vector<TN_Interval> merged = merge_intervals(std::move(intervals));
1890
1891 for(const auto& entry : delegate.entries()) {
1892 switch(entry.type()) {
1894 if(!spcs.contains(entry.service_provider_code())) {
1895 return false;
1896 }
1897 break;
1899 if(!spcs.empty()) {
1900 break;
1901 }
1902 if(entry.number().is_wildcard()) {
1903 if(!wildcards.contains(entry.number())) {
1904 return false;
1905 }
1906 } else if(!is_covered(TN_Interval(entry.number()), merged)) {
1907 return false;
1908 }
1909 break;
1911 if(!spcs.empty()) {
1912 break;
1913 }
1914 if(!is_covered(TN_Interval(entry.range()), merged)) {
1915 return false;
1916 }
1917 break;
1918 }
1919 }
1920
1921 return true;
1922}
1923
1924/*
1925* RFC 8226 Section 9:
1926* "In a CA certificate, the TN Authorization List limits the set of TNs for
1927* certification paths that include this certificate."
1928*/
1930 const std::optional<X509_Certificate>& /*issuer*/,
1931 const std::vector<X509_Certificate>& cert_path,
1932 std::vector<std::set<Certificate_Status_Code>>& cert_status,
1933 size_t pos) const {
1934 for(size_t i = pos + 1; i < cert_path.size(); ++i) {
1935 // A CA list that failed to decode is reported against the CA by Unknown_Extension
1936 const auto* ancestor = cert_path[i].v3_extensions().get_extension_object_as<TNAuthList>();
1937 if(ancestor != nullptr && !ancestor->encompasses(*this)) {
1938 cert_status.at(pos).insert(Certificate_Status_Code::TN_AUTH_LIST_ERROR);
1939 return;
1940 }
1941 }
1942}
1943
1944std::vector<uint8_t> IPAddressBlocks::encode_inner() const {
1945 std::vector<uint8_t> output;
1946 DER_Encoder(output).start_sequence().encode_list(m_ip_addr_blocks).end_cons();
1947 return output;
1948}
1949
1950void IPAddressBlocks::decode_inner(const std::vector<uint8_t>& in) {
1951 /* RFC 3779 Section 2.2.3.1 - IPAddrBlocks ::= SEQUENCE OF IPAddressFamily */
1953
1954 /* RFC 3779 Section 2.2.3.3
1955 *
1956 * There MUST be only one IPAddressFamily SEQUENCE per unique combination of
1957 * AFI and SAFI. Each SEQUENCE MUST be ordered by ascending addressFamily
1958 * values (treating the octets as unsigned quantities).
1959 *
1960 * Comparing (afi, safi) pairs matches the octet string ordering, since
1961 * a std::nullopt safi sorts before any actual safi value.
1962 */
1963 for(size_t i = 1; i < m_ip_addr_blocks.size(); i++) {
1964 const auto prev = std::make_pair(m_ip_addr_blocks[i - 1].afi(), m_ip_addr_blocks[i - 1].safi());
1965 const auto cur = std::make_pair(m_ip_addr_blocks[i].afi(), m_ip_addr_blocks[i].safi());
1966 if(prev >= cur) {
1967 throw Decoding_Error("IPAddrBlocks families must be sorted by AFI/SAFI and not repeat");
1968 }
1969 }
1970
1971 // IPAddressFamily::decode_from only accepts AFI 1 (IPv4) or 2 (IPv6)
1972 m_v4_count = 0;
1973 m_v6_count = 0;
1974 for(const IPAddressFamily& block : m_ip_addr_blocks) {
1975 if(block.afi() == 1) {
1976 m_v4_count++;
1977 } else {
1978 m_v6_count++;
1979 }
1980 }
1981}
1982
1984 into.start_sequence();
1985
1986 std::vector<uint8_t> afam = {get_byte<0>(m_afi), get_byte<1>(m_afi)};
1987
1988 if(m_safi.has_value()) {
1989 afam.push_back(m_safi.value());
1990 }
1991
1993
1994 if(std::holds_alternative<IPAddressChoice<Version::IPv4>>(m_ip_addr_choice)) {
1995 into.encode(std::get<IPAddressChoice<Version::IPv4>>(m_ip_addr_choice));
1996 } else {
1997 into.encode(std::get<IPAddressChoice<Version::IPv6>>(m_ip_addr_choice));
1998 }
1999 into.end_cons();
2000}
2001
2003 const ASN1_Type next_tag = from.peek_next_object().type_tag();
2004 if(next_tag != ASN1_Type::Sequence) {
2005 throw Decoding_Error(fmt("Unexpected type for IPAddressFamily {}", static_cast<uint32_t>(next_tag)));
2006 }
2007
2008 BER_Decoder seq_dec = from.start_sequence();
2009
2010 std::vector<uint8_t> addr_family;
2011 seq_dec.decode(addr_family, ASN1_Type::OctetString);
2012 const size_t addr_family_length = addr_family.size();
2013
2014 if(addr_family_length != 2 && addr_family_length != 3) {
2015 throw Decoding_Error("(S)AFI can only contain 2 or 3 bytes");
2016 }
2017
2018 m_afi = (addr_family[0] << 8) | addr_family[1];
2019
2020 if(addr_family_length == 3) {
2021 m_safi = addr_family[2];
2022 }
2023
2024 if(m_afi == 1) {
2026 seq_dec.decode(addr_choice);
2027 m_ip_addr_choice = addr_choice;
2028 } else if(m_afi == 2) {
2030 seq_dec.decode(addr_choice);
2031 m_ip_addr_choice = addr_choice;
2032 } else {
2033 throw Decoding_Error("Only AFI IPv4 and IPv6 are supported.");
2034 }
2035
2036 seq_dec.end_cons();
2037}
2038
2039namespace {
2040
2041template <IPAddressBlocks::Version V>
2042IPAddressBlocks::IPAddressFamily merge(std::vector<IPAddressBlocks::IPAddressFamily>& blocks) {
2043 // Merge IPAddressFamilies that have the same afi/safi combination
2044 //
2045 // see: https://www.rfc-editor.org/rfc/rfc3779.html#section-2.2.3.3
2046
2047 BOTAN_ASSERT(!blocks.empty(), "Cannot merge an empty set of IP address blocks into a single family");
2048
2049 // nothing to merge
2050 if(blocks.size() == 1) {
2051 return blocks[0];
2052 }
2053
2054 bool all_inherit = true;
2055 bool none_inherit = true;
2056 for(const IPAddressBlocks::IPAddressFamily& block : blocks) {
2057 const auto choice = std::get<IPAddressBlocks::IPAddressChoice<V>>(block.addr_choice());
2058 all_inherit = !choice.ranges().has_value() && all_inherit; // all the blocks have the 'inherit' value
2059 none_inherit = choice.ranges().has_value() && none_inherit;
2060 }
2061
2062 // they are all 'inherit', short-circuit using default constructor for nullopt
2063 if(all_inherit) {
2064 return IPAddressBlocks::IPAddressFamily(IPAddressBlocks::IPAddressChoice<V>(), blocks[0].safi());
2065 }
2066
2067 // some are inherit, and some have values - no sensible way to merge them
2068 if(!all_inherit && !none_inherit) {
2069 throw Decoding_Error("Invalid IPAddressBlocks: Only one of 'inherit' or 'do not inherit' is allowed per family");
2070 }
2071
2072 std::vector<IPAddressBlocks::IPAddressOrRange<V>> merged_ranges;
2073 for(const auto& block : blocks) {
2074 const auto choice = std::get<IPAddressBlocks::IPAddressChoice<V>>(block.addr_choice());
2075 const auto ranges = choice.ranges().value();
2076 for(const auto& r : ranges) {
2077 merged_ranges.push_back(r);
2078 }
2079 }
2080
2081 // we have extracted all the ranges, and now rely on the constructor of IPAddressChoice to merge them
2082 IPAddressBlocks::IPAddressChoice<V> choice(merged_ranges);
2083 IPAddressBlocks::IPAddressFamily fam(choice, blocks[0].safi());
2084 return fam;
2085}
2086
2087} // namespace
2088
2089void IPAddressBlocks::sort_and_merge() {
2090 // Sort IPAddressFamilies by afi/safi values
2091 //
2092 // see: https://www.rfc-editor.org/rfc/rfc3779.html#section-2.2.3.3
2093 //
2094 // v4 families are ordered before v6 families (i.e. they are sorted by afis, primarily),
2095 // families with no safis are ordered before families with safis
2096 //
2097 // families with the same afi/safi combination are then merged
2098
2099 // std::map is ordered, so using a pair (afi, optional(safi)) here works - std::nullopt is sorted before any actual values
2100 std::map<std::pair<uint16_t, std::optional<uint8_t>>, std::vector<IPAddressFamily>> afam_map;
2101 for(const IPAddressFamily& block : m_ip_addr_blocks) {
2102 const auto key = std::make_pair(block.afi(), block.safi());
2103 std::vector<IPAddressFamily>& fams = afam_map[key];
2104 fams.push_back(block);
2105 }
2106
2107 std::vector<IPAddressFamily> merged_blocks;
2108 size_t v4_count = 0;
2109 size_t v6_count = 0;
2110 for(auto& it : afam_map) {
2111 // fams consists of families with the same afi/safi combination
2112 std::vector<IPAddressFamily>& fams = it.second;
2113 // since at least 1 block has to belong to a afi/safi combination for it to appear in the map,
2114 // fams cannot be empty
2115 BOTAN_ASSERT_NOMSG(!fams.empty());
2116
2117 // fams[0] has to have the same choice type as the fams in the same bucket
2118 if(std::holds_alternative<IPAddressChoice<Version::IPv4>>(fams[0].addr_choice())) {
2119 merged_blocks.push_back(merge<Version::IPv4>(fams));
2120 v4_count++;
2121 } else {
2122 merged_blocks.push_back(merge<Version::IPv6>(fams));
2123 v6_count++;
2124 }
2125 }
2126 BOTAN_ASSERT_NOMSG(v4_count + v6_count == merged_blocks.size());
2127 m_ip_addr_blocks = std::move(merged_blocks);
2128 m_v4_count = v4_count;
2129 m_v6_count = v6_count;
2130}
2131
2132namespace {
2133
2134constexpr auto IPv4 = IPAddressBlocks::Version::IPv4;
2135constexpr auto IPv6 = IPAddressBlocks::Version::IPv6;
2136
2137template <IPAddressBlocks::Version V>
2138using IPRangeVec = std::vector<IPAddressBlocks::IPAddressOrRange<V>>;
2139
2140// (S)AFI -> (needs_check, ptr to IPRangeVec)
2141// the pointer can be null, in which case the boolean will be false, as such the pointer's value will never be looked at
2142template <IPAddressBlocks::Version V>
2143using IPValidationMap = std::map<uint32_t, std::pair<bool, const IPRangeVec<V>*>>;
2144
2145// The next address/AS number, wrapping to zero after the maximum value
2146template <IPAddressBlocks::Version V>
2147IPAddressBlocks::IPAddress<V> successor(const IPAddressBlocks::IPAddress<V>& addr) {
2148 auto bytes = addr.to_bytes();
2149 for(auto it = bytes.rbegin(); it != bytes.rend(); ++it) {
2150 (*it)++;
2151 if(*it != 0) {
2152 break;
2153 }
2154 }
2155 using Address = std::conditional_t<V == IPv4, IPv4Address, IPv6Address>;
2156 return IPAddressBlocks::IPAddress<V>(Address(bytes));
2157}
2158
2159template <std::unsigned_integral T>
2160T successor(T x) {
2161 return static_cast<T>(x + 1);
2162}
2163
2164template <typename T>
2165std::optional<std::vector<T>> sort_and_merge_ranges(std::optional<std::span<const T>> ranges) {
2166 // Sort and merge overlapping/adjacent IPAddressOrRange or ASIdOrRange objects.
2167 // cf. https://www.rfc-editor.org/rfc/rfc3779.html#section-2.2.3.6 and https://www.rfc-editor.org/rfc/rfc3779.html#section-3.2.3.4
2168 // This implementation uses only min-max ranges internally, so sorting by the prefix length is not necessary / impossible here.
2169
2170 if(!ranges.has_value()) {
2171 return std::nullopt;
2172 }
2173
2174 std::vector<T> sorted(ranges.value().begin(), ranges.value().end());
2175
2176 if(sorted.empty()) {
2177 return sorted;
2178 }
2179
2180 // sort by the min value
2181 std::sort(sorted.begin(), sorted.end(), [](T& a, T& b) { return a.min() < b.min(); });
2182
2183 // Single-pass merge: extend the last merged range or start a new one
2184 std::vector<T> merged;
2185 merged.reserve(sorted.size());
2186 merged.push_back(sorted[0]);
2187
2188 for(size_t i = 1; i < sorted.size(); ++i) {
2189 auto& back = merged.back();
2190 // they either overlap or are adjacent
2191 if(sorted[i].min() <= back.max() || sorted[i].min() == successor(back.max())) {
2192 back = T(back.min(), std::max(back.max(), sorted[i].max()));
2193 } else {
2194 merged.push_back(sorted[i]);
2195 }
2196 }
2197
2198 return merged;
2199}
2200
2201// Used to check that decoded IPAddressOrRange or ASIdOrRange entries were
2202// encoded in the (unique) canonical form RFC 3779 requires of issuers
2203template <typename T>
2204bool ranges_are_sorted_and_merged(const std::vector<T>& ranges) {
2205 for(size_t i = 1; i < ranges.size(); i++) {
2206 // Required sorted order without overlaps implies the previous maximum
2207 // is strictly below the next minimum
2208 if(!(ranges[i - 1].max() < ranges[i].min())) {
2209 return false;
2210 }
2211 // Contiguous entries were required to be combined by the issuer. The
2212 // increment cannot wrap since max() < min() <= the all-ones value.
2213 if(successor(ranges[i - 1].max()) == ranges[i].min()) {
2214 return false;
2215 }
2216 }
2217 return true;
2218}
2219
2220// If [min,max] covers exactly the address set of some prefix, return its length
2221template <IPAddressBlocks::Version V>
2222std::optional<size_t> range_prefix_length(const IPAddressBlocks::IPAddress<V>& min_addr,
2223 const IPAddressBlocks::IPAddress<V>& max_addr) {
2224 const auto min = min_addr.to_bytes();
2225 const auto max = max_addr.to_bytes();
2226
2227 size_t i = 0;
2228 while(i < min.size() && min[i] == max[i]) {
2229 i++;
2230 }
2231 if(i == min.size()) {
2232 // min == max is a single address, ie a full length prefix
2233 return 8 * min.size();
2234 }
2235
2236 // From the first differing bit on, min must be all zero bits and max all one bits
2237 const size_t common_bits = std::countl_zero(static_cast<uint8_t>(min[i] ^ max[i]));
2238 const uint8_t diff_mask = static_cast<uint8_t>(0xFF >> common_bits);
2239 if((min[i] & diff_mask) != 0 || (max[i] & diff_mask) != diff_mask) {
2240 return std::nullopt;
2241 }
2242 for(size_t j = i + 1; j < min.size(); j++) {
2243 if(min[j] != 0x00 || max[j] != 0xFF) {
2244 return std::nullopt;
2245 }
2246 }
2247 return 8 * i + common_bits;
2248}
2249
2250template <IPAddressBlocks::Version V>
2251bool range_is_expressible_as_prefix(const IPAddressBlocks::IPAddress<V>& min_addr,
2252 const IPAddressBlocks::IPAddress<V>& max_addr) {
2253 return range_prefix_length<V>(min_addr, max_addr).has_value();
2254}
2255
2256template <typename T>
2257bool validate_subject_in_issuer(std::span<const T> subject, std::span<const T> issuer) {
2258 // ensures that the subject ranges are enclosed by the issuer ranges
2259 // both vectors are already sorted, so we can do this in O(n+m)
2260
2261 // the issuer has 0 ranges to validate against, so this can only work if the subject also has none
2262 if(issuer.empty()) {
2263 return subject.empty();
2264 }
2265 for(auto subj = subject.begin(), issu = issuer.begin(); subj != subject.end();) {
2266 // the issuer range is smaller than the subject range, step to the next issuer range to check next round
2267 if(subj->min() > issu->max()) {
2268 issu++;
2269 // we have run out of issuer ranges, but still have subject ranges left to validate
2270 if(issu == issuer.end() && subj != subject.end()) {
2271 return false;
2272 }
2273 } else {
2274 // the subject is outside of the closest issuer range on the left (min) side
2275 if(subj->min() < issu->min()) {
2276 return false;
2277 }
2278 // the subject is outside of the closest issuer range on the right (max) side
2279 if(subj->max() > issu->max()) {
2280 return false;
2281 }
2282 // this range is contained within the issuer, advance to the next subject range
2283 subj++;
2284 }
2285 }
2286 return true;
2287}
2288
2289template <IPAddressBlocks::Version V>
2290void populate_validation_map(uint32_t afam,
2292 IPValidationMap<V>& map) {
2293 const std::optional<IPRangeVec<V>>& ranges = std::get<IPAddressBlocks::IPAddressChoice<V>>(choice).ranges();
2294 const bool has_value = ranges.has_value();
2295 const IPRangeVec<V>* value = has_value ? &ranges.value() : nullptr;
2296 map.emplace(afam, std::make_pair(has_value, std::move(value)));
2297}
2298
2299std::pair<IPValidationMap<IPv4>, IPValidationMap<IPv6>> create_validation_map(
2300 const std::vector<IPAddressBlocks::IPAddressFamily>& addr_blocks) {
2301 IPValidationMap<IPv4> v4_map;
2302 IPValidationMap<IPv6> v6_map;
2303
2304 for(const IPAddressBlocks::IPAddressFamily& block : addr_blocks) {
2305 uint32_t afam = block.afi();
2306 if(block.safi().has_value()) {
2307 afam = (afam << 8) | block.safi().value();
2308 }
2309
2310 const IPAddressBlocks::IPAddressFamily::AddrChoice& a_choice = block.addr_choice();
2311 if(std::holds_alternative<IPAddressBlocks::IPAddressChoice<IPv4>>(a_choice)) {
2312 populate_validation_map(afam, a_choice, v4_map);
2313 } else {
2314 populate_validation_map(afam, a_choice, v6_map);
2315 }
2316 }
2317
2318 return std::make_pair(v4_map, v6_map);
2319}
2320
2321} // namespace
2322
2323template <IPAddressBlocks::Version V>
2325 std::optional<std::span<const IPAddressBlocks::IPAddressOrRange<V>>> ranges) {
2326 // NOLINTNEXTLINE(*-prefer-member-initializer)
2327 m_ip_addr_ranges = sort_and_merge_ranges<IPAddressOrRange<V>>(ranges);
2328}
2329
2330template <IPAddressBlocks::Version V>
2332 if(m_ip_addr_ranges.has_value()) {
2333 into.start_sequence().encode_list(m_ip_addr_ranges.value()).end_cons();
2334 } else {
2335 into.encode_null();
2336 }
2337}
2338
2339template <IPAddressBlocks::Version V>
2341 const ASN1_Type next_tag = from.peek_next_object().type_tag();
2342
2343 if(next_tag == ASN1_Type::Null) {
2344 from.decode_null();
2345 m_ip_addr_ranges = std::nullopt;
2346 } else if(next_tag == ASN1_Type::Sequence) {
2347 std::vector<IPAddressOrRange<V>> ip_ranges;
2348 from.decode_list(ip_ranges);
2349
2350 /* RFC 3779 Section 2.2.3.6 -
2351 *
2352 * Any pair of IPAddressOrRange choices in an extension MUST NOT overlap
2353 * each other. Any contiguous address prefixes or ranges MUST be combined
2354 * into a single range or, whenever possible, a single prefix.
2355 */
2356 if(!ranges_are_sorted_and_merged(ip_ranges)) {
2357 throw Decoding_Error("IPAddressChoice entries must be sorted, non-overlapping and fully merged");
2358 }
2359 m_ip_addr_ranges = std::move(ip_ranges);
2360 } else {
2361 throw Decoding_Error(fmt("Unexpected type for IPAddressChoice {}", static_cast<uint32_t>(next_tag)));
2362 }
2363}
2364
2365template <IPAddressBlocks::Version V>
2367 // Compress IPAddressOrRange as much as possible
2368 // cf. https://www.rfc-editor.org/rfc/rfc3779.html#section-2.2.3.7 - https://www.rfc-editor.org/rfc/rfc3779.html#section-2.2.3.9
2369 //
2370 // If possible encode as a prefix x.x.x.x/x, else encode as a range of min-max.
2371 // Single addresses are encoded as is (technically a /32 or /128 prefix).
2372 //
2373 // A range can be encoded as a prefix if the lowest n bits of the min address are 0
2374 // and the highest n bits of the max address are 1, or in other words, contiguous sequences of 0s and 1s are omitted.
2375 // To make reconstruction possible, an 'unused' octet is included at the start, since in the case of e.g. /25 only
2376 // the highest bit of the last octet is actually meaningful.
2377 //
2378 // If encoding requires a range, the individual elements can still be compressed using the above method,
2379 // but the number of used bits varies between them.
2380
2381 const size_t version_octets = static_cast<size_t>(V);
2382
2383 std::array<uint8_t, version_octets> min = m_min.to_bytes();
2384 std::array<uint8_t, version_octets> max = m_max.to_bytes();
2385
2386 uint8_t zeros = 0;
2387 uint8_t ones = 0;
2388
2389 bool zeros_done = false;
2390 bool ones_done = false;
2391
2392 // count contiguous 0s/1s from the right of the min/max addresses
2393 for(size_t i = version_octets; i > 0; i--) {
2394 if(!zeros_done) {
2395 const uint8_t local_zeros = static_cast<uint8_t>(std::countr_zero(min[i - 1]));
2396 zeros += local_zeros;
2397 zeros_done = (local_zeros != 8);
2398 }
2399
2400 if(!ones_done) {
2401 const uint8_t local_ones = static_cast<uint8_t>(std::countr_one(max[i - 1]));
2402 ones += local_ones;
2403 ones_done = (local_ones != 8);
2404 }
2405
2406 if(zeros_done && ones_done) {
2407 break;
2408 }
2409 }
2410
2411 // the part we want to compress
2412 const uint8_t host = std::min(zeros, ones);
2413
2414 // these we can outright drop
2415 const uint8_t discarded_octets = host / 8;
2416 // in a partially used octet
2417 const uint8_t unused_bits = host % 8;
2418
2419 bool octets_match = true;
2420 bool used_bits_match = true;
2421
2422 // we have octets to check
2423 if(discarded_octets < version_octets) {
2424 // check all but the last octet
2425 for(size_t i = 0; i < static_cast<uint8_t>(version_octets - discarded_octets - 1); i++) {
2426 if(min[i] != max[i]) {
2427 octets_match = false;
2428 break;
2429 }
2430 }
2431 // check the last significant octet if we have matched so far
2432 if(octets_match) {
2433 const uint8_t shifted_min = (min[version_octets - 1 - discarded_octets] >> unused_bits);
2434 const uint8_t shifted_max = (max[version_octets - 1 - discarded_octets] >> unused_bits);
2435 used_bits_match = (shifted_min == shifted_max);
2436 }
2437 }
2438
2439 // both the full octets and the partially used one match
2440 if(octets_match && used_bits_match) {
2441 // at this point the range can be encoded as a prefix
2442 into.encode_bitstring(std::span{min}.first(version_octets - discarded_octets), unused_bits);
2443 } else {
2444 const uint8_t discarded_octets_min = zeros / 8;
2445 const uint8_t unused_bits_min = zeros % 8;
2446
2447 const uint8_t discarded_octets_max = ones / 8;
2448 const uint8_t unused_bits_max = ones % 8;
2449
2450 // compress the max address by setting unused bits to 0, for the min address these are already 0
2451 if(unused_bits_max != 0) {
2452 BOTAN_ASSERT_NOMSG(discarded_octets_max < version_octets);
2453 max[version_octets - 1 - discarded_octets_max] >>= unused_bits_max;
2454 max[version_octets - 1 - discarded_octets_max] <<= unused_bits_max;
2455 }
2456
2457 into.start_sequence()
2458 .encode_bitstring(std::span{min}.first(version_octets - discarded_octets_min), unused_bits_min)
2459 .encode_bitstring(std::span{max}.first(version_octets - discarded_octets_max), unused_bits_max)
2460 .end_cons();
2461 }
2462}
2463
2464template <IPAddressBlocks::Version V>
2466 const ASN1_Type next_tag = from.peek_next_object().type_tag();
2467
2468 // this can either be a prefix or a single address
2469 if(next_tag == ASN1_Type::BitString) {
2470 // construct a min and a max address from the prefix
2471
2472 ASN1_BitString prefix;
2473 from.decode_bitstring(prefix);
2474
2475 // min address gets filled with 0's
2476 m_min = decode_single_address(prefix, true);
2477 // max address with 1's
2478 m_max = decode_single_address(prefix, false);
2479 } else if(next_tag == ASN1_Type::Sequence) {
2480 // this is a range
2481
2482 ASN1_BitString addr_min;
2483 ASN1_BitString addr_max;
2484
2485 from.start_sequence().decode_bitstring(addr_min).decode_bitstring(addr_max).end_cons();
2486
2487 /* RFC 3779 Section 2.2.3.9 -
2488 *
2489 * The BIT STRING for the minimum address results from removing all the
2490 * least-significant zero-bits from the minimum address. The BIT STRING
2491 * for the maximum address results from removing all the least-significant
2492 * one-bits from the maximum address.
2493 *
2494 * So a canonically encoded minimum ends in a one bit (or is empty) and
2495 * a canonically encoded maximum ends in a zero bit (or is empty).
2496 * Section 2.2.3.9 also requires that a maximum "MUST contain at least
2497 * one bit whose value is 1", but verified erratum 2537 removes that
2498 * sentence as it contradicts the removal rule, so it is not checked.
2499 */
2500 if(!addr_min.bytes().empty() && ((addr_min.bytes().back() >> addr_min.unused_bits()) & 1) == 0) {
2501 throw Decoding_Error("IPAddressRange minimum must have trailing zero bits removed");
2502 }
2503 if(!addr_max.bytes().empty() && ((addr_max.bytes().back() >> addr_max.unused_bits()) & 1) == 1) {
2504 throw Decoding_Error("IPAddressRange maximum must have trailing one bits removed");
2505 }
2506
2507 m_min = decode_single_address(addr_min, true);
2508 m_max = decode_single_address(addr_max, false);
2509
2510 if(m_min > m_max) {
2511 throw Decoding_Error("IP address ranges must be sorted.");
2512 }
2513
2514 /* RFC 3779 Section 2.2.3.7 -
2515 *
2516 * This specification requires that any range of addresses that can be
2517 * encoded as a prefix MUST be encoded using an IPAddress element (a BIT
2518 * STRING), and any range that cannot be encoded as a prefix MUST be
2519 * encoded using an IPAddressRange
2520 */
2521 if(range_is_expressible_as_prefix<V>(m_min, m_max)) {
2522 throw Decoding_Error("IPAddressRange expressible as a prefix must be encoded as a prefix");
2523 }
2524 } else {
2525 throw Decoding_Error(fmt("Unexpected type for IPAddressOrRange {}", static_cast<uint32_t>(next_tag)));
2526 }
2527}
2528
2529template <IPAddressBlocks::Version V>
2530IPAddressBlocks::IPAddress<V> IPAddressBlocks::IPAddressOrRange<V>::decode_single_address(const ASN1_BitString& decoded,
2531 bool min) {
2532 const size_t version_octets = static_cast<size_t>(V);
2533
2534 // decode a single address according to https://datatracker.ietf.org/doc/html/rfc3779#section-2.1.1 and following
2535
2536 if(decoded.bytes().size() > version_octets) {
2537 throw Decoding_Error(fmt("IP address range entries must have a length between 0 and {} bytes.", version_octets));
2538 }
2539
2540 std::vector<uint8_t> address(decoded.bytes().begin(), decoded.bytes().end());
2541
2542 // ASN1_BitString guarantees the unused bits are zero (and absent if empty),
2543 // which is already correct for a min address; for a max address set them
2544 if(!min && decoded.unused_bits() > 0) {
2545 address.back() |= static_cast<uint8_t>((1 << decoded.unused_bits()) - 1);
2546 }
2547
2548 // pad to version length with 0's for min addresses, 255's (0xff) for max addresses
2549 address.resize(version_octets, min ? 0x00 : 0xFF);
2550
2551 return IPAddressBlocks::IPAddress<V>::from_bytes(address);
2552}
2553
2554template <IPAddressBlocks::Version V>
2555auto IPAddressBlocks::IPAddressOrRange<V>::as_subnet() const -> std::optional<Subnet> {
2556 if(auto prefix_len = range_prefix_length<V>(m_min, m_max)) {
2557 return Subnet(m_min, *prefix_len);
2558 }
2559 return std::nullopt;
2560}
2561
2562template <IPAddressBlocks::Version V>
2563IPAddressBlocks::IPAddress<V>::IPAddress(std::span<const uint8_t> v) : m_value(from_bytes(v).m_value) {}
2564
2565template <IPAddressBlocks::Version V>
2566IPAddressBlocks::IPAddress<V> IPAddressBlocks::IPAddress<V>::successor() const {
2567 return Cert_Extension::successor(*this);
2568}
2569
2570template <IPAddressBlocks::Version V>
2571IPAddressBlocks::IPAddress<V> IPAddressBlocks::IPAddress<V>::from_bytes(std::span<const uint8_t> v) {
2572 if(v.size() != Length) {
2573 throw Decoding_Error("number of bytes does not match IP version used");
2574 }
2575
2576 IPAddress<V> addr{};
2577 std::copy(v.begin(), v.end(), addr.m_value.begin());
2578 return addr;
2579}
2580
2582 const std::optional<X509_Certificate>& /* unused */,
2583 const std::vector<X509_Certificate>& cert_path,
2584 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2585 size_t pos) const {
2586 // maps in the form of (s)afi -> (needs_checking, ranges)
2587 auto [v4_needs_check, v6_needs_check] = create_validation_map(m_ip_addr_blocks);
2588
2589 if(pos == cert_path.size() - 1) {
2590 // checks if any range / family has 'inherit' as a value somewhere, not allowed for the root cert
2591 const auto validate_root_cert_ext = [&](const auto& map) {
2592 // check if any range has a value of 'false', indicating 'inherit'
2593 return std::any_of(map.begin(), map.end(), [&](const auto& it) {
2594 const auto& [_1, validation_info] = it;
2595 const auto& [needs_checking, _2] = validation_info;
2596 return !needs_checking;
2597 });
2598 };
2599 if(validate_root_cert_ext(v4_needs_check) || validate_root_cert_ext(v6_needs_check)) {
2600 cert_status.at(pos).insert(Certificate_Status_Code::IPADDR_BLOCKS_ERROR);
2601 }
2602 return;
2603 }
2604
2605 // traverse the chain until we find a cert with concrete values for the extension (so not 'inherit')
2606 for(auto cert_path_it = cert_path.begin() + pos + 1; cert_path_it != cert_path.end(); cert_path_it++) {
2607 const IPAddressBlocks* const parent_ip = cert_path_it->v3_extensions().get_extension_object_as<IPAddressBlocks>();
2608 // extension not present for parent
2609 if(parent_ip == nullptr) {
2610 cert_status.at(pos).insert(Certificate_Status_Code::IPADDR_BLOCKS_ERROR);
2611 return;
2612 }
2613 auto [issuer_v4, issuer_v6] = create_validation_map(parent_ip->addr_blocks());
2614
2615 const auto validate_against_issuer = [&](auto& subject_map, const auto& issuer_map) {
2616 for(auto map_it = subject_map.begin(); map_it != subject_map.end(); map_it++) {
2617 auto& [afam, validation_info] = *map_it;
2618
2619 // the issuer does not have this combination of afi/safi
2620 if(issuer_map.count(afam) == 0) {
2621 cert_status.at(pos).insert(Certificate_Status_Code::IPADDR_BLOCKS_ERROR);
2622 return false;
2623 }
2624
2625 auto& [needs_check, subject_value] = validation_info;
2626 const auto& [issuer_has_value, issuer_value] = issuer_map.at(afam);
2627 BOTAN_ASSERT_NOMSG(!needs_check || subject_value != nullptr);
2628 BOTAN_ASSERT_NOMSG(!issuer_has_value || issuer_value != nullptr);
2629
2630 // we still need to check this range and the issuer has an actual value for it (so not 'inherit')
2631 if(needs_check && issuer_has_value) {
2632 if(!validate_subject_in_issuer(std::span(*subject_value), std::span(*issuer_value))) {
2633 cert_status.at(pos).insert(Certificate_Status_Code::IPADDR_BLOCKS_ERROR);
2634 return false;
2635 }
2636 needs_check = false;
2637 }
2638 }
2639 return true;
2640 };
2641
2642 if(!validate_against_issuer(v4_needs_check, issuer_v4) || !validate_against_issuer(v6_needs_check, issuer_v6)) {
2643 return;
2644 }
2645
2646 const auto validate_no_checks_left = [&](const auto& map) {
2647 // check if all ranges have been checked, either by comparing their ranges if they have any,
2648 // or if they are inherit, their parent(s) will be validated later
2649 return std::all_of(map.begin(), map.end(), [&](const auto& it) {
2650 const auto& [_1, validation_info] = it;
2651 const auto& [needs_checking, _2] = validation_info;
2652 return !needs_checking;
2653 });
2654 };
2655
2656 if(validate_no_checks_left(v4_needs_check) && validate_no_checks_left(v6_needs_check)) {
2657 // we've validated what we need to and can stop traversing the cert chain
2658 return;
2659 }
2660 }
2661}
2662
2669
2670std::vector<uint8_t> ASBlocks::encode_inner() const {
2671 std::vector<uint8_t> output;
2672 DER_Encoder(output).encode(m_as_identifiers);
2673 return output;
2674}
2675
2676void ASBlocks::decode_inner(const std::vector<uint8_t>& in) {
2677 /* RFC 3779 Section 3.2.3.1 - ASIdentifiers ::= SEQUENCE { ... } */
2678 BER_Decoder(in, BER_Decoder::Limits::DER()).decode(m_as_identifiers).verify_end();
2679}
2680
2681ASBlocks::ASIdentifierChoice ASBlocks::add_new(const std::optional<ASIdentifierChoice>& old, asnum_t min, asnum_t max) {
2682 std::vector<ASIdOrRange> range;
2683 if(!old.has_value() || !old.value().ranges().has_value()) {
2684 range = {ASIdOrRange(min, max)};
2685 } else {
2686 range = old.value().ranges().value();
2687 range.push_back(ASIdOrRange(min, max));
2688 }
2689 return ASIdentifierChoice(range);
2690}
2691
2693 into.start_sequence();
2694
2695 if(!m_asnum.has_value() && !m_rdi.has_value()) {
2696 throw Encoding_Error("One of asnum, rdi must be present");
2697 }
2698
2699 if(m_asnum.has_value()) {
2700 into.start_explicit(0);
2701 into.encode(m_asnum.value());
2702 into.end_explicit();
2703 }
2704
2705 if(m_rdi.has_value()) {
2706 into.start_explicit(1);
2707 into.encode(m_rdi.value());
2708 into.end_explicit();
2709 }
2710
2711 into.end_cons();
2712}
2713
2715 const ASN1_Type next_tag = from.peek_next_object().type_tag();
2716 if(next_tag != ASN1_Type::Sequence) {
2717 throw Decoding_Error(fmt("Unexpected type for ASIdentifiers {}", static_cast<uint32_t>(next_tag)));
2718 }
2719
2720 BER_Decoder seq_dec = from.start_sequence();
2721
2722 const BER_Object elem_obj = seq_dec.get_next_object();
2723
2724 // asnum, potentially followed by an rdi
2725 if(elem_obj.is_a(0, ASN1_Class::ExplicitContextSpecific)) {
2726 BER_Decoder as_obj_ber = BER_Decoder(elem_obj, seq_dec.limits());
2728 as_obj_ber.decode(asnum).verify_end();
2729 m_asnum = asnum;
2730
2731 const BER_Object rdi_obj = seq_dec.get_next_object();
2733 BER_Decoder rdi_obj_ber = BER_Decoder(rdi_obj, seq_dec.limits());
2735 rdi_obj_ber.decode(rdi).verify_end();
2736 m_rdi = rdi;
2737 } else if(rdi_obj.type_tag() != ASN1_Type::NoObject) {
2738 throw Decoding_Error(
2739 fmt("Unexpected type for ASIdentifiers rdi: {}", static_cast<uint32_t>(rdi_obj.type_tag())));
2740 }
2741 } else if(elem_obj.is_a(1, ASN1_Class::ExplicitContextSpecific)) {
2742 // just an rdi
2743 BER_Decoder rdi_obj_ber = BER_Decoder(elem_obj, seq_dec.limits());
2745 rdi_obj_ber.decode(rdi).verify_end();
2746 m_rdi = rdi;
2747 const BER_Object end = seq_dec.get_next_object();
2748 if(end.type_tag() != ASN1_Type::NoObject) {
2749 throw Decoding_Error(
2750 fmt("Unexpected element with type {} in ASIdentifiers", static_cast<uint32_t>(end.type_tag())));
2751 }
2752 } else if(elem_obj.type_tag() == ASN1_Type::NoObject) {
2753 /* RFC 3779 Section 3.2.3.1 -
2754 * "The ASIdentifiers type is a SEQUENCE containing one or more forms of
2755 * autonomous system identifiers"
2756 */
2757 throw Decoding_Error("ASIdentifiers must contain an asnum or rdi element");
2758 } else {
2759 throw Decoding_Error(
2760 fmt("Unexpected element with type {} in ASIdentifiers", static_cast<uint32_t>(elem_obj.type_tag())));
2761 }
2762
2763 seq_dec.end_cons();
2764
2765 if(!m_asnum.has_value() && !m_rdi.has_value()) {
2766 throw Decoding_Error("Invalid encoding for ASIdentifiers");
2767 }
2768}
2769
2771 if(m_as_ranges.has_value()) {
2772 into.start_sequence().encode_list(m_as_ranges.value()).end_cons();
2773 } else {
2774 into.encode_null();
2775 }
2776}
2777
2778ASBlocks::ASIdentifierChoice::ASIdentifierChoice(const std::optional<std::vector<ASIdOrRange>>& ranges) {
2779 m_as_ranges = sort_and_merge_ranges<ASIdOrRange>(ranges);
2780}
2781
2783 const ASN1_Type next_tag = from.peek_next_object().type_tag();
2784
2785 if(next_tag == ASN1_Type::Null) {
2786 from.decode_null();
2787 m_as_ranges = std::nullopt;
2788 } else if(next_tag == ASN1_Type::Sequence) {
2789 std::vector<ASIdOrRange> as_ranges;
2790 from.decode_list(as_ranges);
2791
2792 /* RFC 3779 Section 3.2.3.4 -
2793 * "Any pair of items in the asIdsOrRanges SEQUENCE MUST NOT overlap.
2794 * Any contiguous series of AS identifiers MUST be combined into a
2795 * single range whenever possible. The AS identifiers in the
2796 * asIdsOrRanges element MUST be sorted by increasing numeric value."
2797 */
2798 if(!ranges_are_sorted_and_merged(as_ranges)) {
2799 throw Decoding_Error("ASIdentifierChoice entries must be sorted, non-overlapping and fully merged");
2800 }
2801 m_as_ranges = std::move(as_ranges);
2802 } else {
2803 throw Decoding_Error(fmt("Unexpected type for ASIdentifierChoice {}", static_cast<uint32_t>(next_tag)));
2804 }
2805}
2806
2808 if(m_min == m_max) {
2809 into.encode(static_cast<size_t>(m_min));
2810 } else {
2811 if(m_min >= m_max) {
2812 throw Encoding_Error("AS range numbers must be sorted");
2813 }
2814 into.start_sequence().encode(static_cast<size_t>(m_min)).encode(static_cast<size_t>(m_max)).end_cons();
2815 }
2816}
2817
2819 const ASN1_Type next_tag = from.peek_next_object().type_tag();
2820
2821 size_t min = 0;
2822 size_t max = 0;
2823
2824 if(next_tag == ASN1_Type::Integer) {
2825 from.decode(min);
2827 m_max = m_min;
2828 } else if(next_tag == ASN1_Type::Sequence) {
2832 if(m_min >= m_max) {
2833 throw Decoding_Error("ASIdOrRange has min greater than max");
2834 }
2835 } else {
2836 throw Decoding_Error(fmt("Unexpected type for ASIdOrRange {}", static_cast<uint32_t>(next_tag)));
2837 }
2838}
2839
2840void ASBlocks::validate(const X509_Certificate& /* unused */,
2841 const std::optional<X509_Certificate>& /* unused */,
2842 const std::vector<X509_Certificate>& cert_path,
2843 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2844 size_t pos) const {
2845 // the extension may not contain asnums or rdis, but one of them is always present
2846 const bool asnum_present = m_as_identifiers.asnum().has_value();
2847 const bool rdi_present = m_as_identifiers.rdi().has_value();
2848
2849 if(!asnum_present && !rdi_present) {
2850 // Invalid, should have been caught during decoding
2851 cert_status.at(pos).insert(Certificate_Status_Code::AS_BLOCKS_ERROR);
2852 return;
2853 }
2854
2855 bool asnum_needs_check = asnum_present ? m_as_identifiers.asnum().value().ranges().has_value() : false;
2856 bool rdi_needs_check = rdi_present ? m_as_identifiers.rdi().value().ranges().has_value() : false;
2857
2858 // we are at the (trusted) root cert, there is no parent to verify against
2859 if(pos == cert_path.size() - 1) {
2860 // asnum / rdi is present, but has 'inherit' value, but there is nothing to inherit from
2861 if((asnum_present && !asnum_needs_check) || (rdi_present && !rdi_needs_check)) {
2862 cert_status.at(pos).insert(Certificate_Status_Code::AS_BLOCKS_ERROR);
2863 }
2864 return;
2865 }
2866
2867 // traverse the chain until we find a cert with concrete values for the extension (so not 'inherit')
2868 for(auto it = cert_path.begin() + pos + 1; it != cert_path.end(); it++) {
2869 const ASBlocks* const parent_as = it->v3_extensions().get_extension_object_as<ASBlocks>();
2870 // no extension at all or no asnums or no rdis (if needed)
2871 if(parent_as == nullptr || (asnum_present && !parent_as->as_identifiers().asnum().has_value()) ||
2872 (rdi_present && !parent_as->as_identifiers().rdi().has_value())) {
2873 cert_status.at(pos).insert(Certificate_Status_Code::AS_BLOCKS_ERROR);
2874 return;
2875 }
2876 const auto as_identifiers = parent_as->as_identifiers();
2877
2878 // only something to validate if the subject does not have 'inherit' as a value
2879 if(asnum_needs_check && as_identifiers.asnum().value().ranges().has_value()) {
2880 const std::vector<ASBlocks::ASIdOrRange>& subject_asnums = m_as_identifiers.asnum()->ranges().value();
2881 const std::vector<ASBlocks::ASIdOrRange>& issuer_asnums = as_identifiers.asnum()->ranges().value();
2882
2883 if(!validate_subject_in_issuer<ASBlocks::ASIdOrRange>(subject_asnums, issuer_asnums)) {
2884 cert_status.at(pos).insert(Certificate_Status_Code::AS_BLOCKS_ERROR);
2885 return;
2886 }
2887 // successfully validated the asnums, but we may need to step further for rdis
2888 asnum_needs_check = false;
2889 }
2890
2891 if(rdi_needs_check && as_identifiers.rdi().value().ranges().has_value()) {
2892 const std::vector<ASBlocks::ASIdOrRange>& subject_rdis = m_as_identifiers.rdi()->ranges().value();
2893 const std::vector<ASBlocks::ASIdOrRange>& issuer_rdis = as_identifiers.rdi()->ranges().value();
2894
2895 if(!validate_subject_in_issuer<ASBlocks::ASIdOrRange>(subject_rdis, issuer_rdis)) {
2896 cert_status.at(pos).insert(Certificate_Status_Code::AS_BLOCKS_ERROR);
2897 return;
2898 }
2899 // successfully validated the rdis, but we may need to step further for asnums
2900 rdi_needs_check = false;
2901 }
2902
2903 if(!asnum_needs_check && !rdi_needs_check) {
2904 // we've validated what we need to and can stop traversing the cert chain
2905 return;
2906 }
2907 }
2908}
2909
2911 const std::optional<X509_Certificate>& /*issuer*/,
2912 const std::vector<X509_Certificate>& /*cert_path*/,
2913 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2914 size_t pos) const {
2915 /*
2916 * RFC 6960 is not particularly explicit about when id-pkix-ocsp-nocheck can
2917 * or cannot be included in a certificate, but reasonably we should require
2918 * that id-pkix-ocsp-nocheck is only included for certificates that are marked
2919 * as OCSP responders. This checks for compatible key usage and also the OCSP
2920 * signer extended key usage.
2921 */
2923 cert_status.at(pos).insert(Certificate_Status_Code::INVALID_OCSP_NOCHECK);
2924 }
2925}
2926
2927std::vector<uint8_t> OCSP_NoCheck::encode_inner() const {
2928 return {0x05, 0x00}; // NULL
2929}
2930
2931void OCSP_NoCheck::decode_inner(const std::vector<uint8_t>& buf) {
2932 /* RFC 6960 Section 4.2.2.2.1 - id-pkix-ocsp-nocheck (value SHALL be NULL) */
2933 BER_Decoder(buf, BER_Decoder::Limits::DER()).decode_null().verify_end();
2934}
2935
2936std::vector<uint8_t> NoRevocationAvailable::encode_inner() const {
2937 return {0x05, 0x00}; // NULL
2938}
2939
2940void NoRevocationAvailable::decode_inner(const std::vector<uint8_t>& buf) {
2941 // RFC 9608 Section 2, it's just a NULL
2942 BER_Decoder(buf, BER_Decoder::Limits::DER()).decode_null().verify_end();
2943}
2944
2946 const std::optional<X509_Certificate>& /*issuer*/,
2947 const std::vector<X509_Certificate>& /*cert_path*/,
2948 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2949 size_t pos) const {
2950 // RFC 9608 Section 2:
2951 // This extension MUST NOT be present in CA public key certificates.
2952 //
2953 // RFC 9608 Section 3:
2954 // Certificates that include the noRevAvail extension MUST NOT include
2955 // certificate extensions that point to CRL repositories or provide
2956 // locations of OCSP responders.
2957 //
2958 // Additionally (and unusually) the requirements of RFC 9608 Section 3
2959 // are not just on issuing parties but also on verifiers:
2960 //
2961 // If any of the above are violated in a certificate, then the relying
2962 // party MUST consider the certificate invalid.
2963
2964 const Extensions& exts = subject.v3_extensions();
2965
2966 if(const auto* bc = exts.get_extension_object_as<Basic_Constraints>(); bc != nullptr && bc->is_ca()) {
2967 // RFC 9608 Section 3:
2968 // The certificate MUST NOT also include the basic constraints
2969 // certificate extension with the cA BOOLEAN set to TRUE
2970 cert_status.at(pos).insert(Certificate_Status_Code::NO_REV_AVAIL_INVALID_USE);
2971 }
2972
2973 // RFC 9608 Section 3:
2974 // The certificate MUST NOT also include the CRL Distribution Points
2975 // certificate extension
2977 cert_status.at(pos).insert(Certificate_Status_Code::NO_REV_AVAIL_INVALID_USE);
2978 }
2979
2980 // RFC 9608 Section 3:
2981 // The certificate MUST NOT also include the Freshest CRL certificate
2982 // extension
2983 if(exts.extension_set(OID({2, 5, 29, 46}))) {
2984 cert_status.at(pos).insert(Certificate_Status_Code::NO_REV_AVAIL_INVALID_USE);
2985 }
2986
2987 // RFC 9608 Section 3:
2988 // The Authority Information Access certificate extension, if
2989 // present, MUST NOT include an id-ad-ocsp accessMethod
2990 //
2991 // Walk the raw AccessDescription list rather than the URI-only typed
2992 // accessor so a non-URI OCSP accessLocation also triggers the rejection.
2993 if(const auto* aia = exts.get_extension_object_as<Authority_Information_Access>(); aia != nullptr) {
2994 const OID id_ad_ocsp = OID::from_string("PKIX.OCSP");
2995 const bool has_ocsp = !aia->ocsp_responder_uris().empty() ||
2996 std::ranges::any_of(aia->access_descriptions(),
2997 [&](const auto& ad) { return ad.access_method() == id_ad_ocsp; });
2998 if(has_ocsp) {
2999 cert_status.at(pos).insert(Certificate_Status_Code::NO_REV_AVAIL_INVALID_USE);
3000 }
3001 }
3002}
3003
3004std::vector<uint8_t> Unknown_Extension::encode_inner() const {
3005 return m_bytes;
3006}
3007
3008void Unknown_Extension::decode_inner(const std::vector<uint8_t>& bytes) {
3009 // Just treat as an opaque blob at this level
3010 m_bytes = bytes;
3011}
3012
3013} // namespace Cert_Extension
3014
3015} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:136
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:49
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
size_t unused_bits() const
Definition asn1_obj.h:211
std::span< const uint8_t > bytes() const
Definition asn1_obj.h:206
const std::string & value() const
Definition asn1_obj.h:590
ASN1_Type tagging() const
Definition asn1_obj.h:585
const std::set< X509_DN > & directory_names() const
Return the set of directory names included in this alternative name.
Definition pkix_types.h:441
static Limits DER()
Definition ber_dec.h:44
const BER_Object & peek_next_object()
Definition ber_dec.cpp:510
BER_Object get_next_object()
Definition ber_dec.cpp:521
BER_Decoder & decode_bitstring(ASN1_BitString &out, ASN1_Type type_tag=ASN1_Type::BitString, ASN1_Class class_tag=ASN1_Class::Universal)
Definition ber_dec.cpp:1047
BER_Decoder & decode(bool &out)
Definition ber_dec.h:361
bool more_items() const
Definition ber_dec.cpp:461
Limits limits() const
Definition ber_dec.h:201
BER_Decoder & verify_end()
Definition ber_dec.cpp:471
BER_Decoder & end_cons()
Definition ber_dec.cpp:635
BER_Decoder start_sequence()
Definition ber_dec.h:279
BER_Decoder start_context_specific(uint32_t tag)
Definition ber_dec.h:294
BER_Decoder & decode_optional(T &out, ASN1_Type type_tag, ASN1_Class class_tag, const T &default_value=T())
Definition ber_dec.h:550
BER_Decoder & decode_null()
Definition ber_dec.cpp:688
BER_Decoder & decode_implicit(BER_Object obj, T &out, ASN1_Type real_type, ASN1_Class real_class)
Definition ber_dec.h:637
BER_Decoder & decode_optional_field(uint32_t tag_no, ASN1_Class class_tag, F &&fn)
Definition ber_dec.h:623
BER_Decoder & decode_list(std::vector< T > &vec, ASN1_Type type_tag=ASN1_Type::Sequence, ASN1_Class class_tag=ASN1_Class::Universal)
Definition ber_dec.h:895
bool is_a(ASN1_Type type_tag, ASN1_Class class_tag) const
Definition asn1_obj.cpp:97
ASN1_Type type_tag() const
Definition asn1_obj.h:277
ASN1_Class get_class() const
Definition asn1_obj.h:292
int signum() const
Definition bigint.h:493
size_t bits() const
Definition bigint.cpp:308
uint8_t byte_at(size_t n) const
Definition bigint.cpp:119
static BigInt from_u64(uint64_t n)
Definition bigint.cpp:31
bool is_negative() const
Definition bigint.h:623
void encode_into(DER_Encoder &to) const override
void decode_from(BER_Decoder &from) override
void encode_into(DER_Encoder &to) const override
void decode_from(BER_Decoder &from) override
const std::optional< std::vector< ASIdOrRange > > & ranges() const
Definition x509_ext.h:1361
const std::optional< ASIdentifierChoice > & asnum() const
Definition x509_ext.h:1380
const std::optional< ASIdentifierChoice > & rdi() const
Definition x509_ext.h:1382
void encode_into(DER_Encoder &to) const override
void decode_from(BER_Decoder &from) override
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 override
const ASIdentifiers & as_identifiers() const
Definition x509_ext.h:1442
std::vector< std::string > ca_issuers() const
const std::vector< AccessDescription > & access_descriptions() const
Definition x509_ext.h:471
std::unique_ptr< Certificate_Extension > copy() const override
std::vector< std::string > ocsp_responders() const
Definition x509_ext.cpp:999
BOTAN_FUTURE_EXPLICIT Basic_Constraints(bool is_ca=false, size_t path_length_constraint=0)
Definition x509_ext.cpp:436
std::optional< size_t > path_length_constraint() const
Definition x509_ext.h:60
const std::optional< AlternativeName > & crl_issuer() const
Definition x509_ext.h:636
std::vector< std::string > crl_distribution_urls() const
const BigInt & crl_number() const
std::unique_ptr< Certificate_Extension > copy() const override
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 override
Definition x509_ext.cpp:926
void decode_from(BER_Decoder &from) override
void encode_into(DER_Encoder &to) const override
const std::optional< AlternativeName > & full_name() const
Definition x509_ext.h:592
void encode_into(DER_Encoder &to) const override
void encode_into(DER_Encoder &to) const override
std::variant< IPAddressChoice< Version::IPv4 >, IPAddressChoice< Version::IPv6 > > AddrChoice
Definition x509_ext.h:1178
void encode_into(DER_Encoder &to) const override
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 override
const std::vector< IPAddressFamily > & addr_blocks() const
Definition x509_ext.h:1286
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 override
Definition x509_ext.cpp:818
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 override
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 override
static Entry from_service_provider_code(std::string_view spc)
static Entry from_telephone_number(const Botan::TelephoneNumber &tn)
const std::string & service_provider_code() const
void decode_from(BER_Decoder &from) override
const std::string & telephone_number() const
std::vector< TelephoneNumberRangeData > RangeContainer
Definition x509_ext.h:889
static Entry from_telephone_number_range(const Botan::TelephoneNumberRange &range)
void encode_into(DER_Encoder &to) const override
const Botan::TelephoneNumber & number() const
const RangeContainer & telephone_number_range() const
const Botan::TelephoneNumberRange & range() const
static TNAuthList from_der(std::span< const uint8_t > der)
bool encompasses(const TNAuthList &delegate) const
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 override
const std::vector< Entry > & entries() const
Definition x509_ext.h:977
virtual bool should_encode() const
Definition pkix_types.h:861
virtual 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:171
virtual std::vector< uint8_t > encode_inner() const =0
DER_Encoder & add_object(ASN1_Type type_tag, ASN1_Class class_tag, const uint8_t rep[], size_t length)
Definition der_enc.cpp:285
DER_Encoder & end_explicit()
Definition der_enc.cpp:230
DER_Encoder & encode_optional(const T &value, const T &default_value)
Definition der_enc.h:301
DER_Encoder & encode_list(const std::vector< T > &values)
Definition der_enc.h:327
DER_Encoder & start_explicit(uint16_t type_tag)
Definition der_enc.cpp:223
DER_Encoder & start_explicit_context_specific(uint32_t tag)
Definition der_enc.h:122
DER_Encoder & start_sequence()
Definition der_enc.h:86
DER_Encoder & encode_null()
Definition der_enc.cpp:306
DER_Encoder & end_cons()
Definition der_enc.cpp:208
DER_Encoder & encode_bitstring(std::span< const uint8_t > bits, size_t unused_bits=0, ASN1_Type type_tag=ASN1_Type::BitString, ASN1_Class class_tag=ASN1_Class::Universal)
Definition der_enc.cpp:411
DER_Encoder & encode(bool b)
Definition der_enc.cpp:313
const Certificate_Extension * get_extension_object(const OID &oid) const
Definition x509_ext.cpp:246
std::map< OID, std::pair< std::vector< uint8_t >, bool > > extensions_raw() const
Definition x509_ext.cpp:281
std::vector< OID > critical_extensions() const
Definition x509_ext.cpp:118
std::unique_ptr< Certificate_Extension > get(const OID &oid) const
Definition x509_ext.cpp:255
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
void decode_from(BER_Decoder &from) override
Definition x509_ext.cpp:312
bool remove(const OID &oid)
Definition x509_ext.cpp:205
std::vector< uint8_t > get_extension_bits(const OID &oid) const
Definition x509_ext.cpp:237
bool critical_extension_set(const OID &oid) const
Definition x509_ext.cpp:229
const T * get_extension_object_as(const OID &oid=T::static_oid()) const
Definition pkix_types.h:882
std::vector< std::pair< std::unique_ptr< Certificate_Extension >, bool > > extensions() const
Definition x509_ext.cpp:262
void encode_into(DER_Encoder &to) const override
Definition x509_ext.cpp:292
void replace(std::unique_ptr< Certificate_Extension > extn, bool critical=false)
Definition x509_ext.cpp:215
bool add_new(std::unique_ptr< Certificate_Extension > extn, bool critical=false)
Definition x509_ext.cpp:193
bool extension_set(const OID &oid) const
Definition x509_ext.cpp:225
void add(std::unique_ptr< Certificate_Extension > extn, bool critical=false)
Definition x509_ext.cpp:180
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:311
static OID from_string(std::string_view str)
Definition asn1_oid.cpp:80
virtual std::vector< uint8_t > public_key_bits() const =0
static std::optional< TelephoneNumberRange > from(const TelephoneNumber &start, uint64_t count)
const TelephoneNumber & start() const
std::optional< uint64_t > numeric_value() const
static std::optional< TelephoneNumber > from_string(std::string_view tn)
const std::string & to_string() const
static std::optional< URI > from_string(std::string_view raw)
Definition uri.cpp:163
bool is_CA_cert() const
Definition x509cert.cpp:481
bool is_critical(std::string_view ex_name) const
Definition x509cert.cpp:611
const Extensions & v3_extensions() const
Definition x509cert.cpp:517
bool allowed_usage(Key_Constraints usage) const
Definition x509cert.cpp:526
const char * name
Definition ffi_tls.h:59
std::string to_string(const BER_Object &obj)
Definition asn1_obj.cpp:224
constexpr uint8_t get_byte(T input)
Definition loadstor.h:79
ASN1_Class
Definition asn1_obj.h:32
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
ASN1_Type
Definition asn1_obj.h:47
bool operator<(const OID &a, const OID &b)
Definition asn1_oid.cpp:175
constexpr RT checked_cast_to(AT i)
Definition int_utils.h:104
std::optional< uint32_t > is_sub_element_of(const OID &oid, std::initializer_list< uint32_t > prefix)
Definition x509_utils.h:22
void append(std::vector< T, Alloc > &out, std::type_identity_t< std::span< const T > > in)
Extension_Context
Definition pkix_types.h:795
std::string to_string(ErrorType type)
Convert an ErrorType to string.
Definition exceptn.cpp:13