370bool Subject_Alternative_Name::is_appropriate_context(
Extension_Context context)
const {
374bool Issuer_Alternative_Name::is_appropriate_context(
Extension_Context context)
const {
378bool Extended_Key_Usage::is_appropriate_context(
Extension_Context context)
const {
386bool Certificate_Policies::is_appropriate_context(
Extension_Context context)
const {
390bool Authority_Information_Access::is_appropriate_context(
Extension_Context context)
const {
404bool CRL_Distribution_Points::is_appropriate_context(
Extension_Context context)
const {
408bool CRL_Issuing_Distribution_Point::is_appropriate_context(
Extension_Context context)
const {
416bool NoRevocationAvailable::is_appropriate_context(
Extension_Context context)
const {
441 if(!m_is_ca && m_path_length_constraint.has_value()) {
443 throw Invalid_Argument(
444 "Basic_Constraints nonsensical to set a path length constraint for a non-CA basicConstraints");
453 return m_path_length_constraint.value_or(NO_CERT_PATH_LIMIT);
455 throw Invalid_State(
"Basic_Constraints::get_path_limit: Not a CA");
463 std::vector<uint8_t> output;
477void Basic_Constraints::decode_inner(
const std::vector<uint8_t>& in) {
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");
504 if(m_constraints.empty()) {
505 throw Encoding_Error(
"Cannot encode empty PKIX key constraints");
508 std::vector<uint8_t> der;
509 DER_Encoder(der).encode_named_bitstring(m_constraints.value(), 16);
516void Key_Usage::decode_inner(
const std::vector<uint8_t>& in) {
527 throw Decoding_Error(
"KeyUsage extension must have at least one bit set");
530 m_constraints = Key_Constraints(
static_cast<uint32_t
>(usage));
537 std::vector<uint8_t> output;
545void Subject_Key_ID::decode_inner(
const std::vector<uint8_t>& in) {
549 if(m_key_id.empty()) {
550 throw Decoding_Error(
"SubjectKeyIdentifier must not be empty");
552 if(m_key_id.size() > MaximumKeyIdentifierLength) {
553 throw Decoding_Error(
554 fmt(
"SubjectKeyIdentifier length {} exceeds limit of {} bytes", m_key_id.size(), MaximumKeyIdentifierLength));
570 m_key_id.resize(hash->output_length());
573 hash->final(m_key_id.data());
582 m_key_id.resize(hash->output_length());
584 hash->update(pub_key);
585 hash->final(m_key_id.data());
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);
598 std::vector<uint8_t> output;
600 der.start_sequence();
601 if(!m_key_id.empty()) {
604 if(m_authority_cert.has_value()) {
605 emit_general_names_implicit(der, m_authority_cert->issuer, 1);
615void Authority_Key_ID::decode_inner(
const std::vector<uint8_t>& in) {
625 BER_Decoder seq = ber.start_sequence();
628 m_authority_cert.reset();
630 bool key_id_present =
false;
631 std::optional<AlternativeName> authority_cert_issuer;
632 std::optional<X509_Serial_Number> authority_cert_serial;
634 seq.decode_optional_field(0,
636 [&](BER_Decoder& d) {
638 key_id_present =
true;
640 .decode_optional_field(1,
642 [&](BER_Decoder& d) {
643 AlternativeName names;
644 d.decode_implicit(names,
649 authority_cert_issuer = std::move(names);
652 X509_Serial_Number serial;
655 authority_cert_serial = std::move(serial);
662 if(m_key_id.empty()) {
663 throw Decoding_Error(
"AuthorityKeyIdentifier keyIdentifier must not be empty");
665 if(m_key_id.size() > MaximumKeyIdentifierLength) {
666 throw Decoding_Error(
fmt(
"AuthorityKeyIdentifier keyIdentifier length {} exceeds limit of {} bytes",
668 MaximumKeyIdentifierLength));
673 if(authority_cert_issuer.has_value() && authority_cert_issuer->is_empty()) {
674 throw Decoding_Error(
"AuthorityKeyIdentifier authorityCertIssuer must contain at least one GeneralName");
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");
688 if(authority_cert_issuer.has_value()) {
698 std::vector<uint8_t> output;
699 DER_Encoder(output).encode(m_alt_name);
707 std::vector<uint8_t> output;
708 DER_Encoder(output).encode(m_alt_name);
715void Subject_Alternative_Name::decode_inner(
const std::vector<uint8_t>& in) {
719 if(!m_alt_name.has_items()) {
720 throw Decoding_Error(
"SubjectAlternativeName extension must contain at least one GeneralName");
727void Issuer_Alternative_Name::decode_inner(
const std::vector<uint8_t>& in) {
731 if(!m_alt_name.has_items()) {
732 throw Decoding_Error(
"IssuerAlternativeName extension must contain at least one GeneralName");
740 std::vector<uint8_t> output;
741 DER_Encoder(output).start_sequence().encode_list(m_oids).end_cons();
748void Extended_Key_Usage::decode_inner(
const std::vector<uint8_t>& in) {
752 throw Decoding_Error(
"ExtendedKeyUsage extension must contain at least one KeyPurposeId");
760 const auto& permitted = m_name_constraints.permitted();
761 const auto& excluded = m_name_constraints.excluded();
763 if(permitted.empty() && excluded.empty()) {
764 throw Encoding_Error(
"Refusing to encode empty NameConstraints");
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();
773 if(!excluded.empty()) {
774 der.start_explicit_context_specific(1).encode_list(excluded).end_cons();
783void Name_Constraints::decode_inner(
const std::vector<uint8_t>& in) {
792 BER_Decoder inner = ber.start_sequence();
794 std::vector<GeneralSubtree> permitted;
796 if(permitted.empty()) {
797 throw Decoding_Error(
"Empty NameConstraint permitted list");
801 std::vector<GeneralSubtree> excluded;
803 if(excluded.empty()) {
804 throw Decoding_Error(
"Empty NameConstraint excluded list");
811 if(permitted.empty() && excluded.empty()) {
812 throw Decoding_Error(
"Empty NameConstraint extension");
815 m_name_constraints = NameConstraints(std::move(permitted), std::move(excluded));
819 const std::optional<X509_Certificate>& ,
820 const std::vector<X509_Certificate>& cert_path,
821 std::vector<std::set<Certificate_Status_Code>>& cert_status,
823 if(!m_name_constraints.permitted().empty() || !m_name_constraints.excluded().empty()) {
828 const bool issuer_name_constraint_critical = subject.
is_critical(
"X509v3.NameConstraints");
831 for(
size_t j = 0; j < pos; ++j) {
832 const auto& cert = cert_path.at(j);
837 if(j > 0 && cert.issuer_dn() == cert.subject_dn()) {
841 if(!m_name_constraints.is_permitted(cert, issuer_name_constraint_critical)) {
846 if(m_name_constraints.is_excluded(cert, issuer_name_constraint_critical)) {
859class Policy_Information final :
public ASN1_Object {
861 Policy_Information() =
default;
863 explicit Policy_Information(
const OID& oid) : m_oid(oid) {}
865 const OID& oid()
const {
return m_oid; }
867 void encode_into(DER_Encoder& codec)
const override { codec.start_sequence().encode(m_oid).end_cons(); }
869 void decode_from(BER_Decoder& codec)
override {
870 codec.start_sequence().decode(m_oid).discard_remaining().end_cons();
877bool policy_oids_have_duplicate(
const std::vector<OID>& oids) {
879 for(
const auto& oid : oids) {
880 if(!seen.insert(oid).second) {
890 m_oids(oids), m_has_duplicate(policy_oids_have_duplicate(m_oids)) {}
896 std::vector<Policy_Information> policies;
898 policies.reserve(m_oids.size());
899 for(
const auto& oid : m_oids) {
900 policies.push_back(Policy_Information(oid));
903 std::vector<uint8_t> output;
911void Certificate_Policies::decode_inner(
const std::vector<uint8_t>& in) {
913 std::vector<Policy_Information> policies;
916 if(policies.empty()) {
917 throw Decoding_Error(
"CertificatePolicies extension must contain at least one PolicyInformation");
920 for(
const auto& policy : policies) {
921 m_oids.push_back(policy.oid());
923 m_has_duplicate = policy_oids_have_duplicate(m_oids);
927 const std::optional<X509_Certificate>& ,
928 const std::vector<X509_Certificate>& ,
929 std::vector<std::set<Certificate_Status_Code>>& cert_status,
931 if(m_has_duplicate) {
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) {
943 out.push_back(std::move(*parsed));
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());
957 const auto append = [&](
const OID& method,
const std::vector<URI>& uris) {
958 for(
const auto& uri : uris) {
960 out.emplace_back(method,
963 std::vector<uint8_t>(value.value().begin(), value.value().end()));
976 m_ca_issuers(parse_aia_uris(
ca_issuers,
"AuthorityInformationAccess CA issuers")) {
978 if(auto parsed = URI::from_string(ocsp)) {
979 m_ocsp_responders.push_back(std::move(*parsed));
981 throw Invalid_Argument(
"Invalid URI in AuthorityInformationAccess OCSP responder");
984 m_access_descriptions = uri_access_descriptions(m_ocsp_responders, m_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)) {}
997 m_access_descriptions(uri_access_descriptions(m_ocsp_responders, m_ca_issuers)) {}
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());
1009 return std::make_unique<Authority_Information_Access>(*
this);
1014void validate_general_name_encoding(
ASN1_Type tag,
ASN1_Class cls, std::span<const uint8_t> value) {
1016 std::vector<uint8_t> wrapped_name;
1023 throw Decoding_Error(
"GeneralName IA5String value must not be empty");
1027 throw Decoding_Error(
"GeneralName directoryName must not be empty");
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");
1050 std::vector<URI>& ocsp_responders,
1051 std::vector<URI>& ca_issuers) {
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) {
1057 ocsp_responders.push_back(std::move(*uri));
1059 throw Invalid_Argument(
"Invalid URI in AuthorityInformationAccess OCSP responder");
1061 }
else if(ad.access_method() == oid_ca_issuers) {
1063 ca_issuers.push_back(std::move(*uri));
1065 throw Invalid_Argument(
"Invalid URI in AuthorityInformationAccess CA issuers");
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);
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));
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());
1098 return std::string(m_location_value.begin(), m_location_value.end());
1100 return std::nullopt;
1104 std::vector<uint8_t> output;
1107 der.start_sequence();
1109 for(
const auto& ad : m_access_descriptions) {
1111 validate_general_name_encoding(ad.location_tag(), ad.location_class(), ad.location_value());
1113 throw Encoding_Error(
"AccessDescription accessLocation is not a valid GeneralName");
1115 der.start_sequence()
1116 .encode(ad.access_method())
1117 .add_object(ad.location_tag(), ad.location_class(), ad.location_value())
1125void Authority_Information_Access::decode_inner(
const std::vector<uint8_t>& in) {
1135 BER_Decoder ber = outer.start_sequence();
1138 const OID ca_issuer =
OID::from_string(
"PKIX.CertificateAuthorityIssuers");
1140 m_access_descriptions.clear();
1141 m_ocsp_responders.clear();
1142 m_ca_issuers.clear();
1144 while(ber.more_items()) {
1147 BER_Decoder info = ber.start_sequence();
1150 const BER_Object
name = info.get_next_object();
1157 if(!
name.is_set()) {
1158 throw Decoding_Error(
"AuthorityInformationAccess AccessDescription missing accessLocation");
1160 validate_general_name_encoding(
name.type_tag(),
name.get_class(),
name.data());
1163 m_access_descriptions.emplace_back(
1164 oid,
name.type_tag(),
name.get_class(), std::vector<uint8_t>(
name.data().begin(),
name.data().end()));
1169 m_ocsp_responders.push_back(std::move(*parsed));
1171 throw Decoding_Error(
"Invalid URI in AuthorityInformationAccess OCSP responder");
1173 }
else if(oid == ca_issuer) {
1175 m_ca_issuers.push_back(std::move(*parsed));
1177 throw Decoding_Error(
"Invalid URI in AuthorityInformationAccess CA issuers");
1186 if(m_access_descriptions.empty()) {
1187 throw Decoding_Error(
"AuthorityInformationAccess extension must contain at least one AccessDescription");
1192 BOTAN_ARG_CHECK(m_crl_number.signum() >= 0,
"CRL number cannot be negative");
1198 return m_crl_number;
1207 return m_crl_number.to_u32bit();
1214 return std::make_unique<CRL_Number>(*
this);
1221 std::vector<uint8_t> output;
1229void CRL_Number::decode_inner(
const std::vector<uint8_t>& in) {
1232 if(m_crl_number.
signum() < 0) {
1242 std::vector<uint8_t> output;
1250void CRL_ReasonCode::decode_inner(
const std::vector<uint8_t>& in) {
1267 size_t reason_code = 0;
1272 if(reason_code == 7 || reason_code > 10) {
1273 throw Decoding_Error(
fmt(
"CRLReason has unknown enumeration value {}", reason_code));
1276 m_reason =
static_cast<CRL_Code>(reason_code);
1281constexpr size_t ReasonFlagsNamedBitWidth = 9;
1283void emit_reason_flags_implicit(DER_Encoder& der, uint32_t tag, ReasonFlags reasons) {
1287ReasonFlags decode_reason_flags_implicit(BER_Decoder& decoder, uint32_t tag) {
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();
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()) {
1324 return *m_dp_name->full_name();
1328 m_distribution_points(points),
1329 m_crl_distribution_urls(crl_distribution_point_uris_from_distribution_points(m_distribution_points)) {}
1333 return *m_dp_name->full_name();
1337 if(!m_full_name.has_value()) {
1338 throw Encoding_Error(
"DistributionPointName has no fullName to encode");
1343 emit_general_names_implicit(der, *m_full_name, 0);
1357 throw Decoding_Error(
"DistributionPointName fullName must contain at least one GeneralName");
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");
1364 throw Decoding_Error(
"nameRelativeToCrlIssuer not supported in DistributionPointName");
1366 throw Decoding_Error(
"DistributionPointName CHOICE is neither fullName nor nameRelativeToCRLIssuer");
1371 std::vector<uint8_t> output;
1376void CRL_Distribution_Points::decode_inner(
const std::vector<uint8_t>& buf) {
1384 if(m_distribution_points.empty()) {
1385 throw Decoding_Error(
"CRLDistributionPoints extension must contain at least one DistributionPoint");
1388 m_crl_distribution_urls = crl_distribution_point_uris_from_distribution_points(m_distribution_points);
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());
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");
1414 if(has_crl_issuer && !crl_issuer_is_well_formed(*m_crl_issuer)) {
1417 throw Encoding_Error(
"cRLIssuer must contain exactly one non-empty directoryName GeneralName");
1428 emit_reason_flags_implicit(der, 1, *m_reasons);
1431 if(has_crl_issuer) {
1432 emit_general_names_implicit(der, *m_crl_issuer, 2);
1449 m_crl_issuer.reset();
1459 m_dp_name = std::move(
name);
1461 .decode_optional_field(
1476 if(m_crl_issuer.has_value() && m_crl_issuer->is_empty()) {
1477 throw Decoding_Error(
"cRLIssuer GeneralNames must contain at least one GeneralName");
1480 if(m_crl_issuer.has_value() && !crl_issuer_is_well_formed(*m_crl_issuer)) {
1483 throw Decoding_Error(
"cRLIssuer must contain exactly one non-empty directoryName GeneralName");
1486 if(!m_dp_name.has_value() && !m_crl_issuer.has_value()) {
1487 throw Decoding_Error(
"DistributionPoint must contain either distributionPoint or cRLIssuer");
1500 throw Encoding_Error(
"Refusing to encode empty IssuingDistributionPoint");
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);
1508 "At most one of onlyContainsUserCerts, onlyContainsCACerts, onlyContainsAttributeCerts may be TRUE");
1511 const auto emit_optional_boolean_implicit = [](
DER_Encoder& der, uint32_t tag,
bool value) {
1515 const uint8_t val = 0xFF;
1520 std::vector<uint8_t> output;
1521 DER_Encoder der(output);
1524 if(m_dp_name.has_value()) {
1528 emit_optional_boolean_implicit(der, 1, m_only_contains_user_certs);
1529 emit_optional_boolean_implicit(der, 2, m_only_contains_ca_certs);
1531 if(m_only_some_reasons) {
1532 emit_reason_flags_implicit(der, 3, *m_only_some_reasons);
1535 emit_optional_boolean_implicit(der, 4, m_indirect_crl);
1536 emit_optional_boolean_implicit(der, 5, m_only_contains_attribute_certs);
1542void CRL_Issuing_Distribution_Point::decode_inner(
const std::vector<uint8_t>& buf) {
1555 BER_Decoder seq = outer.start_sequence();
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;
1564 auto decode_implicit_bool = [&](BER_Decoder& dec, uint32_t tag) ->
bool {
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);
1580 .decode_optional_field(1,
1582 [&](BER_Decoder& d) { m_only_contains_user_certs = decode_implicit_bool(d, 1); })
1583 .decode_optional_field(
1585 .decode_optional_field(3,
1587 [&](BER_Decoder& d) { m_only_some_reasons = decode_reason_flags_implicit(d, 3); })
1588 .decode_optional_field(
1591 m_only_contains_attribute_certs = decode_implicit_bool(d, 5);
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");
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);
1611 throw Decoding_Error(
1612 "IssuingDistributionPoint sets more than one of onlyContainsUserCerts/CACerts/AttributeCerts");
1618 throw Invalid_Argument(
"TNAuthList service provider code cannot be empty");
1629 if(
range.count() < 2) {
1630 throw Invalid_Argument(
"TNAuthList range must contain at least two numbers");
1633 entry.set_range(
range);
1664 throw Invalid_State(
"TNAuthList::Entry has an invalid type");
1668 const auto decode_ia5_string = [](
BER_Decoder& from, std::string_view what) {
1684 const uint32_t type_tag =
static_cast<uint32_t
>(obj.
type_tag());
1689 m_data = decode_ia5_string(inner,
"ServiceProviderCode");
1694 if(!start.has_value()) {
1699 range.decode(count);
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);
1708 if(count_value < 2) {
1713 if(!tn_range.has_value()) {
1718 while(
range.more_items()) {
1719 range.get_next_object();
1723 set_range(std::move(*tn_range));
1727 if(!tn.has_value()) {
1730 m_data = std::move(*tn);
1739 if(m_tn_entries.empty()) {
1740 throw Invalid_Argument(
"TNAuthList requires at least one entry");
1746 list.decode_inner(std::vector<uint8_t>(der.begin(), der.end()));
1751 std::vector<uint8_t> output;
1756void TNAuthList::decode_inner(
const std::vector<uint8_t>& in) {
1758 m_tn_entries.clear();
1760 if(m_tn_entries.empty()) {
1767 return std::get<std::string>(m_data);
1772 return std::get<Botan::TelephoneNumberRange>(m_data);
1777 return std::get<Botan::TelephoneNumber>(m_data);
1782 m_legacy_range.clear();
1783 if(std::in_range<size_t>(range.
count())) {
1785 static_cast<size_t>(range.
count())});
1787 m_data = std::move(range);
1792 if(m_legacy_range.empty()) {
1793 throw Invalid_State(
"TNAuthList range count does not fit in size_t, use range() instead");
1795 return m_legacy_range;
1799 return number().to_string();
1814 class TN_Interval final {
1822 m_last(m_first + range.
count() - 1) {}
1824 size_t length()
const {
return m_length; }
1826 uint64_t first()
const {
return m_first; }
1828 uint64_t last()
const {
return m_last; }
1830 void update_last(uint64_t last) { m_last = last; }
1832 bool operator<(
const TN_Interval& other)
const {
1833 return std::tie(m_length, m_first) < std::tie(other.m_length, other.m_first);
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()));
1851 merged.push_back(interval);
1857 const auto is_covered = [](
const TN_Interval& child, std::span<const TN_Interval> merged) {
1859 const auto after = std::upper_bound(merged.begin(), merged.end(), child);
1860 if(after == merged.begin()) {
1863 const TN_Interval& block = *(after - 1);
1864 return block.length() == child.length() && block.first() <= child.first() && child.last() <= block.last();
1867 std::set<std::string> spcs;
1868 std::set<TelephoneNumber> wildcards;
1869 std::vector<TN_Interval> intervals;
1871 for(
const auto& entry : m_tn_entries) {
1872 switch(entry.type()) {
1874 spcs.insert(entry.service_provider_code());
1877 if(entry.number().is_wildcard()) {
1878 wildcards.insert(entry.number());
1880 intervals.emplace_back(entry.number());
1884 intervals.emplace_back(entry.range());
1889 const std::vector<TN_Interval> merged = merge_intervals(std::move(intervals));
1891 for(
const auto& entry : delegate.
entries()) {
1892 switch(entry.type()) {
1894 if(!spcs.contains(entry.service_provider_code())) {
1902 if(entry.number().is_wildcard()) {
1903 if(!wildcards.contains(entry.number())) {
1906 }
else if(!is_covered(TN_Interval(entry.number()), merged)) {
1914 if(!is_covered(TN_Interval(entry.range()), merged)) {
1930 const std::optional<X509_Certificate>& ,
1931 const std::vector<X509_Certificate>& cert_path,
1932 std::vector<std::set<Certificate_Status_Code>>& cert_status,
1934 for(
size_t i = pos + 1; i < cert_path.size(); ++i) {
1936 const auto* ancestor = cert_path[i].v3_extensions().get_extension_object_as<
TNAuthList>();
1937 if(ancestor !=
nullptr && !ancestor->encompasses(*
this)) {
1945 std::vector<uint8_t> output;
1950void IPAddressBlocks::decode_inner(
const std::vector<uint8_t>& in) {
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());
1967 throw Decoding_Error(
"IPAddrBlocks families must be sorted by AFI/SAFI and not repeat");
1974 for(
const IPAddressFamily& block : m_ip_addr_blocks) {
1975 if(block.afi() == 1) {
1988 if(m_safi.has_value()) {
1989 afam.push_back(m_safi.value());
2005 throw Decoding_Error(
fmt(
"Unexpected type for IPAddressFamily {}",
static_cast<uint32_t
>(next_tag)));
2010 std::vector<uint8_t> addr_family;
2012 const size_t addr_family_length = addr_family.size();
2014 if(addr_family_length != 2 && addr_family_length != 3) {
2018 m_afi = (addr_family[0] << 8) | addr_family[1];
2020 if(addr_family_length == 3) {
2021 m_safi = addr_family[2];
2028 }
else if(m_afi == 2) {
2041template <IPAddressBlocks::Version V>
2047 BOTAN_ASSERT(!blocks.empty(),
"Cannot merge an empty set of IP address blocks into a single family");
2050 if(blocks.size() == 1) {
2054 bool all_inherit =
true;
2055 bool none_inherit =
true;
2057 const auto choice = std::get<IPAddressBlocks::IPAddressChoice<V>>(block.addr_choice());
2058 all_inherit = !choice.ranges().has_value() && all_inherit;
2059 none_inherit = choice.ranges().has_value() && none_inherit;
2064 return IPAddressBlocks::IPAddressFamily(IPAddressBlocks::IPAddressChoice<V>(), blocks[0].safi());
2068 if(!all_inherit && !none_inherit) {
2069 throw Decoding_Error(
"Invalid IPAddressBlocks: Only one of 'inherit' or 'do not inherit' is allowed per family");
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);
2082 IPAddressBlocks::IPAddressChoice<V> choice(merged_ranges);
2083 IPAddressBlocks::IPAddressFamily fam(choice, blocks[0].safi());
2089void IPAddressBlocks::sort_and_merge() {
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);
2107 std::vector<IPAddressFamily> merged_blocks;
2108 size_t v4_count = 0;
2109 size_t v6_count = 0;
2110 for(
auto& it : afam_map) {
2112 std::vector<IPAddressFamily>& fams = it.second;
2118 if(std::holds_alternative<IPAddressChoice<Version::IPv4>>(fams[0].addr_choice())) {
2119 merged_blocks.push_back(merge<Version::IPv4>(fams));
2122 merged_blocks.push_back(merge<Version::IPv6>(fams));
2127 m_ip_addr_blocks = std::move(merged_blocks);
2128 m_v4_count = v4_count;
2129 m_v6_count = v6_count;
2137template <IPAddressBlocks::Version V>
2138using IPRangeVec = std::vector<IPAddressBlocks::IPAddressOrRange<V>>;
2142template <IPAddressBlocks::Version V>
2143using IPValidationMap = std::map<uint32_t, std::pair<bool, const IPRangeVec<V>*>>;
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) {
2155 using Address = std::conditional_t<V == IPv4, IPv4Address, IPv6Address>;
2156 return IPAddressBlocks::IPAddress<V>(Address(bytes));
2159template <std::
unsigned_
integral T>
2161 return static_cast<T
>(x + 1);
2164template <
typename T>
2165std::optional<std::vector<T>> sort_and_merge_ranges(std::optional<std::span<const T>> ranges) {
2170 if(!ranges.has_value()) {
2171 return std::nullopt;
2174 std::vector<T> sorted(ranges.value().begin(), ranges.value().end());
2176 if(sorted.empty()) {
2181 std::sort(sorted.begin(), sorted.end(), [](T& a, T& b) { return a.min() < b.min(); });
2184 std::vector<T> merged;
2185 merged.reserve(sorted.size());
2186 merged.push_back(sorted[0]);
2188 for(
size_t i = 1; i < sorted.size(); ++i) {
2189 auto& back = merged.back();
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()));
2194 merged.push_back(sorted[i]);
2203template <
typename T>
2204bool ranges_are_sorted_and_merged(
const std::vector<T>& ranges) {
2205 for(
size_t i = 1; i < ranges.size(); i++) {
2208 if(!(ranges[i - 1].max() < ranges[i].min())) {
2213 if(successor(ranges[i - 1].max()) == ranges[i].min()) {
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();
2228 while(i < min.size() && min[i] == max[i]) {
2231 if(i == min.size()) {
2233 return 8 * min.size();
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;
2242 for(
size_t j = i + 1; j < min.size(); j++) {
2243 if(min[j] != 0x00 || max[j] != 0xFF) {
2244 return std::nullopt;
2247 return 8 * i + common_bits;
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();
2256template <
typename T>
2257bool validate_subject_in_issuer(std::span<const T> subject, std::span<const T> issuer) {
2262 if(issuer.empty()) {
2263 return subject.empty();
2265 for(
auto subj = subject.begin(), issu = issuer.begin(); subj != subject.end();) {
2267 if(subj->min() > issu->max()) {
2270 if(issu == issuer.end() && subj != subject.end()) {
2275 if(subj->min() < issu->min()) {
2279 if(subj->max() > issu->max()) {
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)));
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;
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();
2311 if(std::holds_alternative<IPAddressBlocks::IPAddressChoice<IPv4>>(a_choice)) {
2312 populate_validation_map(afam, a_choice, v4_map);
2314 populate_validation_map(afam, a_choice, v6_map);
2318 return std::make_pair(v4_map, v6_map);
2323template <IPAddressBlocks::Version V>
2325 std::optional<std::span<
const IPAddressBlocks::IPAddressOrRange<V>>> ranges) {
2327 m_ip_addr_ranges = sort_and_merge_ranges<IPAddressOrRange<V>>(ranges);
2330template <IPAddressBlocks::Version V>
2332 if(m_ip_addr_ranges.has_value()) {
2339template <IPAddressBlocks::Version V>
2345 m_ip_addr_ranges = std::nullopt;
2347 std::vector<IPAddressOrRange<V>> ip_ranges;
2356 if(!ranges_are_sorted_and_merged(ip_ranges)) {
2357 throw Decoding_Error(
"IPAddressChoice entries must be sorted, non-overlapping and fully merged");
2359 m_ip_addr_ranges = std::move(ip_ranges);
2361 throw Decoding_Error(
fmt(
"Unexpected type for IPAddressChoice {}",
static_cast<uint32_t
>(next_tag)));
2365template <IPAddressBlocks::Version V>
2381 const size_t version_octets =
static_cast<size_t>(V);
2383 std::array<uint8_t, version_octets>
min = m_min.to_bytes();
2384 std::array<uint8_t, version_octets>
max = m_max.to_bytes();
2389 bool zeros_done =
false;
2390 bool ones_done =
false;
2393 for(
size_t i = version_octets; i > 0; i--) {
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);
2401 const uint8_t local_ones =
static_cast<uint8_t
>(std::countr_one(
max[i - 1]));
2403 ones_done = (local_ones != 8);
2406 if(zeros_done && ones_done) {
2412 const uint8_t host = std::min(zeros, ones);
2415 const uint8_t discarded_octets = host / 8;
2417 const uint8_t unused_bits = host % 8;
2419 bool octets_match =
true;
2420 bool used_bits_match =
true;
2423 if(discarded_octets < version_octets) {
2425 for(
size_t i = 0; i < static_cast<uint8_t>(version_octets - discarded_octets - 1); i++) {
2427 octets_match =
false;
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);
2440 if(octets_match && used_bits_match) {
2442 into.
encode_bitstring(std::span{
min}.first(version_octets - discarded_octets), unused_bits);
2444 const uint8_t discarded_octets_min = zeros / 8;
2445 const uint8_t unused_bits_min = zeros % 8;
2447 const uint8_t discarded_octets_max = ones / 8;
2448 const uint8_t unused_bits_max = ones % 8;
2451 if(unused_bits_max != 0) {
2453 max[version_octets - 1 - discarded_octets_max] >>= unused_bits_max;
2454 max[version_octets - 1 - discarded_octets_max] <<= unused_bits_max;
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)
2464template <IPAddressBlocks::Version V>
2476 m_min = decode_single_address(prefix,
true);
2478 m_max = decode_single_address(prefix,
false);
2501 throw Decoding_Error(
"IPAddressRange minimum must have trailing zero bits removed");
2504 throw Decoding_Error(
"IPAddressRange maximum must have trailing one bits removed");
2507 m_min = decode_single_address(addr_min,
true);
2508 m_max = decode_single_address(addr_max,
false);
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");
2525 throw Decoding_Error(
fmt(
"Unexpected type for IPAddressOrRange {}",
static_cast<uint32_t
>(next_tag)));
2529template <IPAddressBlocks::Version V>
2532 const size_t version_octets =
static_cast<size_t>(V);
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));
2540 std::vector<uint8_t> address(decoded.
bytes().begin(), decoded.
bytes().end());
2545 address.back() |=
static_cast<uint8_t
>((1 << decoded.
unused_bits()) - 1);
2549 address.resize(version_octets, min ? 0x00 : 0xFF);
2551 return IPAddressBlocks::IPAddress<V>::from_bytes(address);
2554template <IPAddressBlocks::Version V>
2556 if(
auto prefix_len = range_prefix_length<V>(m_min, m_max)) {
2557 return Subnet(m_min, *prefix_len);
2559 return std::nullopt;
2562template <IPAddressBlocks::Version V>
2565template <IPAddressBlocks::Version V>
2567 return Cert_Extension::successor(*
this);
2570template <IPAddressBlocks::Version V>
2572 if(v.size() != Length) {
2573 throw Decoding_Error(
"number of bytes does not match IP version used");
2576 IPAddress<V> addr{};
2577 std::copy(v.begin(), v.end(), addr.m_value.begin());
2582 const std::optional<X509_Certificate>& ,
2583 const std::vector<X509_Certificate>& cert_path,
2584 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2587 auto [v4_needs_check, v6_needs_check] = create_validation_map(m_ip_addr_blocks);
2589 if(pos == cert_path.size() - 1) {
2591 const auto validate_root_cert_ext = [&](
const auto& map) {
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;
2599 if(validate_root_cert_ext(v4_needs_check) || validate_root_cert_ext(v6_needs_check)) {
2606 for(
auto cert_path_it = cert_path.begin() + pos + 1; cert_path_it != cert_path.end(); cert_path_it++) {
2609 if(parent_ip ==
nullptr) {
2613 auto [issuer_v4, issuer_v6] = create_validation_map(parent_ip->
addr_blocks());
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;
2620 if(issuer_map.count(afam) == 0) {
2625 auto& [needs_check, subject_value] = validation_info;
2626 const auto& [issuer_has_value, issuer_value] = issuer_map.at(afam);
2631 if(needs_check && issuer_has_value) {
2632 if(!validate_subject_in_issuer(std::span(*subject_value), std::span(*issuer_value))) {
2636 needs_check =
false;
2642 if(!validate_against_issuer(v4_needs_check, issuer_v4) || !validate_against_issuer(v6_needs_check, issuer_v6)) {
2646 const auto validate_no_checks_left = [&](
const auto& map) {
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;
2656 if(validate_no_checks_left(v4_needs_check) && validate_no_checks_left(v6_needs_check)) {
2671 std::vector<uint8_t> output;
2676void ASBlocks::decode_inner(
const std::vector<uint8_t>& in) {
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)};
2686 range = old.value().ranges().value();
2687 range.push_back(ASIdOrRange(min, max));
2689 return ASIdentifierChoice(range);
2695 if(!m_asnum.has_value() && !m_rdi.has_value()) {
2699 if(m_asnum.has_value()) {
2701 into.
encode(m_asnum.value());
2705 if(m_rdi.has_value()) {
2707 into.
encode(m_rdi.value());
2717 throw Decoding_Error(
fmt(
"Unexpected type for ASIdentifiers {}",
static_cast<uint32_t
>(next_tag)));
2739 fmt(
"Unexpected type for ASIdentifiers rdi: {}",
static_cast<uint32_t
>(rdi_obj.
type_tag())));
2750 fmt(
"Unexpected element with type {} in ASIdentifiers",
static_cast<uint32_t
>(end.
type_tag())));
2757 throw Decoding_Error(
"ASIdentifiers must contain an asnum or rdi element");
2760 fmt(
"Unexpected element with type {} in ASIdentifiers",
static_cast<uint32_t
>(elem_obj.
type_tag())));
2765 if(!m_asnum.has_value() && !m_rdi.has_value()) {
2771 if(m_as_ranges.has_value()) {
2779 m_as_ranges = sort_and_merge_ranges<ASIdOrRange>(
ranges);
2787 m_as_ranges = std::nullopt;
2789 std::vector<ASIdOrRange> as_ranges;
2798 if(!ranges_are_sorted_and_merged(as_ranges)) {
2799 throw Decoding_Error(
"ASIdentifierChoice entries must be sorted, non-overlapping and fully merged");
2801 m_as_ranges = std::move(as_ranges);
2803 throw Decoding_Error(
fmt(
"Unexpected type for ASIdentifierChoice {}",
static_cast<uint32_t
>(next_tag)));
2808 if(m_min == m_max) {
2809 into.
encode(
static_cast<size_t>(m_min));
2811 if(m_min >= m_max) {
2832 if(m_min >= m_max) {
2836 throw Decoding_Error(
fmt(
"Unexpected type for ASIdOrRange {}",
static_cast<uint32_t
>(next_tag)));
2841 const std::optional<X509_Certificate>& ,
2842 const std::vector<X509_Certificate>& cert_path,
2843 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2846 const bool asnum_present = m_as_identifiers.asnum().has_value();
2847 const bool rdi_present = m_as_identifiers.rdi().has_value();
2849 if(!asnum_present && !rdi_present) {
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;
2859 if(pos == cert_path.size() - 1) {
2861 if((asnum_present && !asnum_needs_check) || (rdi_present && !rdi_needs_check)) {
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>();
2871 if(parent_as ==
nullptr || (asnum_present && !parent_as->
as_identifiers().
asnum().has_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();
2883 if(!validate_subject_in_issuer<ASBlocks::ASIdOrRange>(subject_asnums, issuer_asnums)) {
2888 asnum_needs_check =
false;
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();
2895 if(!validate_subject_in_issuer<ASBlocks::ASIdOrRange>(subject_rdis, issuer_rdis)) {
2900 rdi_needs_check =
false;
2903 if(!asnum_needs_check && !rdi_needs_check) {
2911 const std::optional<X509_Certificate>& ,
2912 const std::vector<X509_Certificate>& ,
2913 std::vector<std::set<Certificate_Status_Code>>& cert_status,
2928 return {0x05, 0x00};
2931void OCSP_NoCheck::decode_inner(
const std::vector<uint8_t>& buf) {
2937 return {0x05, 0x00};
2940void NoRevocationAvailable::decode_inner(
const std::vector<uint8_t>& buf) {
2946 const std::optional<X509_Certificate>& ,
2947 const std::vector<X509_Certificate>& ,
2948 std::vector<std::set<Certificate_Status_Code>>& cert_status,
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; });
3008void Unknown_Extension::decode_inner(
const std::vector<uint8_t>& bytes) {