Botan 3.14.1
Crypto and TLS for C&
x509_dn.cpp
Go to the documentation of this file.
1/*
2* X509_DN
3* (C) 1999-2007,2018 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/pkix_types.h>
9
10#include <botan/ber_dec.h>
11#include <botan/der_enc.h>
12#include <botan/internal/charset.h>
13#include <botan/internal/loadstor.h>
14#include <botan/internal/x509_utils.h>
15#include <algorithm>
16#include <istream>
17#include <iterator>
18#include <optional>
19#include <ostream>
20#include <sstream>
21
22namespace Botan {
23
24namespace {
25
26bool is_space(char c) {
27 return c == ' ' || c == '\t';
28}
29
30std::optional<uint8_t> hex_digit_value(char c) {
31 if(c >= '0' && c <= '9') {
32 return static_cast<uint8_t>(c - '0');
33 } else if(c >= 'a' && c <= 'f') {
34 return static_cast<uint8_t>(c - 'a' + 10);
35 } else if(c >= 'A' && c <= 'F') {
36 return static_cast<uint8_t>(c - 'A' + 10);
37 } else {
38 return {};
39 }
40}
41
42/*
43* RFC 4514 Section 3 specifies which characters can be escaped
44*/
45bool is_escapable_char(char c) {
46 switch(c) {
47 case '\\':
48 case '"':
49 case '+':
50 case ',':
51 case ';':
52 case '<':
53 case '>':
54 case ' ':
55 case '#':
56 case '=':
57 return true;
58 default:
59 return false;
60 }
61}
62
63bool is_unescaped_special_value_char(char c) {
64 switch(c) {
65 case ';':
66 case '<':
67 case '>':
68 case '#':
69 case '=':
70 return true;
71 default:
72 return false;
73 }
74}
75
76/*
77* Yields the X.500 canonical form of a name component one character at a time
78*/
79class X500_Char_Iterator final {
80 public:
81 explicit X500_Char_Iterator(std::string_view s) : m_str(s), m_pos(0) {
82 // Skip leading whitespace
83 while(m_pos < m_str.size() && is_space(m_str[m_pos])) {
84 ++m_pos;
85 }
86 }
87
88 // Returns next canonical character, or nullopt when exhausted.
89 std::optional<char> next() {
90 if(m_pos >= m_str.size()) {
91 return std::nullopt;
92 }
93
94 if(is_space(m_str[m_pos])) {
95 // Skip the entire whitespace run
96 while(m_pos < m_str.size() && is_space(m_str[m_pos])) {
97 ++m_pos;
98 }
99 // Emit a single space only if more content follows (strip trailing ws)
100 if(m_pos < m_str.size()) {
101 return ' ';
102 }
103 return std::nullopt;
104 }
105
106 const char c = m_str[m_pos++];
107 // Locale-independent ASCII fold; RFC 5280 DN matching does not depend on libc locale
108 if(c >= 'A' && c <= 'Z') {
109 return static_cast<char>(c + ('a' - 'A'));
110 }
111 return c;
112 }
113
114 static std::string canonicalize(std::string_view name) {
115 std::string result;
116 result.reserve(name.size());
117
118 X500_Char_Iterator it(name);
119 while(auto c = it.next()) {
120 result += *c;
121 }
122
123 return result;
124 }
125
126 private:
127 std::string_view m_str;
128 size_t m_pos;
129};
130
131/*
132* Canonical form of an RDN's AVAs: each value is X.500-canonicalized
133* (case-fold and whitespace collapse) and the resulting (OID, value)
134* pairs are sorted, so an RDN's SET semantics reduce to vector equality.
135*/
136std::vector<std::pair<OID, std::string>> canonicalize_rdn(const std::vector<std::pair<OID, ASN1_String>>& rdn) {
137 std::vector<std::pair<OID, std::string>> result;
138 result.reserve(rdn.size());
139 for(const auto& ava : rdn) {
140 result.emplace_back(ava.first, X500_Char_Iterator::canonicalize(ava.second.value()));
141 }
142 if(result.size() != 1) {
143 std::sort(result.begin(), result.end());
144 }
145 return result;
146}
147
148/*
149* The canonical encoding of a DN is the concatenation of the encodings of
150* each RDN, so appending an RDN to a DN only requires appending its encoding.
151*/
152void append_canonical_rdn(std::vector<uint8_t>& canonical_bits, const std::vector<std::pair<OID, ASN1_String>>& rdn) {
153 const auto append_canonical_data = []<typename T>(std::vector<uint8_t>& out, const T& data) {
154 const std::array<uint8_t, 8> data_len = store_le(static_cast<uint64_t>(data.size()));
155 out.insert(out.end(), data_len.begin(), data_len.end());
156 out.insert(out.end(), data.begin(), data.end());
157 };
158
159 std::vector<uint8_t> rdn_bits;
160
161 for(const auto& [oid, value] : canonicalize_rdn(rdn)) {
162 append_canonical_data(rdn_bits, oid.BER_encode());
163 append_canonical_data(rdn_bits, value);
164 }
165
166 append_canonical_data(canonical_bits, rdn_bits);
167}
168
169std::vector<uint8_t> canonicalize_dn(const std::vector<std::vector<std::pair<OID, ASN1_String>>>& rdns) {
170 std::vector<uint8_t> canonical_bits;
171
172 for(const auto& rdn : rdns) {
173 append_canonical_rdn(canonical_bits, rdn);
174 }
175
176 return canonical_bits;
177}
178
179} // namespace
180
181/*
182* Add an attribute to a X509_DN
183*/
184void X509_DN::add_attribute(std::string_view type, std::string_view str) {
186}
187
188/*
189* Add an attribute to a X509_DN
190*/
191void X509_DN::add_attribute(const OID& oid, const ASN1_String& str) {
192 if(str.empty()) {
193 return;
194 }
195
196 // Each programmatic add appends a new single-AVA RDN.
197 add_rdn({std::make_pair(oid, str)});
198}
199
200void X509_DN::add_rdn(std::vector<std::pair<OID, ASN1_String>> rdn) {
201 if(rdn.empty()) {
202 return;
203 }
204 append_canonical_rdn(m_canonical_dn_bits, rdn);
205 m_rdn.push_back(std::move(rdn));
206 m_dn_bits.clear();
207}
208
209std::vector<std::pair<OID, ASN1_String>> X509_DN::dn_info() const {
210 std::vector<std::pair<OID, ASN1_String>> flat;
211 for(const auto& rdn : m_rdn) {
212 for(const auto& ava : rdn) {
213 flat.push_back(ava);
214 }
215 }
216 return flat;
217}
218
219/*
220* Get the attributes of this X509_DN
221*/
222std::multimap<OID, std::string> X509_DN::get_attributes() const {
223 std::multimap<OID, std::string> retval;
224
225 for(const auto& rdn : m_rdn) {
226 for(const auto& ava : rdn) {
227 retval.emplace(ava.first, ava.second.value());
228 }
229 }
230 return retval;
231}
232
233/*
234* Get the contents of this X.500 Name
235*/
236std::multimap<std::string, std::string> X509_DN::contents() const {
237 std::multimap<std::string, std::string> retval;
238
239 for(const auto& rdn : m_rdn) {
240 for(const auto& ava : rdn) {
241 retval.emplace(ava.first.to_formatted_string(), ava.second.value());
242 }
243 }
244 return retval;
245}
246
247bool X509_DN::has_field(std::string_view attr) const {
248 try {
249 const OID o = OID::from_string(deref_info_field(attr));
250 if(o.has_value()) {
251 return has_field(o);
252 }
253 } catch(Lookup_Error&) {}
254
255 return false;
256}
257
258bool X509_DN::has_field(const OID& oid) const {
259 for(const auto& rdn : m_rdn) {
260 for(const auto& ava : rdn) {
261 if(ava.first == oid) {
262 return true;
263 }
264 }
265 }
266
267 return false;
268}
269
270std::string X509_DN::get_first_attribute(std::string_view attr) const {
271 const OID oid = OID::from_string(deref_info_field(attr));
272 return get_first_attribute(oid).value();
273}
274
276 for(const auto& rdn : m_rdn) {
277 for(const auto& ava : rdn) {
278 if(ava.first == oid) {
279 return ava.second;
280 }
281 }
282 }
283
284 return ASN1_String();
285}
286
287/*
288* Get a single attribute type
289*/
290std::vector<std::string> X509_DN::get_attribute(std::string_view attr) const {
291 const OID oid = OID::from_string(deref_info_field(attr));
292
293 std::vector<std::string> values;
294
295 for(const auto& rdn : m_rdn) {
296 for(const auto& ava : rdn) {
297 if(ava.first == oid) {
298 values.push_back(ava.second.value());
299 }
300 }
301 }
302
303 return values;
304}
305
306/*
307* Deref aliases in a subject/issuer info request
308*/
309std::string X509_DN::deref_info_field(std::string_view info) {
310 if(info == "Name" || info == "CommonName" || info == "CN") {
311 return "X520.CommonName";
312 }
313 if(info == "SerialNumber" || info == "SN") {
314 return "X520.SerialNumber";
315 }
316 if(info == "Country" || info == "C") {
317 return "X520.Country";
318 }
319 if(info == "Organization" || info == "O") {
320 return "X520.Organization";
321 }
322 if(info == "Organizational Unit" || info == "OrgUnit" || info == "OU") {
323 return "X520.OrganizationalUnit";
324 }
325 if(info == "Locality" || info == "L") {
326 return "X520.Locality";
327 }
328 if(info == "State" || info == "Province" || info == "ST") {
329 return "X520.State";
330 }
331 if(info == "Email") {
332 return "RFC822";
333 }
334 return std::string(info);
335}
336
337/*
338* Compare two X509_DNs for equality
339*/
340bool operator==(const X509_DN& dn1, const X509_DN& dn2) {
341 return dn1._canonical_bytes() == dn2._canonical_bytes();
342}
343
344/*
345* Compare two X509_DNs for inequality
346*/
347bool operator!=(const X509_DN& dn1, const X509_DN& dn2) {
348 return !(dn1 == dn2);
349}
350
351/*
352* Induce an arbitrary ordering on DNs that respects RDN sequence order
353* and RDN set-equality.
354*/
355bool operator<(const X509_DN& dn1, const X509_DN& dn2) {
356 return dn1._canonical_bytes() < dn2._canonical_bytes();
357}
358
359bool x509_dn_subtree_match(const X509_DN& name, const X509_DN& constraint) {
360 const auto& name_bits = name._canonical_bytes();
361 const auto& constraint_bits = constraint._canonical_bytes();
362
363 if(constraint_bits.size() > name_bits.size()) {
364 return false;
365 }
366
367 return std::equal(constraint_bits.begin(), constraint_bits.end(), name_bits.begin());
368}
369
370std::vector<uint8_t> X509_DN::DER_encode() const {
371 std::vector<uint8_t> result;
372 DER_Encoder der(result);
373 this->encode_into(der);
374 return result;
375}
376
377/*
378* DER encode a DistinguishedName
379*/
381 der.start_sequence();
382
383 if(!m_dn_bits.empty()) {
384 /*
385 If we decoded this from somewhere, encode it back exactly as
386 we received it
387 */
388 der.raw_bytes(m_dn_bits);
389 } else {
390 for(const auto& rdn : m_rdn) {
391 der.start_set();
392 for(const auto& ava : rdn) {
393 der.start_sequence().encode(ava.first).encode(ava.second).end_cons();
394 }
395 der.end_cons();
396 }
397 }
398
399 der.end_cons();
400}
401
402/*
403* Decode a BER encoded DistinguishedName
404*/
406 std::vector<uint8_t> bits;
407
408 source.start_sequence().raw_bytes(bits).end_cons();
409
410 BER_Decoder sequence(bits, source.limits());
411
412 std::vector<std::vector<std::pair<OID, ASN1_String>>> rdns;
413
414 // Cap AVAs per RDN to bound work for downstream set-based matching.
415 // No legitimate cert has anywhere near this many AVAs in a single RDN.
416 constexpr size_t MAX_AVAS_PER_RDN = 32;
417
418 while(sequence.more_items()) {
419 BER_Decoder rdn_decoder = sequence.start_set();
420
421 std::vector<std::pair<OID, ASN1_String>> rdn;
422 while(rdn_decoder.more_items()) {
423 OID oid;
424 ASN1_String str;
425
426 rdn_decoder.start_sequence()
427 .decode(oid)
428 .decode(str) // TODO support Any
429 .end_cons();
430
431 rdn.emplace_back(std::move(oid), std::move(str));
432
433 if(rdn.size() > MAX_AVAS_PER_RDN) {
434 throw Decoding_Error("X.500 RDN has too many attribute-value assertions");
435 }
436 }
437
438 /*
439 RFC 5280 4.1.2.4:
440 RelativeDistinguishedName ::=
441 SET SIZE (1..MAX) OF AttributeTypeAndValue
442 */
443 if(rdn.empty()) {
444 throw Decoding_Error("X.500 RDN must contain at least one attribute-value assertion");
445 }
446 rdns.push_back(std::move(rdn));
447 }
448
449 auto canonical_bits = canonicalize_dn(rdns);
450
451 m_rdn = std::move(rdns);
452 m_dn_bits = std::move(bits);
453 m_canonical_dn_bits = std::move(canonical_bits);
454}
455
456namespace {
457
458std::string to_short_form(const OID& oid) {
459 std::string long_id = oid.to_formatted_string();
460
461 if(long_id == "X520.CommonName") {
462 return "CN";
463 }
464
465 if(long_id == "X520.Country") {
466 return "C";
467 }
468
469 if(long_id == "X520.Organization") {
470 return "O";
471 }
472
473 if(long_id == "X520.OrganizationalUnit") {
474 return "OU";
475 }
476
477 return long_id;
478}
479
480} // namespace
481
482std::string X509_DN::to_string() const {
483 std::ostringstream out;
484 out << *this;
485 return out.str();
486}
487
488std::ostream& operator<<(std::ostream& out, const X509_DN& dn) {
489 const auto& rdns = dn.rdns();
490
491 // Escape characters as a backslash plus two hex digits per byte
492 // See RFC 4514 Sections 2.4 and 4
493 const auto hex_escape = [](std::ostream& s, char c) {
494 const auto b = static_cast<uint8_t>(c);
495 s << '\\' << nibble_to_hex(b >> 4) << nibble_to_hex(b);
496 };
497
498 // AVAs within the same RDN are joined with '+' (per RFC 4514), so a
499 // multi-valued RDN remains distinguishable from multiple single-valued
500 // RDNs separated by ','.
501 bool first_rdn = true;
502 for(const auto& rdn : rdns) {
503 if(!first_rdn) {
504 out << ",";
505 }
506 first_rdn = false;
507
508 bool first_ava = true;
509 for(const auto& ava : rdn) {
510 if(!first_ava) {
511 out << "+";
512 }
513 first_ava = false;
514 out << to_short_form(ava.first) << "=\"";
515 const std::string_view value = ava.second.value();
516 size_t pos = 0;
517 while(pos < value.size()) {
518 const size_t start = pos;
519
520 uint32_t cp = 0;
521 try {
522 cp = next_utf8_codepoint(value, pos);
523 } catch(const Decoding_Error&) {
524 // value() should always be valid UTF-8, but escape defensively otherwise
525 hex_escape(out, value[start]);
526 pos = start + 1;
527 continue;
528 }
529
530 if(cp == '\\' || cp == '"') {
531 out << '\\' << static_cast<char>(cp);
532 } else if(is_unicode_control_char(cp)) {
533 for(size_t i = start; i < pos; ++i) {
534 hex_escape(out, value[i]);
535 }
536 } else {
537 out << value.substr(start, pos - start);
538 }
539 }
540 out << "\"";
541 }
542 }
543 return out;
544}
545
546/*
547* Parse the string representation of a distinguished name, accepting
548* the formats specified in RFC 4514 Section 3 as well as RFC 2253's
549* quoted format.
550*/
551std::optional<X509_DN> X509_DN::parse(std::string_view str) {
552 X509_DN dn;
553
554 // AVAs accumulate here; a trailing '+' keeps the next AVA in the same
555 // RDN, while a ',' (or end of input) flushes them as a single RDN.
556 std::vector<std::pair<OID, ASN1_String>> pending_rdn;
557
558 // Separator that ended the previous AVA. A ',' or '+' still pending after the
559 // loop means the input ended with a separator and no AVA to follow it.
560 char terminator = '\0';
561
562 size_t pos = 0;
563 while(pos < str.size()) {
564 // Whitespace separating an attributeType from the preceding ',' or '+'
565 // is tolerated even though RFC 4514 does not produce it.
566 while(pos < str.size() && is_space(str[pos])) {
567 ++pos;
568 }
569 if(pos == str.size()) {
570 break;
571 }
572
573 // attributeType, terminated by '='
574 const size_t type_start = pos;
575 while(pos < str.size() && str[pos] != '=' && !is_space(str[pos])) {
576 ++pos;
577 }
578 const std::string_view type = str.substr(type_start, pos - type_start);
579 if(type.empty() || pos == str.size() || str[pos] != '=') {
580 return std::nullopt;
581 }
582 ++pos; // consume '='
583
584 /*
585 attributeValue, in RFC 4514 <string> form plus the legacy quoted form.
586 value_len tracks the length up to the last significant octet: leading and
587 trailing unescaped whitespace is not significant unless it was escaped or
588 quoted, so trailing whitespace is dropped by the final resize.
589 */
590 std::string value;
591 size_t value_len = 0;
592
593 // The legacy quoted form wraps the whole value: a quote is only an opening
594 // quote at the start of the value, and nothing but trailing whitespace or a
595 // separator may follow the closing quote.
596 enum class Quote : uint8_t { None, Open, Closed };
597 Quote quote = Quote::None;
598
599 terminator = '\0';
600
601 while(pos < str.size()) {
602 const char c = str[pos];
603
604 if(c == '"') {
605 if(quote == Quote::Open) {
606 quote = Quote::Closed;
607 } else if(quote == Quote::None && value.empty()) {
608 quote = Quote::Open;
609 } else {
610 return std::nullopt; // quote in mid-value or after the closing quote
611 }
612 ++pos;
613 } else if(c == '\\') {
614 if(quote == Quote::Closed) {
615 return std::nullopt; // escape after the closing quote
616 }
617 // pair = ESC ( ESC / special / hexpair )
618 ++pos;
619 if(pos == str.size()) {
620 return std::nullopt;
621 }
622 if(const auto hi = hex_digit_value(str[pos])) {
623 const auto lo = (pos + 1 < str.size()) ? hex_digit_value(str[pos + 1]) : std::nullopt;
624 if(!lo) {
625 return std::nullopt;
626 }
627 value.push_back(static_cast<char>((*hi << 4) | *lo));
628 pos += 2;
629 } else if(is_escapable_char(str[pos])) {
630 value.push_back(str[pos]);
631 ++pos;
632 } else {
633 return std::nullopt; // not ESC / special / hexpair
634 }
635 value_len = value.size(); // an escaped octet is always significant
636 } else if((c == ',' || c == '+') && quote != Quote::Open) {
637 terminator = c;
638 ++pos;
639 break;
640 } else if(quote == Quote::Closed) {
641 if(!is_space(c)) {
642 return std::nullopt; // content after the closing quote
643 }
644 ++pos; // trailing whitespace after the closing quote is insignificant
645 } else if(quote != Quote::Open && is_unescaped_special_value_char(c)) {
646 return std::nullopt;
647 } else {
648 ++pos;
649 if(is_space(c) && quote != Quote::Open) {
650 // Keep interior whitespace only if more content follows; skip it
651 // entirely while leading (value is still empty)
652 if(!value.empty()) {
653 value.push_back(c);
654 }
655 } else {
656 value.push_back(c);
657 value_len = value.size();
658 }
659 }
660 }
661
662 if(quote == Quote::Open) {
663 return std::nullopt; // unterminated quoted value
664 }
665 value.resize(value_len); // strip trailing unescaped whitespace
666
667 try {
669 // ASN1_String rejects values (e.g. a \FF hexpair) that are not valid
670 // for any supported string encoding.
671 pending_rdn.emplace_back(std::move(oid), ASN1_String(value));
672 } catch(const Exception&) {
673 return std::nullopt; // unknown attributeType or invalid attributeValue
674 }
675
676 if(terminator != '+') {
677 dn.add_rdn(std::move(pending_rdn));
678 pending_rdn.clear();
679 }
680 }
681
682 // A trailing ',' or '+' leaves an RDN/AVA with nothing to follow it
683 if(terminator == ',' || terminator == '+') {
684 return std::nullopt;
685 }
686 return dn;
687}
688
689std::istream& operator>>(std::istream& in, X509_DN& dn) {
690 const std::istreambuf_iterator<char> begin(in);
691 const std::istreambuf_iterator<char> end;
692 const std::string contents(begin, end);
693
694 if(auto parsed = X509_DN::parse(contents)) {
695 dn = std::move(*parsed);
696 } else {
697 in.setstate(std::ios::failbit);
698 }
699 return in;
700}
701} // namespace Botan
const std::string & value() const
Definition asn1_obj.h:590
bool empty() const
Definition asn1_obj.h:600
BER_Decoder & raw_bytes(T &out_wrapped)
Definition ber_dec.h:343
BER_Decoder start_set()
Definition ber_dec.h:285
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 & end_cons()
Definition ber_dec.cpp:635
BER_Decoder start_sequence()
Definition ber_dec.h:279
DER_Encoder & start_set()
Definition der_enc.h:91
DER_Encoder & start_sequence()
Definition der_enc.h:86
DER_Encoder & raw_bytes(const uint8_t val[], size_t len)
Definition der_enc.cpp:237
DER_Encoder & end_cons()
Definition der_enc.cpp:208
DER_Encoder & encode(bool b)
Definition der_enc.cpp:313
std::string to_formatted_string() const
Definition asn1_oid.cpp:137
bool has_value() const
Definition asn1_obj.h:474
static OID from_string(std::string_view str)
Definition asn1_oid.cpp:80
const std::vector< std::vector< std::pair< OID, ASN1_String > > > & rdns() const
Definition pkix_types.h:229
void add_rdn(std::vector< std::pair< OID, ASN1_String > > rdn)
Definition x509_dn.cpp:200
static std::optional< X509_DN > parse(std::string_view str)
Definition x509_dn.cpp:551
bool has_field(const OID &oid) const
Definition x509_dn.cpp:258
std::multimap< std::string, std::string > contents() const
Definition x509_dn.cpp:236
std::vector< std::pair< OID, ASN1_String > > dn_info() const
Definition x509_dn.cpp:209
std::vector< std::string > get_attribute(std::string_view attr) const
Definition x509_dn.cpp:290
void add_attribute(std::string_view key, std::string_view val)
Definition x509_dn.cpp:184
X509_DN()=default
std::multimap< OID, std::string > get_attributes() const
Definition x509_dn.cpp:222
ASN1_String get_first_attribute(const OID &oid) const
Definition x509_dn.cpp:275
void encode_into(DER_Encoder &to) const override
Definition x509_dn.cpp:380
std::vector< uint8_t > DER_encode() const
Definition x509_dn.cpp:370
std::string to_string() const
Definition x509_dn.cpp:482
const std::vector< uint8_t > & _canonical_bytes() const
Definition pkix_types.h:274
void decode_from(BER_Decoder &from) override
Definition x509_dn.cpp:405
static std::string deref_info_field(std::string_view key)
Definition x509_dn.cpp:309
const char * name
Definition ffi_tls.h:59
constexpr char nibble_to_hex(uint8_t b)
Definition charset.h:76
bool is_unicode_control_char(uint32_t cp)
Definition charset.cpp:203
bool operator<(const OID &a, const OID &b)
Definition asn1_oid.cpp:175
std::ostream & operator<<(std::ostream &out, const OID &oid)
Definition asn1_oid.cpp:308
constexpr auto store_le(ParamTs &&... params)
Definition loadstor.h:736
bool x509_dn_subtree_match(const X509_DN &name, const X509_DN &constraint)
Definition x509_dn.cpp:359
int operator>>(int fd, Pipe &pipe)
Definition fd_unix.cpp:43
bool operator!=(const AlgorithmIdentifier &x, const AlgorithmIdentifier &y)
Definition alg_id.cpp:58
uint32_t next_utf8_codepoint(std::string_view utf8, size_t &pos)
Definition charset.cpp:53
bool operator==(const AlgorithmIdentifier &x, const AlgorithmIdentifier &y)
Definition alg_id.cpp:54