Botan  1.11.26
x509cert.cpp
Go to the documentation of this file.
1 /*
2 * X.509 Certificates
3 * (C) 1999-2010,2015 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #include <botan/x509cert.h>
9 #include <botan/x509_ext.h>
10 #include <botan/der_enc.h>
11 #include <botan/ber_dec.h>
12 #include <botan/internal/stl_util.h>
13 #include <botan/parsing.h>
14 #include <botan/bigint.h>
15 #include <botan/oids.h>
16 #include <botan/pem.h>
17 #include <botan/hash.h>
18 #include <botan/hex.h>
19 #include <algorithm>
20 #include <iterator>
21 #include <sstream>
22 
23 namespace Botan {
24 
25 namespace {
26 
27 /*
28 * Lookup each OID in the vector
29 */
30 std::vector<std::string> lookup_oids(const std::vector<std::string>& in)
31  {
32  std::vector<std::string> out;
33 
34  for(auto i = in.begin(); i != in.end(); ++i)
35  out.push_back(OIDS::lookup(OID(*i)));
36  return out;
37  }
38 
39 }
40 
41 /*
42 * X509_Certificate Constructor
43 */
44 X509_Certificate::X509_Certificate(DataSource& in) :
45  X509_Object(in, "CERTIFICATE/X509 CERTIFICATE")
46  {
47  m_self_signed = false;
48  do_decode();
49  }
50 
51 /*
52 * X509_Certificate Constructor
53 */
54 X509_Certificate::X509_Certificate(const std::string& in) :
55  X509_Object(in, "CERTIFICATE/X509 CERTIFICATE")
56  {
57  m_self_signed = false;
58  do_decode();
59  }
60 
61 /*
62 * X509_Certificate Constructor
63 */
64 X509_Certificate::X509_Certificate(const std::vector<byte>& in) :
65  X509_Object(in, "CERTIFICATE/X509 CERTIFICATE")
66  {
67  m_self_signed = false;
68  do_decode();
69  }
70 
71 /*
72 * Decode the TBSCertificate data
73 */
74 void X509_Certificate::force_decode()
75  {
76  size_t version;
77  BigInt serial_bn;
78  AlgorithmIdentifier sig_algo_inner;
79  X509_DN dn_issuer, dn_subject;
80  X509_Time start, end;
81 
82  BER_Decoder tbs_cert(m_tbs_bits);
83 
84  tbs_cert.decode_optional(version, ASN1_Tag(0),
86  .decode(serial_bn)
87  .decode(sig_algo_inner)
88  .decode(dn_issuer)
90  .decode(start)
91  .decode(end)
92  .verify_end()
93  .end_cons()
94  .decode(dn_subject);
95 
96  if(version > 2)
97  throw Decoding_Error("Unknown X.509 cert version " + std::to_string(version));
98  if(m_sig_algo != sig_algo_inner)
99  throw Decoding_Error("Algorithm identifier mismatch");
100 
101  m_self_signed = (dn_subject == dn_issuer);
102 
103  m_subject.add(dn_subject.contents());
104  m_issuer.add(dn_issuer.contents());
105 
106  m_subject.add("X509.Certificate.dn_bits", ASN1::put_in_sequence(dn_subject.get_bits()));
107  m_issuer.add("X509.Certificate.dn_bits", ASN1::put_in_sequence(dn_issuer.get_bits()));
108 
109  BER_Object public_key = tbs_cert.get_next_object();
110  if(public_key.type_tag != SEQUENCE || public_key.class_tag != CONSTRUCTED)
111  throw BER_Bad_Tag("X509_Certificate: Unexpected tag for public key",
112  public_key.type_tag, public_key.class_tag);
113 
114  std::vector<byte> v2_issuer_key_id, v2_subject_key_id;
115 
116  tbs_cert.decode_optional_string(v2_issuer_key_id, BIT_STRING, 1);
117  tbs_cert.decode_optional_string(v2_subject_key_id, BIT_STRING, 2);
118 
119  BER_Object v3_exts_data = tbs_cert.get_next_object();
120  if(v3_exts_data.type_tag == 3 &&
121  v3_exts_data.class_tag == ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))
122  {
123  Extensions extensions;
124 
125  BER_Decoder(v3_exts_data.value).decode(extensions).verify_end();
126 
127  extensions.contents_to(m_subject, m_issuer);
128  }
129  else if(v3_exts_data.type_tag != NO_OBJECT)
130  throw BER_Bad_Tag("Unknown tag in X.509 cert",
131  v3_exts_data.type_tag, v3_exts_data.class_tag);
132 
133  if(tbs_cert.more_items())
134  throw Decoding_Error("TBSCertificate has more items that expected");
135 
136  m_subject.add("X509.Certificate.version", version);
137  m_subject.add("X509.Certificate.serial", BigInt::encode(serial_bn));
138  m_subject.add("X509.Certificate.start", start.to_string());
139  m_subject.add("X509.Certificate.end", end.to_string());
140 
141  m_issuer.add("X509.Certificate.v2.key_id", v2_issuer_key_id);
142  m_subject.add("X509.Certificate.v2.key_id", v2_subject_key_id);
143 
144  m_subject.add("X509.Certificate.public_key",
145  hex_encode(public_key.value));
146 
147  if(m_self_signed && version == 0)
148  {
149  m_subject.add("X509v3.BasicConstraints.is_ca", 1);
150  m_subject.add("X509v3.BasicConstraints.path_constraint", Cert_Extension::NO_CERT_PATH_LIMIT);
151  }
152 
153  if(is_CA_cert() &&
154  !m_subject.has_value("X509v3.BasicConstraints.path_constraint"))
155  {
156  const size_t limit = (x509_version() < 3) ?
157  Cert_Extension::NO_CERT_PATH_LIMIT : 0;
158 
159  m_subject.add("X509v3.BasicConstraints.path_constraint", limit);
160  }
161  }
162 
163 /*
164 * Return the X.509 version in use
165 */
167  {
168  return (m_subject.get1_u32bit("X509.Certificate.version") + 1);
169  }
170 
171 /*
172 * Return the time this cert becomes valid
173 */
174 std::string X509_Certificate::start_time() const
175  {
176  return m_subject.get1("X509.Certificate.start");
177  }
178 
179 /*
180 * Return the time this cert becomes invalid
181 */
182 std::string X509_Certificate::end_time() const
183  {
184  return m_subject.get1("X509.Certificate.end");
185  }
186 
187 /*
188 * Return information about the subject
189 */
190 std::vector<std::string>
191 X509_Certificate::subject_info(const std::string& what) const
192  {
193  return m_subject.get(X509_DN::deref_info_field(what));
194  }
195 
196 /*
197 * Return information about the issuer
198 */
199 std::vector<std::string>
200 X509_Certificate::issuer_info(const std::string& what) const
201  {
202  return m_issuer.get(X509_DN::deref_info_field(what));
203  }
204 
205 /*
206 * Return the public key in this certificate
207 */
209  {
210  return X509::load_key(
212  }
213 
215  {
216  return hex_decode(m_subject.get1("X509.Certificate.public_key"));
217  }
218 
219 /*
220 * Check if the certificate is for a CA
221 */
223  {
224  if(!m_subject.get1_u32bit("X509v3.BasicConstraints.is_ca"))
225  return false;
226 
228  }
229 
231  {
232  if(constraints() == NO_CONSTRAINTS)
233  return true;
234  return ((constraints() & usage) != 0);
235  }
236 
237 bool X509_Certificate::allowed_usage(const std::string& usage) const
238  {
239  const std::vector<std::string> ex = ex_constraints();
240 
241  if(ex.empty())
242  return true;
243 
244  if(std::find(ex.begin(), ex.end(), usage) != ex.end())
245  return true;
246 
247  return false;
248  }
249 
251  {
252  switch(usage)
253  {
255  return true;
256 
259 
262 
265 
267  return is_CA_cert();
268  }
269 
270  return false;
271  }
272 
273 /*
274 * Return the path length constraint
275 */
277  {
278  return m_subject.get1_u32bit("X509v3.BasicConstraints.path_constraint", 0);
279  }
280 
281 /*
282 * Return the key usage constraints
283 */
285  {
286  return Key_Constraints(m_subject.get1_u32bit("X509v3.KeyUsage",
287  NO_CONSTRAINTS));
288  }
289 
290 /*
291 * Return the list of extended key usage OIDs
292 */
293 std::vector<std::string> X509_Certificate::ex_constraints() const
294  {
295  return lookup_oids(m_subject.get("X509v3.ExtendedKeyUsage"));
296  }
297 
298 /*
299 * Return the list of certificate policies
300 */
301 std::vector<std::string> X509_Certificate::policies() const
302  {
303  return lookup_oids(m_subject.get("X509v3.CertificatePolicies"));
304  }
305 
307  {
308  return m_subject.get1("OCSP.responder", "");
309  }
310 
312  {
313  return m_subject.get1("CRL.DistributionPoint", "");
314  }
315 
316 /*
317 * Return the authority key id
318 */
319 std::vector<byte> X509_Certificate::authority_key_id() const
320  {
321  return m_issuer.get1_memvec("X509v3.AuthorityKeyIdentifier");
322  }
323 
324 /*
325 * Return the subject key id
326 */
327 std::vector<byte> X509_Certificate::subject_key_id() const
328  {
329  return m_subject.get1_memvec("X509v3.SubjectKeyIdentifier");
330  }
331 
332 /*
333 * Return the certificate serial number
334 */
335 std::vector<byte> X509_Certificate::serial_number() const
336  {
337  return m_subject.get1_memvec("X509.Certificate.serial");
338  }
339 
341  {
342  return create_dn(m_issuer);
343  }
344 
345 std::vector<byte> X509_Certificate::raw_issuer_dn() const
346  {
347  return m_issuer.get1_memvec("X509.Certificate.dn_bits");
348  }
349 
351  {
352  return create_dn(m_subject);
353  }
354 
355 std::vector<byte> X509_Certificate::raw_subject_dn() const
356  {
357  return m_subject.get1_memvec("X509.Certificate.dn_bits");
358  }
359 
360 std::string X509_Certificate::fingerprint(const std::string& hash_name) const
361  {
362  std::unique_ptr<HashFunction> hash(HashFunction::create(hash_name));
363  hash->update(this->BER_encode());
364  const auto hex_print = hex_encode(hash->final());
365 
366  std::string formatted_print;
367 
368  for(size_t i = 0; i != hex_print.size(); i += 2)
369  {
370  formatted_print.push_back(hex_print[i]);
371  formatted_print.push_back(hex_print[i+1]);
372 
373  if(i != hex_print.size() - 2)
374  formatted_print.push_back(':');
375  }
376 
377  return formatted_print;
378  }
379 
380 bool X509_Certificate::matches_dns_name(const std::string& name) const
381  {
382  if(name.empty())
383  return false;
384 
385  std::vector<std::string> issued_names = subject_info("DNS");
386 
387  // Fall back to CN only if no DNS names are set (RFC 6125 sec 6.4.4)
388  if(issued_names.empty())
389  issued_names = subject_info("Name");
390 
391  for(size_t i = 0; i != issued_names.size(); ++i)
392  {
393  if(host_wildcard_match(issued_names[i], name))
394  return true;
395  }
396 
397  return false;
398  }
399 
400 /*
401 * Compare two certificates for equality
402 */
404  {
405  return (m_sig == other.m_sig &&
406  m_sig_algo == other.m_sig_algo &&
407  m_self_signed == other.m_self_signed &&
408  m_issuer == other.m_issuer &&
409  m_subject == other.m_subject);
410  }
411 
413  {
414  /* If signature values are not equal, sort by lexicographic ordering of that */
415  if(m_sig != other.m_sig)
416  {
417  if(m_sig < other.m_sig)
418  return true;
419  return false;
420  }
421 
422  // Then compare the signed contents
423  return m_tbs_bits < other.m_tbs_bits;
424  }
425 
426 /*
427 * X.509 Certificate Comparison
428 */
429 bool operator!=(const X509_Certificate& cert1, const X509_Certificate& cert2)
430  {
431  return !(cert1 == cert2);
432  }
433 
434 std::string X509_Certificate::to_string() const
435  {
436  const std::vector<std::string> dn_fields{
437  "Name",
438  "Email",
439  "Organization",
440  "Organizational Unit",
441  "Locality",
442  "State",
443  "Country",
444  "IP",
445  "DNS",
446  "URI",
447  "PKIX.XMPPAddr"
448  };
449 
450  std::ostringstream out;
451 
452  for(auto&& field : dn_fields)
453  {
454  for(auto&& val : subject_info(field))
455  {
456  out << "Subject " << field << ": " << val << "\n";
457  }
458  }
459 
460  for(auto&& field : dn_fields)
461  {
462  for(auto&& val : issuer_info(field))
463  {
464  out << "Issuer " << field << ": " << val << "\n";
465  }
466  }
467 
468  out << "Version: " << this->x509_version() << "\n";
469 
470  out << "Not valid before: " << this->start_time() << "\n";
471  out << "Not valid after: " << this->end_time() << "\n";
472 
473  out << "Constraints:\n";
475  if(constraints == NO_CONSTRAINTS)
476  out << " None\n";
477  else
478  {
479  if(constraints & DIGITAL_SIGNATURE)
480  out << " Digital Signature\n";
481  if(constraints & NON_REPUDIATION)
482  out << " Non-Repuidation\n";
483  if(constraints & KEY_ENCIPHERMENT)
484  out << " Key Encipherment\n";
485  if(constraints & DATA_ENCIPHERMENT)
486  out << " Data Encipherment\n";
487  if(constraints & KEY_AGREEMENT)
488  out << " Key Agreement\n";
489  if(constraints & KEY_CERT_SIGN)
490  out << " Cert Sign\n";
491  if(constraints & CRL_SIGN)
492  out << " CRL Sign\n";
493  }
494 
495  std::vector<std::string> policies = this->policies();
496  if(!policies.empty())
497  {
498  out << "Policies: " << "\n";
499  for(size_t i = 0; i != policies.size(); i++)
500  out << " " << policies[i] << "\n";
501  }
502 
503  std::vector<std::string> ex_constraints = this->ex_constraints();
504  if(!ex_constraints.empty())
505  {
506  out << "Extended Constraints:\n";
507  for(size_t i = 0; i != ex_constraints.size(); i++)
508  out << " " << ex_constraints[i] << "\n";
509  }
510 
511  if(!ocsp_responder().empty())
512  out << "OCSP responder " << ocsp_responder() << "\n";
513  if(!crl_distribution_point().empty())
514  out << "CRL " << crl_distribution_point() << "\n";
515 
516  out << "Signature algorithm: " <<
517  OIDS::lookup(this->signature_algorithm().oid) << "\n";
518 
519  out << "Serial number: " << hex_encode(this->serial_number()) << "\n";
520 
521  if(this->authority_key_id().size())
522  out << "Authority keyid: " << hex_encode(this->authority_key_id()) << "\n";
523 
524  if(this->subject_key_id().size())
525  out << "Subject keyid: " << hex_encode(this->subject_key_id()) << "\n";
526 
527  std::unique_ptr<X509_PublicKey> pubkey(this->subject_public_key());
528  out << "Public Key:\n" << X509::PEM_encode(*pubkey);
529 
530  return out.str();
531  }
532 
533 /*
534 * Create and populate a X509_DN
535 */
537  {
538  auto names = info.search_for(
539  [](const std::string& key, const std::string&)
540  {
541  return (key.find("X520.") != std::string::npos);
542  });
543 
544  X509_DN dn;
545 
546  for(auto i = names.begin(); i != names.end(); ++i)
547  dn.add_attribute(i->first, i->second);
548 
549  return dn;
550  }
551 
552 /*
553 * Create and populate an AlternativeName
554 */
556  {
557  auto names = info.search_for(
558  [](const std::string& key, const std::string&)
559  {
560  return (key == "RFC822" ||
561  key == "DNS" ||
562  key == "URI" ||
563  key == "IP");
564  });
565 
566  AlternativeName alt_name;
567 
568  for(auto i = names.begin(); i != names.end(); ++i)
569  alt_name.add_attribute(i->first, i->second);
570 
571  return alt_name;
572  }
573 
574 }
AlgorithmIdentifier m_sig_algo
Definition: x509_obj.h:96
void add_attribute(const std::string &, const std::string &)
std::vector< byte > get_bits() const
Definition: x509_dn.cpp:110
friend class BER_Decoder
Definition: x509cert.h:237
bool operator==(const X509_Certificate &other) const
Definition: x509cert.cpp:403
static std::vector< byte > encode(const BigInt &n, Base base=Binary)
Definition: big_code.cpp:54
size_t hex_decode(byte output[], const char input[], size_t input_length, size_t &input_consumed, bool ignore_ws)
Definition: hex.cpp:49
std::multimap< std::string, std::string > search_for(std::function< bool(std::string, std::string)> predicate) const
Definition: datastor.cpp:35
bool operator!=(const AlgorithmIdentifier &a1, const AlgorithmIdentifier &a2)
Definition: alg_id.cpp:92
bool matches_dns_name(const std::string &name) const
Definition: x509cert.cpp:380
Public_Key * load_key(DataSource &source)
Definition: x509_key.cpp:41
bool is_CA_cert() const
Definition: x509cert.cpp:222
std::string ocsp_responder() const
Definition: x509cert.cpp:306
Key_Constraints constraints() const
Definition: x509cert.cpp:284
BER_Decoder & decode(bool &v)
Definition: ber_dec.cpp:373
void add_attribute(const std::string &, const std::string &)
Definition: x509_dn.cpp:46
std::uint32_t u32bit
Definition: types.h:33
std::string to_string(const BER_Object &obj)
Definition: asn1_obj.cpp:47
bool allowed_usage(Key_Constraints usage) const
Definition: x509cert.cpp:230
std::string crl_distribution_point() const
Definition: x509cert.cpp:311
void contents_to(Data_Store &, Data_Store &) const
Definition: x509_ext.cpp:159
std::vector< byte > raw_subject_dn() const
Definition: x509cert.cpp:355
secure_vector< byte > value
Definition: asn1_obj.h:91
std::string get1(const std::string &key) const
Definition: datastor.cpp:62
u32bit path_limit() const
Definition: x509cert.cpp:276
std::vector< byte > serial_number() const
Definition: x509cert.cpp:335
BER_Decoder & decode_optional(T &out, ASN1_Tag type_tag, ASN1_Tag class_tag, const T &default_value=T())
Definition: ber_dec.h:181
BER_Decoder & end_cons()
Definition: ber_dec.cpp:269
X509_DN create_dn(const Data_Store &info)
Definition: x509cert.cpp:536
bool more_items() const
Definition: ber_dec.cpp:155
std::string end_time() const
Definition: x509cert.cpp:182
AlternativeName create_alt_name(const Data_Store &info)
Definition: x509cert.cpp:555
std::vector< byte > get1_memvec(const std::string &) const
Definition: datastor.cpp:92
std::string to_string() const
Definition: x509cert.cpp:434
std::vector< byte > BER_encode() const
Definition: x509_obj.cpp:113
std::string lookup(const OID &oid)
Definition: oids.cpp:155
ASN1_Tag
Definition: asn1_obj.h:22
std::string fingerprint(const std::string &="SHA-1") const
Definition: x509cert.cpp:360
std::vector< byte > subject_public_key_bits() const
Definition: x509cert.cpp:214
std::vector< byte > m_tbs_bits
Definition: x509_obj.h:97
static std::unique_ptr< HashFunction > create(const std::string &algo_spec, const std::string &provider="")
Definition: hash.cpp:98
std::vector< byte > m_sig
Definition: x509_obj.h:97
std::string start_time() const
Definition: x509cert.cpp:174
BER_Decoder start_cons(ASN1_Tag type_tag, ASN1_Tag class_tag=UNIVERSAL)
Definition: ber_dec.cpp:255
std::string PEM_encode(const Public_Key &key)
Definition: x509_key.cpp:32
Definition: alg_id.cpp:13
bool operator<(const X509_Certificate &other) const
Definition: x509cert.cpp:412
std::vector< byte > raw_issuer_dn() const
Definition: x509cert.cpp:345
std::vector< byte > subject_key_id() const
Definition: x509cert.cpp:327
std::vector< std::string > policies() const
Definition: x509cert.cpp:301
BER_Object get_next_object()
Definition: ber_dec.cpp:207
std::string to_string() const
Return an internal string representation of the time.
Definition: asn1_time.cpp:60
ASN1_Tag class_tag
Definition: asn1_obj.h:88
u32bit get1_u32bit(const std::string &, u32bit=0) const
Definition: datastor.cpp:109
bool has_value(const std::string &) const
Definition: datastor.cpp:27
ASN1_Tag type_tag
Definition: asn1_obj.h:88
BER_Decoder & verify_end()
Definition: ber_dec.cpp:165
X509_DN issuer_dn() const
Definition: x509cert.cpp:340
std::vector< std::string > subject_info(const std::string &name) const
Definition: x509cert.cpp:191
std::vector< std::string > ex_constraints() const
Definition: x509cert.cpp:293
static std::string deref_info_field(const std::string &)
Definition: x509_dn.cpp:118
std::vector< std::string > issuer_info(const std::string &name) const
Definition: x509cert.cpp:200
std::vector< byte > authority_key_id() const
Definition: x509cert.cpp:319
BER_Decoder & decode_optional_string(std::vector< byte, Alloc > &out, ASN1_Tag real_type, u16bit type_no, ASN1_Tag class_tag=CONTEXT_SPECIFIC)
Definition: ber_dec.h:130
Public_Key * subject_public_key() const
Definition: x509cert.cpp:208
std::multimap< std::string, std::string > contents() const
Definition: x509_dn.cpp:84
bool host_wildcard_match(const std::string &issued, const std::string &host)
Definition: parsing.cpp:335
X509_DN subject_dn() const
Definition: x509cert.cpp:350
u32bit x509_version() const
Definition: x509cert.cpp:166
std::vector< byte > put_in_sequence(const std::vector< byte > &contents)
Definition: asn1_obj.cpp:35
std::vector< std::string > get(const std::string &) const
Definition: datastor.cpp:50
AlgorithmIdentifier signature_algorithm() const
Definition: x509_obj.cpp:147
Usage_Type
Definition: x509cert.h:21
void add(const std::multimap< std::string, std::string > &)
Definition: datastor.cpp:155
OID oid
Definition: x509_ext.cpp:448
void hex_encode(char output[], const byte input[], size_t input_length, bool uppercase)
Definition: hex.cpp:14