Botan 3.14.1
Crypto and TLS for C&
pkix_types.h
Go to the documentation of this file.
1/*
2* (C) 1999-2010,2012,2018,2020 Jack Lloyd
3* (C) 2007 Yves Jerschow
4* (C) 2015 Kai Michaelis
5* (C) 2016 René Korthaus, Rohde & Schwarz Cybersecurity
6* (C) 2017 Fabian Weissberg, Rohde & Schwarz Cybersecurity
7*
8* Botan is released under the Simplified BSD License (see license.txt)
9*/
10
11#ifndef BOTAN_PKIX_TYPES_H_
12#define BOTAN_PKIX_TYPES_H_
13
14#include <botan/asn1_obj.h>
15
16#include <botan/dns_name.h>
17#include <botan/email.h>
18#include <botan/ipv4_address.h>
19#include <botan/ipv6_address.h>
20#include <botan/pkix_enums.h>
21#include <botan/uri.h>
22#include <compare>
23#include <initializer_list>
24#include <iosfwd>
25#include <map>
26#include <memory>
27#include <optional>
28#include <set>
29#include <string>
30#include <string_view>
31#include <variant>
32#include <vector>
33
34namespace Botan {
35
37class Public_Key;
38class BigInt;
40
41BOTAN_DEPRECATED("Use Key_Constraints::to_string")
42
44 return c.to_string();
45}
46
47/**
48* X.509 certificate serial number (RFC 5280 CertificateSerialNumber)
49*
50* Stores the value as the contents octets of the DER INTEGER encoding
51* (two's complement, minimal length), so the sign is preserved and
52* equality on the stored bytes is value equality.
53*
54* RFC 5280 4.1.2.2:
55* The serial number MUST be a positive integer assigned by the CA to
56* each certificate.
57* and
58* Note: Non-conforming CAs may issue certificates with serial numbers
59* that are negative or zero. Certificate users SHOULD be prepared to
60* gracefully handle such certificates.
61*
62* so non-conforming values are representable, and can be detected with
63* is_negative, is_zero and octet_length.
64*/
65class BOTAN_PUBLIC_API(3, 13) X509_Serial_Number final : public ASN1_Object {
66 public:
67 /**
68 * Serial number zero
69 */
70 X509_Serial_Number() : m_contents{0x00} {}
71
72 /**
73 * Create from an integer value
74 */
75 explicit X509_Serial_Number(const BigInt& value);
76
77 /**
78 * Create from an unsigned big-endian encoded integer
79 */
80 static X509_Serial_Number from_bytes(std::span<const uint8_t> bytes);
81
82 /**
83 * Create from the contents octets of a BER INTEGER (big-endian two's
84 * complement). Redundant leading octets are normalized away; an empty
85 * input is rejected.
86 */
87 static X509_Serial_Number from_der_contents(std::span<const uint8_t> contents);
88
89 /**
90 * Generate a serial number suitable for issuing a certificate.
91 *
92 * The result is positive, never zero, and contains 126 bits of output
93 * from the RNG. The topmost bit is cleared, and the 127th bit is set.
94 */
95 static X509_Serial_Number random(RandomNumberGenerator& rng);
96
97 /**
98 * Return true if the serial number is negative
99 *
100 * TODO(Botan4) remove this once negative serial numbers are prohibited
101 */
102 bool is_negative() const;
103
104 /**
105 * Return true if the serial number is the integer zero
106 */
107 bool is_zero() const;
108
109 /**
110 * Number of contents octets in the DER encoding of this value
111 */
112 size_t octet_length() const { return m_contents.size(); }
113
114 /**
115 * True if this serial number satisfies the RFC 5280 4.1.2.2 rules for
116 * conforming CAs: a positive integer of at most 20 octets
117 */
118 bool conforms_to_rfc5280() const { return !is_negative() && !is_zero() && octet_length() <= 20; }
119
120 /**
121 * The contents octets of the DER INTEGER encoding (big-endian two's
122 * complement, minimal length)
123 */
124 std::span<const uint8_t> der_contents() const { return m_contents; }
125
126 /**
127 * The absolute value as unsigned big-endian bytes without leading
128 * zeros. Note this loses the sign, and is empty for a zero serial;
129 * it matches X509_Certificate::serial_number.
130 */
131 std::vector<uint8_t> magnitude() const;
132
133 BigInt to_bigint() const;
134
135 /**
136 * The value in hex, prefixed with '-' if negative
137 */
138 std::string to_string() const;
139
140 void encode_into(DER_Encoder& to) const override;
141 void decode_from(BER_Decoder& from) override;
142
143 bool operator==(const X509_Serial_Number& other) const { return m_contents == other.m_contents; }
144
145 /**
146 * Numeric ordering
147 */
148 std::strong_ordering operator<=>(const X509_Serial_Number& other) const;
149
150 private:
151 std::vector<uint8_t> m_contents;
152};
153
154/**
155* Distinguished Name
156*/
157class BOTAN_PUBLIC_API(2, 0) X509_DN final : public ASN1_Object {
158 public:
159 X509_DN() = default;
160
161 X509_DN(std::initializer_list<std::pair<std::string_view, std::string_view>> args) {
162 for(const auto& i : args) {
163 add_attribute(i.first, i.second);
164 }
165 }
166
167 /**
168 * Since DN matching for Name Constraints requires preserving order and
169 * multimaps have sorted keys, this constructor is deprecated.
170 */
171 BOTAN_DEPRECATED("Deprecated use initializer list constructor")
172 explicit X509_DN(const std::multimap<OID, std::string>& args) {
173 for(const auto& i : args) {
174 add_attribute(i.first, i.second);
175 }
176 }
177
178 /**
179 * Since DN matching for Name Constraints requires preserving order and
180 * multimaps have sorted keys, this constructor is deprecated.
181 */
182 BOTAN_DEPRECATED("Deprecated use initializer list constructor")
183 explicit X509_DN(const std::multimap<std::string, std::string>& args) {
184 for(const auto& i : args) {
185 add_attribute(i.first, i.second);
186 }
187 }
188
189 void encode_into(DER_Encoder& to) const override;
190 void decode_from(BER_Decoder& from) override;
191
192 bool has_field(const OID& oid) const;
193 ASN1_String get_first_attribute(const OID& oid) const;
194
195 /*
196 * Return the BER encoded data, if any
197 */
198 const std::vector<uint8_t>& get_bits() const { return m_dn_bits; }
199
200 std::vector<uint8_t> DER_encode() const;
201
202 bool empty() const { return m_rdn.empty(); }
203
204 /**
205 * Number of relative distinguished names (RDNs) in the DN. Note: prior
206 * to multi-AVA RDN support this returned the total number of AVAs; the
207 * two differ only when the DN contains a multi-valued RDN.
208 */
209 size_t count() const { return m_rdn.size(); }
210
211 std::string to_string() const;
212
213 /**
214 * Parse the string representation of a distinguished name.
215 *
216 * The grammar accepted is a subset of RFC 4514 Section 3, but also accepts
217 * quoted-value forms ala RFC 2253. The entire input must be consumed.
218 *
219 * @param str the string to parse
220 * @return the parsed DN, or nullopt if @p str is not a well-formed DN
221 */
222 static std::optional<X509_DN> parse(std::string_view str);
223
224 /**
225 * Return the DN as a sequence of RDNs. Each RDN is an X.501
226 * SET OF AttributeTypeAndValue; the inner vector preserves the
227 * decoded order but RDN equality is set-based per RFC 5280 7.1.
228 */
229 const std::vector<std::vector<std::pair<OID, ASN1_String>>>& rdns() const { return m_rdn; }
230
231 /**
232 * Return the DN attributes as a flat sequence of AVAs in decoded order.
233 * RDN structure is not preserved in this view; prefer rdns() to retain it.
234 */
235 BOTAN_DEPRECATED("Use rdns() which preserves RDN structure")
236 std::vector<std::pair<OID, ASN1_String>> dn_info() const;
237
238 std::multimap<OID, std::string> get_attributes() const;
239 std::multimap<std::string, std::string> contents() const;
240
241 bool has_field(std::string_view attr) const;
242 std::vector<std::string> get_attribute(std::string_view attr) const;
243 std::string get_first_attribute(std::string_view attr) const;
244
245 void add_attribute(std::string_view key, std::string_view val);
246
247 void add_attribute(const OID& oid, std::string_view val) { add_attribute(oid, ASN1_String(val)); }
248
249 void add_attribute(const OID& oid, const ASN1_String& val);
250
251 /**
252 * Append a complete RDN. The provided AVAs become one
253 * RelativeDistinguishedName (X.501 SET OF AttributeTypeAndValue).
254 * An empty input is ignored.
255 */
256 void add_rdn(std::vector<std::pair<OID, ASN1_String>> rdn);
257
258 static std::string deref_info_field(std::string_view key);
259
260 /**
261 * Lookup upper bounds in characters for the length of distinguished name fields
262 * as given in RFC 5280, Appendix A.
263 *
264 * @param oid the oid of the DN to lookup
265 * @return the upper bound, or zero if no ub is known to Botan
266 */
267 static size_t lookup_ub(const OID& oid);
268
269 /**
270 * Return a canonical byte encoding
271 *
272 * Internal interface, not covered by SemVer
273 */
274 const std::vector<uint8_t>& _canonical_bytes() const { return m_canonical_dn_bits; }
275
276 private:
277 // Outer vector: sequence of RDNs. Inner vector: AVAs within
278 // one RDN (X.501 SET OF AttributeTypeAndValue).
279 std::vector<std::vector<std::pair<OID, ASN1_String>>> m_rdn;
280 std::vector<uint8_t> m_dn_bits;
281 std::vector<uint8_t> m_canonical_dn_bits;
282};
283
284BOTAN_PUBLIC_API(2, 0) bool operator==(const X509_DN& dn1, const X509_DN& dn2);
285BOTAN_PUBLIC_API(2, 0) bool operator!=(const X509_DN& dn1, const X509_DN& dn2);
286
287/*
288The ordering here is arbitrary and may change from release to release.
289It is intended for allowing DNs as keys in std::map and similar containers
290*/
291BOTAN_PUBLIC_API(2, 0) bool operator<(const X509_DN& dn1, const X509_DN& dn2);
292
293BOTAN_PUBLIC_API(2, 0) std::ostream& operator<<(std::ostream& out, const X509_DN& dn);
294
295/**
296* Parse the input stream as a DN
297* Prefer X509_DN::parse
298*/
299BOTAN_DEPRECATED_API("Use X509_DN::parse") std::istream& operator>>(std::istream& in, X509_DN& dn);
300
301/**
302* Alternative Name
303*/
304class BOTAN_PUBLIC_API(2, 0) AlternativeName final : public ASN1_Object {
305 public:
306 /// An "OtherName" GeneralName entry: type-id OID and the inner ANY value as raw BER
307 class OtherNameValue final {
308 public:
309 const OID& oid() const { return m_oid; }
310
311 std::span<const uint8_t> value() const { return m_value; }
312
313 bool operator<(const OtherNameValue& other) const {
314 if(oid() != other.oid()) {
315 return oid() < other.oid();
316 }
317 return m_value < other.m_value;
318 }
319
320 private:
321 friend class AlternativeName;
322
323 OtherNameValue(const OID& oid, std::vector<uint8_t> value) : m_oid(oid), m_value(std::move(value)) {}
324
325 OtherNameValue(const OID& oid, std::span<const uint8_t> value) :
326 m_oid(oid), m_value(value.begin(), value.end()) {}
327
328 OID m_oid;
329 std::vector<uint8_t> m_value;
330 };
331
332 void encode_into(DER_Encoder& to) const override;
333 void decode_from(BER_Decoder& from) override;
334
335 /// Create an empty name
336 AlternativeName() = default;
337
338 /// Add a URI to this AlternativeName, parsing and validating the input
339 void add_uri(std::string_view uri);
340
341 /// Add a previously parsed URI to this AlternativeName
342 void add_uri(URI uri);
343
344 /// Add an email address to this AlternativeName, parsing and validating the input
345 void add_email(std::string_view addr);
346
347 /// Add a previously parsed email address to this AlternativeName
348 void add_email(EmailAddress addr);
349
350 /// Add a DNS name to this AlternativeName, parsing and validating the input
351 void add_dns(std::string_view dns);
352
353 /// Add a previously parsed DNS name to this AlternativeName
354 void add_dns(DNSName dns);
355
356 /// Add an "OtherName" identified by object identifier to this AlternativeName
357 void add_other_name(const OID& oid, const ASN1_String& value);
358
359 /// Add an "OtherName" with arbitrary inner value, given as raw BER bytes
360 ///
361 /// `value` must be a complete BER-encoded object (tag + length + content)
362 /// representing the inner ANY value of the OtherName.
363 void add_other_name_value(const OID& oid, std::span<const uint8_t> value);
364
365 /// Add a registeredID (RFC 5280 [8])
366 void add_registered_id(const OID& oid);
367
368 /// Add a directory name to this AlternativeName
369 void add_dn(const X509_DN& dn);
370
371 /// Add an IP address to this alternative name
372 BOTAN_DEPRECATED("Use variant taking IPv4Address") void add_ipv4_address(uint32_t ipv4) {
373 this->add_ipv4_address(IPv4Address(ipv4));
374 }
375
376 /// Add an IP address to this alternative name
377 void add_ipv4_address(const IPv4Address& ipv4);
378
379 /// Add an IPv6 address to this alternative name
380 void add_ipv6_address(const IPv6Address& ipv6);
381
382 /// Return the set of URIs included in this alternative name
383 ///
384 /// Deprecated: use uri_names() instead, which exposes the parsed
385 /// URI values. This accessor constructs a copy.
386 BOTAN_DEPRECATED("Use AlternativeName::uri_names") std::set<std::string> uris() const;
387
388 /// Return the set of URIs included in this alternative name
389 const std::set<URI>& uri_names() const { return m_uri; }
390
391 /// Return the set of email addresses included in this alternative name
392 ///
393 /// Deprecated: use email_addresses() instead, which exposes the
394 /// parsed EmailAddress values. This accessor constructs a copy.
395 BOTAN_DEPRECATED("Use AlternativeName::email_addresses") std::set<std::string> email() const;
396
397 /// Return the set of email addresses included in this alternative name
398 const std::set<EmailAddress>& email_addresses() const { return m_email; }
399
400 /// Return the set of DNS names included in this alternative name
401 ///
402 /// Deprecated: use dns_names() instead, which exposes the parsed
403 /// DNSName values. This accessor constructs a copy.
404 BOTAN_DEPRECATED("Use AlternativeName::dns_names") std::set<std::string> dns() const;
405
406 /// Return the set of DNS names included in this alternative name
407 const std::set<DNSName>& dns_names() const { return m_dns; }
408
409 /// Return the set of IPv4 addresses included in this alternative name
410 BOTAN_DEPRECATED("Use ipv4_addresses") std::set<uint32_t> ipv4_address() const;
411
412 /// Return the set of IPv6 addresses included in this alternative name
413 BOTAN_DEPRECATED("Use ipv6_addresses") const std::set<IPv6Address>& ipv6_address() const {
414 return ipv6_addresses();
415 }
416
417 /// Return the set of IPv4 addresses included in this alternative name
418 const std::set<IPv4Address>& ipv4_addresses() const { return m_ipv4_addrs; }
419
420 /// Return the set of IPv6 addresses included in this alternative name
421 const std::set<IPv6Address>& ipv6_addresses() const { return m_ipv6_addrs; }
422
423 /// Return the set of "other names" whose value was a recognized ASN1_String type
424 BOTAN_DEPRECATED("Use AlternativeName::other_name_values")
425 const std::set<std::pair<OID, ASN1_String>>& other_names() const {
426 return m_othernames;
427 }
428
429 /// Return all "OtherName" entries with their inner ANY value as raw BER
430 const std::set<OtherNameValue>& other_name_values() const { return m_other_name_values; }
431
432 /// Return the set of `SmtpUTF8Mailbox` SAN entries (RFC 9598).
433 ///
434 /// Any such values are also included with their raw encoding in other_name_values
435 const std::set<SmtpUtf8Mailbox>& smtp_utf8_mailboxes() const { return m_smtp_utf8_mailboxes; }
436
437 /// Return the set of registeredID OIDs
438 const std::set<OID>& registered_ids() const { return m_registered_ids; }
439
440 /// Return the set of directory names included in this alternative name
441 const std::set<X509_DN>& directory_names() const { return m_dn_names; }
442
443 /// Return the total number of names in this AlternativeName
444 ///
445 /// This only counts names which were parsed, ignoring names which
446 /// were of some unknown type
447 size_t count() const;
448
449 /// Return true if this has any names set
450 bool has_items() const;
451
452 /// Return true if this alternative name is empty (zero names)
453 bool is_empty() const;
454
455 // Old, now deprecated interface follows:
456 BOTAN_DEPRECATED("Use AlternativeName::{uris, email, dns, othernames, directory_names}")
457 std::multimap<std::string, std::string> contents() const;
458
459 BOTAN_DEPRECATED("Use AlternativeName::{uris, email, dns, othernames, directory_names}.empty()")
460 bool has_field(std::string_view attr) const;
461
462 BOTAN_DEPRECATED("Use AlternativeName::{uris, email, dns, othernames, directory_names}")
463 std::vector<std::string> get_attribute(std::string_view attr) const;
464
465 BOTAN_DEPRECATED("Use AlternativeName::{uris, email, dns, othernames, directory_names}")
466 std::multimap<std::string, std::string, std::less<>> get_attributes() const;
467
468 BOTAN_DEPRECATED("Use AlternativeName::{uris, email, dns, othernames, directory_names}")
469 std::string get_first_attribute(std::string_view attr) const;
470
471 BOTAN_DEPRECATED("Use AlternativeName::add_{uri, dns, email, ...}")
472 void add_attribute(std::string_view type, std::string_view value);
473
474 BOTAN_DEPRECATED("Use AlternativeName::add_other_name")
475 void add_othername(const OID& oid, std::string_view value, ASN1_Type type);
476
477 BOTAN_DEPRECATED("Use AlternativeName::othernames") std::multimap<OID, ASN1_String> get_othernames() const;
478
479 /**
480 * This returns all of the alternative name DNs combined into a single DN
481 *
482 * This result is not a valid DN. The logic is retained for compatibility,
483 * but this function should not be used. It will be removed in Botan4.
484 */
485 BOTAN_DEPRECATED("Use AlternativeName::directory_names") X509_DN dn() const;
486
487 BOTAN_DEPRECATED("Use plain constructor plus add_{uri,dns,email,ipv4_address}")
488 BOTAN_FUTURE_EXPLICIT AlternativeName(std::string_view email_addr,
489 std::string_view uri = "",
490 std::string_view dns = "",
491 std::string_view ip_address = "");
492
493 private:
494 std::set<DNSName> m_dns;
495 std::set<URI> m_uri;
496 std::set<EmailAddress> m_email;
497 std::set<IPv4Address> m_ipv4_addrs;
498 std::set<IPv6Address> m_ipv6_addrs;
499 std::set<X509_DN> m_dn_names;
500 std::set<std::pair<OID, ASN1_String>> m_othernames; // TODO(Botan4) remove this
501 std::set<OtherNameValue> m_other_name_values;
502 std::set<SmtpUtf8Mailbox> m_smtp_utf8_mailboxes;
503 std::set<OID> m_registered_ids;
504};
505
506/**
507* Attribute
508*/
509class BOTAN_PUBLIC_API(2, 0) Attribute final : public ASN1_Object {
510 public:
511 void encode_into(DER_Encoder& to) const override;
512 void decode_from(BER_Decoder& from) override;
513
514 Attribute() = default;
515 Attribute(const OID& oid, const std::vector<uint8_t>& params);
516 Attribute(std::string_view oid_str, const std::vector<uint8_t>& params);
517
518 const OID& oid() const { return m_oid; }
519
520 const std::vector<uint8_t>& parameters() const { return m_parameters; }
521
522 const OID& object_identifier() const { return m_oid; }
523
524 const std::vector<uint8_t>& get_parameters() const { return m_parameters; }
525
526 private:
527 OID m_oid;
528 std::vector<uint8_t> m_parameters;
529};
530
531/**
532* @brief X.509 GeneralName Type
533*
534* Handles parsing GeneralName types in their BER and canonical string
535* encoding. Allows matching GeneralNames against each other using
536* the rules laid out in the RFC 5280, sec. 4.2.1.10 (Name Constraints).
537*
538* This entire class is deprecated and will be removed in a future
539* major release
540*/
541class BOTAN_PUBLIC_API(2, 0) GeneralName final : public ASN1_Object {
542 public:
543 enum MatchResult : uint8_t /* NOLINT(*-use-enum-class) */ {
549 };
550
551 enum class NameType : uint8_t {
553 RFC822 = 1,
554 DNS = 2,
555 URI = 3,
556 DN = 4,
557 IPv4 = 5,
558 IPv6 = 6,
559 Other = 7,
560 };
561
562 BOTAN_DEPRECATED("Deprecated use NameConstraints") GeneralName() = default;
563
564 static GeneralName email(std::string_view email);
565 static GeneralName dns(std::string_view dns);
566 static GeneralName uri(std::string_view uri);
568 static GeneralName ipv4_address(uint32_t ipv4);
569 static GeneralName ipv4_address(uint32_t ipv4, uint32_t mask);
571 static GeneralName ipv4_address(const IPv4Subnet& subnet);
572 static GeneralName ipv6_address(const IPv6Address& ipv6);
573 static GeneralName ipv6_address(const IPv6Subnet& subnet);
574
575 /**
576 * Wrap a URI SAN in a GeneralName, this is used for ffi
577 * @warning internal function that may be removed at any time
578 */
579 static GeneralName _uri_san_value(std::string_view full_uri);
580
581 /**
582 * Wrap a DNS SAN in a GeneralName, this is used for ffi
583 * @warning internal function that may be removed at any time
584 */
585 static GeneralName _dns_san_value(std::string_view dns);
586
587 void encode_into(DER_Encoder& to) const override;
588
589 void decode_from(BER_Decoder& from) override;
590
591 /**
592 * @return Type of the name expressed in this restriction
593 */
594 NameType type_code() const { return m_type; }
595
596 /**
597 * @return Type of the name. Can be DN, DNS, IP, RFC822 or URI.
598 */
599 BOTAN_DEPRECATED("Deprecated use type_code") std::string type() const;
600
601 /**
602 * @return The name as string. Format depends on type.
603 */
604 BOTAN_DEPRECATED("Deprecated no replacement") std::string name() const;
605
606 /**
607 * @return The name as binary string. Format depends on type.
608 */
609 BOTAN_DEPRECATED("Deprecated no replacement") std::vector<uint8_t> binary_name() const;
610
611 /**
612 * Checks whether a given certificate (partially) matches this name.
613 * @param cert certificate to be matched
614 * @return the match result
615 */
616 BOTAN_DEPRECATED("Deprecated use NameConstraints type") MatchResult matches(const X509_Certificate& cert) const;
617
618 bool matches_dns(const std::string& dns_name) const;
619 bool matches_dns(const DNSName& dns_name) const;
620
621 bool matches_ipv4(uint32_t ip) const;
622
623 bool matches_ipv4(const IPv4Address& ip) const { return matches_ipv4(ip.address()); }
624
625 bool matches_ipv6(const IPv6Address& ip) const;
626 bool matches_dn(const X509_DN& dn) const;
627 bool matches_uri(const URI& uri) const;
628 bool matches_email(const EmailAddress& addr) const;
629 bool matches_email(const SmtpUtf8Mailbox& mailbox) const;
630
631 private:
632 friend class NameConstraints;
633
634 class EmailConstraint final {
635 public:
636 EmailConstraint() = default;
637
638 static std::optional<EmailConstraint> from_string(std::string_view input);
639
640 const std::string& value() const { return m_value; }
641
642 auto operator<=>(const EmailConstraint&) const = default;
643
644 private:
645 explicit EmailConstraint(std::string value) : m_value(std::move(value)) {}
646
647 std::string m_value;
648 };
649
650 class DNSConstraint final {
651 public:
652 DNSConstraint() = default;
653
654 static std::optional<DNSConstraint> from_string(std::string_view input);
655
656 static std::optional<DNSConstraint> from_san_value(std::string_view input);
657
658 const std::string& value() const { return m_value; }
659
660 auto operator<=>(const DNSConstraint&) const = default;
661
662 private:
663 explicit DNSConstraint(std::string value) : m_value(std::move(value)) {}
664
665 std::string m_value;
666 };
667
668 class URIConstraint final {
669 public:
670 URIConstraint() = default;
671
672 static std::optional<URIConstraint> from_string(std::string_view input);
673
674 static std::optional<URIConstraint> from_san_value(std::string_view full_uri);
675
676 const std::string& value() const { return m_value; }
677
678 auto operator<=>(const URIConstraint&) const = default;
679
680 private:
681 explicit URIConstraint(std::string value) : m_value(std::move(value)) {}
682
683 std::string m_value;
684 };
685
686 /*
687 TODO: consider adding OtherConstraint and UnknownConstraint types here and eliminating m_type,
688 using m_name variant choice as the single source of the constraint type
689 */
690 using NameVariant = std::variant<EmailConstraint, DNSConstraint, URIConstraint, X509_DN, IPv4Subnet, IPv6Subnet>;
691
692 GeneralName(NameType type, NameVariant name) : m_type(type), m_name(std::move(name)) {}
693
694 NameType m_type = NameType::Unknown;
695 NameVariant m_name;
696
697 /**
698 * Partial DN matching according to RFC 5280, Section 7.1, i.e.,
699 * whether the constraint is a prefix of the name.
700 */
701 static bool matches_dn(const X509_DN& name, const X509_DN& constraint);
702};
703
704BOTAN_DEPRECATED("Deprecated no replacement") std::ostream& operator<<(std::ostream& os, const GeneralName& gn);
705
706/**
707* @brief A single Name Constraint
708*
709* The Name Constraint extension adds a minimum and maximum path
710* length to a GeneralName to form a constraint. The length limits
711* are not used in PKIX.
712*
713* This entire class is deprecated and will be removed in a future
714* major release
715*/
716class BOTAN_PUBLIC_API(2, 0) GeneralSubtree final : public ASN1_Object {
717 public:
718 /**
719 * Creates an empty name constraint.
720 */
721 BOTAN_DEPRECATED("Deprecated use NameConstraints") GeneralSubtree();
722
723 /**
724 * Creates a name constraint over the given base name.
725 */
726 explicit GeneralSubtree(GeneralName base) : m_base(std::move(base)) {}
727
728 void encode_into(DER_Encoder& to) const override;
729
730 void decode_from(BER_Decoder& from) override;
731
732 /**
733 * @return name
734 */
735 const GeneralName& base() const { return m_base; }
736
737 private:
738 GeneralName m_base;
739};
740
741BOTAN_DEPRECATED("Deprecated no replacement") std::ostream& operator<<(std::ostream& os, const GeneralSubtree& gs);
742
743/**
744* @brief Name Constraints
745*
746* Wraps the Name Constraints associated with a certificate.
747*/
749 public:
750 /**
751 * Creates an empty name NameConstraints.
752 */
753 NameConstraints() = default;
754
755 /**
756 * Creates NameConstraints from a list of permitted and excluded subtrees.
757 * @param permitted_subtrees names for which the certificate is permitted
758 * @param excluded_subtrees names for which the certificate is not permitted
759 */
760 NameConstraints(std::vector<GeneralSubtree>&& permitted_subtrees,
761 std::vector<GeneralSubtree>&& excluded_subtrees);
762
763 /**
764 * @return permitted names
765 */
766 BOTAN_DEPRECATED("Deprecated no replacement") const std::vector<GeneralSubtree>& permitted() const {
767 return m_permitted_subtrees;
768 }
769
770 /**
771 * @return excluded names
772 */
773 BOTAN_DEPRECATED("Deprecated no replacement") const std::vector<GeneralSubtree>& excluded() const {
774 return m_excluded_subtrees;
775 }
776
777 /**
778 * Return true if all of the names in the certificate are permitted
779 */
780 bool is_permitted(const X509_Certificate& cert, bool reject_unknown) const;
781
782 /**
783 * Return true if any of the names in the certificate are excluded
784 */
785 bool is_excluded(const X509_Certificate& cert, bool reject_unknown) const;
786
787 private:
788 std::vector<GeneralSubtree> m_permitted_subtrees;
789 std::vector<GeneralSubtree> m_excluded_subtrees;
790
791 std::set<GeneralName::NameType> m_permitted_name_types;
792 std::set<GeneralName::NameType> m_excluded_name_types;
793};
794
796
797/**
798* X.509 Certificate Extension
799*/
800class BOTAN_PUBLIC_API(2, 0) Certificate_Extension /* NOLINT(*-special-member-functions) */ {
801 public:
802 /**
803 * Return object identifier for this extension
804 *
805 * @return OID representing this extension
806 */
807 virtual OID oid_of() const = 0;
808
809 /**
810 * Return string identifier for this extension
811 *
812 * If possible the OID table should match oid_name, ie
813 * `OID::from_string(ext->oid_name()) == ext->oid_of()`
814 *
815 * @return specific OID name, or empty if unknown
816 */
817 virtual std::string oid_name() const = 0;
818
819 /**
820 * Make a copy of this extension
821 * @return copy of this
822 */
823 virtual std::unique_ptr<Certificate_Extension> copy() const = 0;
824
825 /**
826 * Query if @param context is an appropriate context for this extension to exist
827 *
828 * Many extensions are used across different types of X509 objects but some
829 * are specific, this allows decoding to reject extensions in an
830 * inappropriate context.
831 */
832 virtual bool is_appropriate_context(Extension_Context context) const = 0;
833
834 /**
835 * Callback visited during path validation.
836 *
837 * An extension can implement this callback to inspect
838 * the path during path validation.
839 *
840 * If an error occurs during validation of this extension,
841 * an appropriate status code shall be added to cert_status.
842 *
843 * @param subject Subject certificate that contains this extension
844 * @param issuer Issuer certificate. nullopt for certificates with no
845 * available issuer (e.g. non self-signed trust anchors).
846 * @param cert_path Certificate path which is currently validated
847 * @param cert_status Certificate validation status codes for subject certificate
848 * @param pos Position of subject certificate in cert_path
849 */
850 virtual void validate(const X509_Certificate& subject,
851 const std::optional<X509_Certificate>& issuer,
852 const std::vector<X509_Certificate>& cert_path,
853 std::vector<std::set<Certificate_Status_Code>>& cert_status,
854 size_t pos) const;
855
856 virtual ~Certificate_Extension() = default;
857
858 protected:
859 friend class Extensions;
860
861 virtual bool should_encode() const { return true; }
862
863 virtual std::vector<uint8_t> encode_inner() const = 0;
864 virtual void decode_inner(const std::vector<uint8_t>&) = 0;
865};
866
867/**
868* X.509 Certificate Extension List
869*/
870class BOTAN_PUBLIC_API(2, 0) Extensions final : public ASN1_Object {
871 public:
872 /**
873 * Look up an object in the extensions, based on OID Returns
874 * nullptr if not set, if the extension was either absent or not
875 * handled. The pointer returned is owned by the Extensions
876 * object.
877 * This would be better with an optional<T> return value
878 */
879 const Certificate_Extension* get_extension_object(const OID& oid) const;
880
881 template <typename T>
882 const T* get_extension_object_as(const OID& oid = T::static_oid()) const {
883 if(const Certificate_Extension* extn = get_extension_object(oid)) {
884 // Unknown_Extension oid_name is empty
885 if(extn->oid_name().empty()) {
886 return nullptr;
887 } else if(const T* extn_as_T = dynamic_cast<const T*>(extn)) {
888 return extn_as_T;
889 } else {
890 throw Decoding_Error("Exception::get_extension_object_as dynamic_cast failed");
891 }
892 }
893
894 return nullptr;
895 }
896
897 /**
898 * Return the set of extensions in the order they appeared in the certificate
899 * (or as they were added, if constructed)
900 */
901 const std::vector<OID>& get_extension_oids() const { return m_extension_oids; }
902
903 /**
904 * Return the set of critical extensions in the order they appeared in the extension list
905 * (This may be an empty vector)
906 */
907 std::vector<OID> critical_extensions() const;
908
909 /**
910 * Return true if an extension was set
911 */
912 bool extension_set(const OID& oid) const;
913
914 /**
915 * Return true if an extension was set and marked critical
916 */
917 bool critical_extension_set(const OID& oid) const;
918
919 /**
920 * Return the raw bytes of the extension
921 * Will throw if OID was not set as an extension.
922 */
923 std::vector<uint8_t> get_extension_bits(const OID& oid) const;
924
925 void encode_into(DER_Encoder& to) const override;
926 void decode_from(BER_Decoder& from) override;
927 void decode_from(BER_Decoder& from, std::optional<Extension_Context> context);
928
929 /**
930 * Return true if an unrecognized critical extension was encountered
931 * during the most recent decode_from. Resets on each call to decode_from
932 * and is not affected by subsequent calls to add/replace/remove.
933 */
934 bool has_unknown_critical_extension() const { return m_has_unknown_critical_extension; }
935
936 /**
937 * Adds a new extension to the list.
938 * @param extn pointer to the certificate extension (Extensions takes ownership)
939 * @param critical whether this extension should be marked as critical
940 * @throw Invalid_Argument if the extension is already present in the list
941 */
942 void add(std::unique_ptr<Certificate_Extension> extn, bool critical = false);
943
944 /**
945 * Adds a new extension to the list unless it already exists. If the extension
946 * already exists within the Extensions object, the extn pointer will be deleted.
947 *
948 * @param extn pointer to the certificate extension (Extensions takes ownership)
949 * @param critical whether this extension should be marked as critical
950 * @return true if the object was added false if the extension was already used
951 */
952 bool add_new(std::unique_ptr<Certificate_Extension> extn, bool critical = false);
953
954 /**
955 * Adds an extension to the list or replaces it.
956 * @param extn the certificate extension
957 * @param critical whether this extension should be marked as critical
958 */
959 void replace(std::unique_ptr<Certificate_Extension> extn, bool critical = false);
960
961 /**
962 * Remove an extension from the list. Returns true if the
963 * extension had been set, false otherwise.
964 */
965 bool remove(const OID& oid);
966
967 /**
968 * Searches for an extension by OID and returns the result.
969 * Only the known extensions types declared in this header
970 * are searched for by this function.
971 * @return Copy of extension with oid, nullptr if not found.
972 * Can avoid creating a copy by using get_extension_object function
973 */
974 std::unique_ptr<Certificate_Extension> get(const OID& oid) const;
975
976 /**
977 * Searches for an extension by OID and returns the result decoding
978 * it to some arbitrary extension type chosen by the application.
979 *
980 * Only the unknown extensions, that is, extensions types that
981 * are not declared in this header, are searched for by this
982 * function.
983 *
984 * @return Pointer to new extension with oid, nullptr if not found.
985 */
986 template <typename T>
987 std::unique_ptr<T> get_raw(const OID& oid) const {
988 const auto extn_info = m_extension_info.find(oid);
989
990 if(extn_info != m_extension_info.end()) {
991 // Unknown_Extension oid_name is empty
992 if(extn_info->second.obj().oid_name().empty()) {
993 auto ext = std::make_unique<T>();
994 ext->decode_inner(extn_info->second.bits());
995 return ext;
996 }
997 }
998 return nullptr;
999 }
1000
1001 /**
1002 * Returns a copy of the list of extensions together with the corresponding
1003 * criticality flag. All extensions are encoded as some object, falling back
1004 * to Unknown_Extension class which simply allows reading the bytes as well
1005 * as the criticality flag.
1006 */
1007 std::vector<std::pair<std::unique_ptr<Certificate_Extension>, bool>> extensions() const;
1008
1009 /**
1010 * Invoke the validation callback for each extension.
1011 */
1012 void validate(const X509_Certificate& subject,
1013 const std::optional<X509_Certificate>& issuer,
1014 const std::vector<X509_Certificate>& cert_path,
1015 std::vector<std::set<Certificate_Status_Code>>& cert_status,
1016 size_t pos) const;
1017
1018 /**
1019 * Returns the list of extensions as raw, encoded bytes
1020 * together with the corresponding criticality flag.
1021 * Contains all extensions, including any extensions encoded as Unknown_Extension
1022 */
1023 std::map<OID, std::pair<std::vector<uint8_t>, bool>> extensions_raw() const;
1024
1025 size_t count() const { return m_extension_oids.size(); }
1026
1027 Extensions() = default;
1028
1029 Extensions(const Extensions&) = default;
1030 Extensions& operator=(const Extensions&) = default;
1031
1034
1035 ~Extensions() override = default;
1036
1037 private:
1038 static std::unique_ptr<Certificate_Extension> create_extn_obj(const OID& oid,
1039 bool critical,
1040 const std::vector<uint8_t>& body,
1041 std::optional<Extension_Context> context);
1042
1043 class BOTAN_UNSTABLE_API Extensions_Info final {
1044 public:
1045 Extensions_Info(bool critical, std::unique_ptr<Certificate_Extension> ext) :
1046 m_obj(std::move(ext)), m_bits(m_obj->encode_inner()), m_critical(critical) {}
1047
1048 Extensions_Info(bool critical, std::vector<uint8_t> encoding, std::unique_ptr<Certificate_Extension> ext) :
1049 m_obj(std::move(ext)), m_bits(std::move(encoding)), m_critical(critical) {}
1050
1051 bool is_critical() const { return m_critical; }
1052
1053 const std::vector<uint8_t>& bits() const { return m_bits; }
1054
1055 const Certificate_Extension& obj() const;
1056
1057 private:
1058 std::shared_ptr<Certificate_Extension> m_obj;
1059 std::vector<uint8_t> m_bits;
1060 bool m_critical = false;
1061 };
1062
1063 std::vector<OID> m_extension_oids;
1064 std::map<OID, Extensions_Info> m_extension_info;
1065 bool m_has_unknown_critical_extension = false;
1066};
1067
1068} // namespace Botan
1069
1070#endif
#define BOTAN_PUBLIC_API(maj, min)
Definition api.h:21
#define BOTAN_UNSTABLE_API
Definition api.h:34
#define BOTAN_DEPRECATED(msg)
Definition api.h:73
#define BOTAN_FUTURE_EXPLICIT
Definition api.h:52
#define BOTAN_DEPRECATED_API(msg)
Definition api.h:27
ASN1_Object()=default
An "OtherName" GeneralName entry: type-id OID and the inner ANY value as raw BER.
Definition pkix_types.h:307
bool operator<(const OtherNameValue &other) const
Definition pkix_types.h:313
std::span< const uint8_t > value() const
Definition pkix_types.h:311
const std::set< IPv6Address > & ipv6_addresses() const
Return the set of IPv6 addresses included in this alternative name.
Definition pkix_types.h:421
const std::set< DNSName > & dns_names() const
Return the set of DNS names included in this alternative name.
Definition pkix_types.h:407
const std::set< X509_DN > & directory_names() const
Return the set of directory names included in this alternative name.
Definition pkix_types.h:441
void add_dns(std::string_view dns)
Add a DNS name to this AlternativeName, parsing and validating the input.
Definition alt_name.cpp:63
std::set< std::string > dns() const
Definition alt_name.cpp:78
void add_ipv4_address(uint32_t ipv4)
Add an IP address to this alternative name.
Definition pkix_types.h:372
void add_email(std::string_view addr)
Add an email address to this AlternativeName, parsing and validating the input.
Definition alt_name.cpp:40
const std::set< EmailAddress > & email_addresses() const
Return the set of email addresses included in this alternative name.
Definition pkix_types.h:398
const std::set< std::pair< OID, ASN1_String > > & other_names() const
Return the set of "other names" whose value was a recognized ASN1_String type.
Definition pkix_types.h:425
const std::set< SmtpUtf8Mailbox > & smtp_utf8_mailboxes() const
Definition pkix_types.h:435
void add_uri(std::string_view uri)
Add a URI to this AlternativeName, parsing and validating the input.
Definition alt_name.cpp:17
void add_registered_id(const OID &oid)
Add a registeredID (RFC 5280 [8]).
Definition alt_name.cpp:97
const std::set< OtherNameValue > & other_name_values() const
Return all "OtherName" entries with their inner ANY value as raw BER.
Definition pkix_types.h:430
void add_other_name_value(const OID &oid, std::span< const uint8_t > value)
Definition alt_name.cpp:93
void add_other_name(const OID &oid, const ASN1_String &value)
Add an "OtherName" identified by object identifier to this AlternativeName.
Definition alt_name.cpp:86
const std::set< IPv6Address > & ipv6_address() const
Return the set of IPv6 addresses included in this alternative name.
Definition pkix_types.h:413
const std::set< IPv4Address > & ipv4_addresses() const
Return the set of IPv4 addresses included in this alternative name.
Definition pkix_types.h:418
void add_dn(const X509_DN &dn)
Add a directory name to this AlternativeName.
Definition alt_name.cpp:101
const std::set< URI > & uri_names() const
Return the set of URIs included in this alternative name.
Definition pkix_types.h:389
AlternativeName()=default
Create an empty name.
std::multimap< OID, ASN1_String > get_othernames() const
const std::set< OID > & registered_ids() const
Return the set of registeredID OIDs.
Definition pkix_types.h:438
const std::vector< uint8_t > & parameters() const
Definition pkix_types.h:520
void decode_from(BER_Decoder &from) override
const OID & object_identifier() const
Definition pkix_types.h:522
const OID & oid() const
Definition pkix_types.h:518
void encode_into(DER_Encoder &to) const override
Attribute()=default
const std::vector< uint8_t > & get_parameters() const
Definition pkix_types.h:524
Definition x509_crl.h:32
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::string oid_name() const =0
virtual OID oid_of() const =0
virtual std::unique_ptr< Certificate_Extension > copy() const =0
virtual bool is_appropriate_context(Extension_Context context) const =0
virtual std::vector< uint8_t > encode_inner() const =0
virtual ~Certificate_Extension()=default
virtual void decode_inner(const std::vector< uint8_t > &)=0
const Certificate_Extension * get_extension_object(const OID &oid) const
Definition x509_ext.cpp:246
std::unique_ptr< T > get_raw(const OID &oid) const
Definition pkix_types.h:987
Extensions & operator=(const Extensions &)=default
bool has_unknown_critical_extension() const
Definition pkix_types.h:934
Extensions(const Extensions &)=default
~Extensions() override=default
size_t count() const
Extensions(Extensions &&)=default
const std::vector< OID > & get_extension_oids() const
Definition pkix_types.h:901
const T * get_extension_object_as(const OID &oid=T::static_oid()) const
Definition pkix_types.h:882
Extensions()=default
Extensions & operator=(Extensions &&)=default
X.509 GeneralName Type.
Definition pkix_types.h:541
static GeneralName email(std::string_view email)
void decode_from(BER_Decoder &from) override
GeneralName()=default
static GeneralName ipv4_address(uint32_t ipv4)
void encode_into(DER_Encoder &to) const override
static GeneralName uri(std::string_view uri)
static GeneralName _dns_san_value(std::string_view dns)
static GeneralName ipv6_address(const IPv6Address &ipv6)
friend class NameConstraints
Definition pkix_types.h:632
NameType type_code() const
Definition pkix_types.h:594
bool matches_ipv4(const IPv4Address &ip) const
Definition pkix_types.h:623
bool matches_ipv4(uint32_t ip) const
static GeneralName dns(std::string_view dns)
static GeneralName _uri_san_value(std::string_view full_uri)
static GeneralName directory_name(Botan::X509_DN dn)
A single Name Constraint.
Definition pkix_types.h:716
const GeneralName & base() const
Definition pkix_types.h:735
const std::vector< GeneralSubtree > & permitted() const
Definition pkix_types.h:766
const std::vector< GeneralSubtree > & excluded() const
Definition pkix_types.h:773
const std::vector< std::vector< std::pair< OID, ASN1_String > > > & rdns() const
Definition pkix_types.h:229
void add_attribute(const OID &oid, std::string_view val)
Definition pkix_types.h:247
void add_attribute(std::string_view key, std::string_view val)
Definition x509_dn.cpp:184
X509_DN()=default
const std::vector< uint8_t > & _canonical_bytes() const
Definition pkix_types.h:274
X509_DN(std::initializer_list< std::pair< std::string_view, std::string_view > > args)
Definition pkix_types.h:161
bool empty() const
Definition pkix_types.h:202
const std::vector< uint8_t > & get_bits() const
Definition pkix_types.h:198
size_t count() const
Definition pkix_types.h:209
size_t octet_length() const
Definition pkix_types.h:112
bool conforms_to_rfc5280() const
Definition pkix_types.h:118
std::span< const uint8_t > der_contents() const
Definition pkix_types.h:124
bool operator==(const X509_Serial_Number &other) const
Definition pkix_types.h:143
const char * name
Definition ffi_tls.h:59
ASN1_Type
Definition asn1_obj.h:47
auto operator<=>(const Strong< T, Tags... > &lhs, const Strong< T, Tags... > &rhs)
Extension_Context
Definition pkix_types.h:795
std::string to_string(ErrorType type)
Convert an ErrorType to string.
Definition exceptn.cpp:13
std::string key_constraints_to_string(Key_Constraints c)
Definition pkix_types.h:43