1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/cert/x509_certificate.h"
6 
7 #include <limits.h>
8 #include <stdlib.h>
9 
10 #include <memory>
11 #include <string>
12 #include <vector>
13 
14 #include "base/base64.h"
15 #include "base/logging.h"
16 #include "base/macros.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/pickle.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_piece.h"
21 #include "base/strings/string_util.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "build/build_config.h"
25 #include "crypto/openssl_util.h"
26 #include "net/base/ip_address.h"
27 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
28 #include "net/base/url_util.h"
29 #include "net/cert/asn1_util.h"
30 #include "net/cert/internal/cert_errors.h"
31 #include "net/cert/internal/name_constraints.h"
32 #include "net/cert/internal/parsed_certificate.h"
33 #include "net/cert/internal/signature_algorithm.h"
34 #include "net/cert/internal/verify_name_match.h"
35 #include "net/cert/internal/verify_signed_data.h"
36 #include "net/cert/pem.h"
37 #include "net/cert/x509_util.h"
38 #include "net/der/encode_values.h"
39 #include "net/der/parser.h"
40 #include "net/dns/dns_util.h"
41 #include "third_party/boringssl/src/include/openssl/evp.h"
42 #include "third_party/boringssl/src/include/openssl/pkcs7.h"
43 #include "third_party/boringssl/src/include/openssl/pool.h"
44 #include "third_party/boringssl/src/include/openssl/sha.h"
45 #include "url/url_canon.h"
46 
47 namespace net {
48 
49 namespace {
50 
51 // Indicates the order to use when trying to decode binary data, which is
52 // based on (speculation) as to what will be most common -> least common
53 const X509Certificate::Format kFormatDecodePriority[] = {
54   X509Certificate::FORMAT_SINGLE_CERTIFICATE,
55   X509Certificate::FORMAT_PKCS7
56 };
57 
58 // The PEM block header used for DER certificates
59 const char kCertificateHeader[] = "CERTIFICATE";
60 // The PEM block header used for PKCS#7 data
61 const char kPKCS7Header[] = "PKCS7";
62 
63 // Utility to split |src| on the first occurrence of |c|, if any. |right| will
64 // either be empty if |c| was not found, or will contain the remainder of the
65 // string including the split character itself.
SplitOnChar(const base::StringPiece & src,char c,base::StringPiece * left,base::StringPiece * right)66 void SplitOnChar(const base::StringPiece& src,
67                  char c,
68                  base::StringPiece* left,
69                  base::StringPiece* right) {
70   size_t pos = src.find(c);
71   if (pos == base::StringPiece::npos) {
72     *left = src;
73     *right = base::StringPiece();
74   } else {
75     *left = src.substr(0, pos);
76     *right = src.substr(pos);
77   }
78 }
79 
80 // Sets |value| to the Value from a DER Sequence Tag-Length-Value and return
81 // true, or return false if the TLV was not a valid DER Sequence.
ParseSequenceValue(const der::Input & tlv,der::Input * value)82 WARN_UNUSED_RESULT bool ParseSequenceValue(const der::Input& tlv,
83                                            der::Input* value) {
84   der::Parser parser(tlv);
85   return parser.ReadTag(der::kSequence, value) && !parser.HasMore();
86 }
87 
88 // Normalize |cert|'s Issuer and store it in |out_normalized_issuer|, returning
89 // true on success or false if there was a parsing error.
GetNormalizedCertIssuer(CRYPTO_BUFFER * cert,std::string * out_normalized_issuer)90 bool GetNormalizedCertIssuer(CRYPTO_BUFFER* cert,
91                              std::string* out_normalized_issuer) {
92   der::Input tbs_certificate_tlv;
93   der::Input signature_algorithm_tlv;
94   der::BitString signature_value;
95   if (!ParseCertificate(
96           der::Input(CRYPTO_BUFFER_data(cert), CRYPTO_BUFFER_len(cert)),
97           &tbs_certificate_tlv, &signature_algorithm_tlv, &signature_value,
98           nullptr)) {
99     return false;
100   }
101   ParsedTbsCertificate tbs;
102   if (!ParseTbsCertificate(tbs_certificate_tlv,
103                            x509_util::DefaultParseCertificateOptions(), &tbs,
104                            nullptr))
105     return false;
106 
107   der::Input issuer_value;
108   if (!ParseSequenceValue(tbs.issuer_tlv, &issuer_value))
109     return false;
110 
111   CertErrors errors;
112   return NormalizeName(issuer_value, out_normalized_issuer, &errors);
113 }
114 
115 // Parses certificates from a PKCS#7 SignedData structure, appending them to
116 // |handles|.
CreateCertBuffersFromPKCS7Bytes(const char * data,size_t length,std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> * handles)117 void CreateCertBuffersFromPKCS7Bytes(
118     const char* data,
119     size_t length,
120     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>* handles) {
121   crypto::EnsureOpenSSLInit();
122   crypto::OpenSSLErrStackTracer err_cleaner(FROM_HERE);
123 
124   CBS der_data;
125   CBS_init(&der_data, reinterpret_cast<const uint8_t*>(data), length);
126   STACK_OF(CRYPTO_BUFFER)* certs = sk_CRYPTO_BUFFER_new_null();
127 
128   if (PKCS7_get_raw_certificates(certs, &der_data,
129                                  x509_util::GetBufferPool())) {
130     for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(certs); ++i) {
131       handles->push_back(
132           bssl::UniquePtr<CRYPTO_BUFFER>(sk_CRYPTO_BUFFER_value(certs, i)));
133     }
134   }
135   // |handles| took ownership of the individual buffers, so only free the list
136   // itself.
137   sk_CRYPTO_BUFFER_free(certs);
138 }
139 
140 }  // namespace
141 
142 // static
CreateFromBuffer(bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates)143 scoped_refptr<X509Certificate> X509Certificate::CreateFromBuffer(
144     bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
145     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates) {
146   DCHECK(cert_buffer);
147   scoped_refptr<X509Certificate> cert(
148       new X509Certificate(std::move(cert_buffer), std::move(intermediates)));
149   if (!cert->cert_buffer())
150     return nullptr;  // Initialize() failed.
151   return cert;
152 }
153 
154 // static
CreateFromBufferUnsafeOptions(bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,UnsafeCreateOptions options)155 scoped_refptr<X509Certificate> X509Certificate::CreateFromBufferUnsafeOptions(
156     bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
157     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,
158     UnsafeCreateOptions options) {
159   DCHECK(cert_buffer);
160   scoped_refptr<X509Certificate> cert(new X509Certificate(
161       std::move(cert_buffer), std::move(intermediates), options));
162   if (!cert->cert_buffer())
163     return nullptr;  // Initialize() failed.
164   return cert;
165 }
166 
167 // static
CreateFromDERCertChain(const std::vector<base::StringPiece> & der_certs)168 scoped_refptr<X509Certificate> X509Certificate::CreateFromDERCertChain(
169     const std::vector<base::StringPiece>& der_certs) {
170   return CreateFromDERCertChainUnsafeOptions(der_certs, {});
171 }
172 
173 // static
174 scoped_refptr<X509Certificate>
CreateFromDERCertChainUnsafeOptions(const std::vector<base::StringPiece> & der_certs,UnsafeCreateOptions options)175 X509Certificate::CreateFromDERCertChainUnsafeOptions(
176     const std::vector<base::StringPiece>& der_certs,
177     UnsafeCreateOptions options) {
178   TRACE_EVENT0("io", "X509Certificate::CreateFromDERCertChain");
179   if (der_certs.empty())
180     return nullptr;
181 
182   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediate_ca_certs;
183   intermediate_ca_certs.reserve(der_certs.size() - 1);
184   for (size_t i = 1; i < der_certs.size(); i++) {
185     bssl::UniquePtr<CRYPTO_BUFFER> handle = CreateCertBufferFromBytes(
186         const_cast<char*>(der_certs[i].data()), der_certs[i].size());
187     if (!handle)
188       break;
189     intermediate_ca_certs.push_back(std::move(handle));
190   }
191 
192   // Return NULL if we failed to parse any of the certs.
193   if (der_certs.size() - 1 != intermediate_ca_certs.size())
194     return nullptr;
195 
196   bssl::UniquePtr<CRYPTO_BUFFER> handle = CreateCertBufferFromBytes(
197       const_cast<char*>(der_certs[0].data()), der_certs[0].size());
198   if (!handle)
199     return nullptr;
200 
201   return CreateFromBufferUnsafeOptions(
202       std::move(handle), std::move(intermediate_ca_certs), options);
203 }
204 
205 // static
CreateFromBytes(const char * data,size_t length)206 scoped_refptr<X509Certificate> X509Certificate::CreateFromBytes(
207     const char* data,
208     size_t length) {
209   return CreateFromBytesUnsafeOptions(data, length, {});
210 }
211 
212 // static
CreateFromBytesUnsafeOptions(const char * data,size_t length,UnsafeCreateOptions options)213 scoped_refptr<X509Certificate> X509Certificate::CreateFromBytesUnsafeOptions(
214     const char* data,
215     size_t length,
216     UnsafeCreateOptions options) {
217   bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer =
218       CreateCertBufferFromBytes(data, length);
219   if (!cert_buffer)
220     return nullptr;
221 
222   scoped_refptr<X509Certificate> cert =
223       CreateFromBufferUnsafeOptions(std::move(cert_buffer), {}, options);
224   return cert;
225 }
226 
227 // static
CreateFromPickle(base::PickleIterator * pickle_iter)228 scoped_refptr<X509Certificate> X509Certificate::CreateFromPickle(
229     base::PickleIterator* pickle_iter) {
230   return CreateFromPickleUnsafeOptions(pickle_iter, {});
231 }
232 
233 // static
CreateFromPickleUnsafeOptions(base::PickleIterator * pickle_iter,UnsafeCreateOptions options)234 scoped_refptr<X509Certificate> X509Certificate::CreateFromPickleUnsafeOptions(
235     base::PickleIterator* pickle_iter,
236     UnsafeCreateOptions options) {
237   int chain_length = 0;
238   if (!pickle_iter->ReadLength(&chain_length))
239     return nullptr;
240 
241   std::vector<base::StringPiece> cert_chain;
242   const char* data = nullptr;
243   int data_length = 0;
244   for (int i = 0; i < chain_length; ++i) {
245     if (!pickle_iter->ReadData(&data, &data_length))
246       return nullptr;
247     cert_chain.push_back(base::StringPiece(data, data_length));
248   }
249   return CreateFromDERCertChainUnsafeOptions(cert_chain, options);
250 }
251 
252 // static
CreateCertificateListFromBytes(const char * data,size_t length,int format)253 CertificateList X509Certificate::CreateCertificateListFromBytes(
254     const char* data,
255     size_t length,
256     int format) {
257   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> certificates;
258 
259   // Check to see if it is in a PEM-encoded form. This check is performed
260   // first, as both OS X and NSS will both try to convert if they detect
261   // PEM encoding, except they don't do it consistently between the two.
262   base::StringPiece data_string(data, length);
263   std::vector<std::string> pem_headers;
264 
265   // To maintain compatibility with NSS/Firefox, CERTIFICATE is a universally
266   // valid PEM block header for any format.
267   pem_headers.push_back(kCertificateHeader);
268   if (format & FORMAT_PKCS7)
269     pem_headers.push_back(kPKCS7Header);
270 
271   PEMTokenizer pem_tokenizer(data_string, pem_headers);
272   while (pem_tokenizer.GetNext()) {
273     std::string decoded(pem_tokenizer.data());
274 
275     bssl::UniquePtr<CRYPTO_BUFFER> handle;
276     if (format & FORMAT_PEM_CERT_SEQUENCE)
277       handle = CreateCertBufferFromBytes(decoded.c_str(), decoded.size());
278     if (handle) {
279       // Parsed a DER encoded certificate. All PEM blocks that follow must
280       // also be DER encoded certificates wrapped inside of PEM blocks.
281       format = FORMAT_PEM_CERT_SEQUENCE;
282       certificates.push_back(std::move(handle));
283       continue;
284     }
285 
286     // If the first block failed to parse as a DER certificate, and
287     // formats other than PEM are acceptable, check to see if the decoded
288     // data is one of the accepted formats.
289     if (format & ~FORMAT_PEM_CERT_SEQUENCE) {
290       for (size_t i = 0;
291            certificates.empty() && i < base::size(kFormatDecodePriority); ++i) {
292         if (format & kFormatDecodePriority[i]) {
293           certificates = CreateCertBuffersFromBytes(
294               decoded.c_str(), decoded.size(), kFormatDecodePriority[i]);
295         }
296       }
297     }
298 
299     // Stop parsing after the first block for any format but a sequence of
300     // PEM-encoded DER certificates. The case of FORMAT_PEM_CERT_SEQUENCE
301     // is handled above, and continues processing until a certificate fails
302     // to parse.
303     break;
304   }
305 
306   // Try each of the formats, in order of parse preference, to see if |data|
307   // contains the binary representation of a Format, if it failed to parse
308   // as a PEM certificate/chain.
309   for (size_t i = 0;
310        certificates.empty() && i < base::size(kFormatDecodePriority); ++i) {
311     if (format & kFormatDecodePriority[i])
312       certificates =
313           CreateCertBuffersFromBytes(data, length, kFormatDecodePriority[i]);
314   }
315 
316   CertificateList results;
317   // No certificates parsed.
318   if (certificates.empty())
319     return results;
320 
321   for (auto& it : certificates) {
322     scoped_refptr<X509Certificate> cert = CreateFromBuffer(std::move(it), {});
323     if (cert)
324       results.push_back(std::move(cert));
325   }
326 
327   return results;
328 }
329 
Persist(base::Pickle * pickle) const330 void X509Certificate::Persist(base::Pickle* pickle) const {
331   DCHECK(cert_buffer_);
332   // This would be an absolutely insane number of intermediates.
333   if (intermediate_ca_certs_.size() > static_cast<size_t>(INT_MAX) - 1) {
334     NOTREACHED();
335     return;
336   }
337   pickle->WriteInt(static_cast<int>(intermediate_ca_certs_.size() + 1));
338   pickle->WriteString(x509_util::CryptoBufferAsStringPiece(cert_buffer_.get()));
339   for (const auto& intermediate : intermediate_ca_certs_) {
340     pickle->WriteString(
341         x509_util::CryptoBufferAsStringPiece(intermediate.get()));
342   }
343 }
344 
GetSubjectAltName(std::vector<std::string> * dns_names,std::vector<std::string> * ip_addrs) const345 bool X509Certificate::GetSubjectAltName(
346     std::vector<std::string>* dns_names,
347     std::vector<std::string>* ip_addrs) const {
348   if (dns_names)
349     dns_names->clear();
350   if (ip_addrs)
351     ip_addrs->clear();
352 
353   der::Input tbs_certificate_tlv;
354   der::Input signature_algorithm_tlv;
355   der::BitString signature_value;
356   if (!ParseCertificate(der::Input(CRYPTO_BUFFER_data(cert_buffer_.get()),
357                                    CRYPTO_BUFFER_len(cert_buffer_.get())),
358                         &tbs_certificate_tlv, &signature_algorithm_tlv,
359                         &signature_value, nullptr)) {
360     return false;
361   }
362 
363   ParsedTbsCertificate tbs;
364   if (!ParseTbsCertificate(tbs_certificate_tlv,
365                            x509_util::DefaultParseCertificateOptions(), &tbs,
366                            nullptr))
367     return false;
368   if (!tbs.has_extensions)
369     return false;
370 
371   std::map<der::Input, ParsedExtension> extensions;
372   if (!ParseExtensions(tbs.extensions_tlv, &extensions))
373     return false;
374 
375   ParsedExtension subject_alt_names_extension;
376   if (!ConsumeExtension(SubjectAltNameOid(), &extensions,
377                         &subject_alt_names_extension)) {
378     return false;
379   }
380 
381   CertErrors errors;
382   std::unique_ptr<GeneralNames> subject_alt_names =
383       GeneralNames::Create(subject_alt_names_extension.value, &errors);
384   if (!subject_alt_names)
385     return false;
386 
387   if (dns_names) {
388     for (const auto& dns_name : subject_alt_names->dns_names)
389       dns_names->push_back(dns_name.as_string());
390   }
391   if (ip_addrs) {
392     for (const IPAddress& addr : subject_alt_names->ip_addresses) {
393       ip_addrs->push_back(
394           std::string(reinterpret_cast<const char*>(addr.bytes().data()),
395                       addr.bytes().size()));
396     }
397   }
398 
399   return !subject_alt_names->dns_names.empty() ||
400          !subject_alt_names->ip_addresses.empty();
401 }
402 
HasExpired() const403 bool X509Certificate::HasExpired() const {
404   return base::Time::Now() > valid_expiry();
405 }
406 
EqualsExcludingChain(const X509Certificate * other) const407 bool X509Certificate::EqualsExcludingChain(const X509Certificate* other) const {
408   return x509_util::CryptoBufferEqual(cert_buffer_.get(),
409                                       other->cert_buffer_.get());
410 }
411 
EqualsIncludingChain(const X509Certificate * other) const412 bool X509Certificate::EqualsIncludingChain(const X509Certificate* other) const {
413   if (intermediate_ca_certs_.size() != other->intermediate_ca_certs_.size() ||
414       !EqualsExcludingChain(other)) {
415     return false;
416   }
417   for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) {
418     if (!x509_util::CryptoBufferEqual(intermediate_ca_certs_[i].get(),
419                                       other->intermediate_ca_certs_[i].get())) {
420       return false;
421     }
422   }
423   return true;
424 }
425 
IsIssuedByEncoded(const std::vector<std::string> & valid_issuers) const426 bool X509Certificate::IsIssuedByEncoded(
427     const std::vector<std::string>& valid_issuers) const {
428   std::vector<std::string> normalized_issuers;
429   CertErrors errors;
430   for (const auto& raw_issuer : valid_issuers) {
431     der::Input issuer_value;
432     std::string normalized_issuer;
433     if (!ParseSequenceValue(der::Input(&raw_issuer), &issuer_value) ||
434         !NormalizeName(issuer_value, &normalized_issuer, &errors)) {
435       continue;
436     }
437     normalized_issuers.push_back(std::move(normalized_issuer));
438   }
439 
440   std::string normalized_cert_issuer;
441   if (!GetNormalizedCertIssuer(cert_buffer_.get(), &normalized_cert_issuer))
442     return false;
443   if (base::Contains(normalized_issuers, normalized_cert_issuer))
444     return true;
445 
446   for (const auto& intermediate : intermediate_ca_certs_) {
447     if (!GetNormalizedCertIssuer(intermediate.get(), &normalized_cert_issuer))
448       return false;
449     if (base::Contains(normalized_issuers, normalized_cert_issuer))
450       return true;
451   }
452   return false;
453 }
454 
455 // static
VerifyHostname(const std::string & hostname,const std::vector<std::string> & cert_san_dns_names,const std::vector<std::string> & cert_san_ip_addrs)456 bool X509Certificate::VerifyHostname(
457     const std::string& hostname,
458     const std::vector<std::string>& cert_san_dns_names,
459     const std::vector<std::string>& cert_san_ip_addrs) {
460   DCHECK(!hostname.empty());
461 
462   if (cert_san_dns_names.empty() && cert_san_ip_addrs.empty()) {
463     // Either a dNSName or iPAddress subjectAltName MUST be present in order
464     // to match, so fail quickly if not.
465     return false;
466   }
467 
468   // Perform name verification following http://tools.ietf.org/html/rfc6125.
469   // The terminology used in this method is as per that RFC:-
470   // Reference identifier == the host the local user/agent is intending to
471   //                         access, i.e. the thing displayed in the URL bar.
472   // Presented identifier(s) == name(s) the server knows itself as, in its cert.
473 
474   // CanonicalizeHost requires surrounding brackets to parse an IPv6 address.
475   const std::string host_or_ip = hostname.find(':') != std::string::npos ?
476       "[" + hostname + "]" : hostname;
477   url::CanonHostInfo host_info;
478   std::string reference_name = CanonicalizeHost(host_or_ip, &host_info);
479 
480   // If the host cannot be canonicalized, fail fast.
481   if (reference_name.empty())
482     return false;
483 
484   // Fully handle all cases where |hostname| contains an IP address.
485   if (host_info.IsIPAddress()) {
486     base::StringPiece ip_addr_string(
487         reinterpret_cast<const char*>(host_info.address),
488         host_info.AddressLength());
489     return base::Contains(cert_san_ip_addrs, ip_addr_string);
490   }
491 
492   // The host portion of a URL may support a variety of name resolution formats
493   // and services. However, the only supported name types in this code are IP
494   // addresses, which have been handled above via iPAddress subjectAltNames,
495   // and DNS names, via dNSName subjectAltNames.
496   // Validate that the host conforms to the DNS preferred name syntax, in
497   // either relative or absolute form, and exclude the "root" label for DNS.
498   if (reference_name == "." || !IsValidDNSDomain(reference_name))
499     return false;
500 
501   // CanonicalizeHost does not normalize absolute vs relative DNS names. If
502   // the input name was absolute (included trailing .), normalize it as if it
503   // was relative.
504   if (reference_name.back() == '.')
505     reference_name.pop_back();
506 
507   // |reference_domain| is the remainder of |host| after the leading host
508   // component is stripped off, but includes the leading dot e.g.
509   // "www.f.com" -> ".f.com".
510   // If there is no meaningful domain part to |host| (e.g. it contains no dots)
511   // then |reference_domain| will be empty.
512   base::StringPiece reference_host, reference_domain;
513   SplitOnChar(reference_name, '.', &reference_host, &reference_domain);
514   bool allow_wildcards = false;
515   if (!reference_domain.empty()) {
516     DCHECK(reference_domain.starts_with("."));
517 
518     // Do not allow wildcards for public/ICANN registry controlled domains -
519     // that is, prevent *.com or *.co.uk as valid presented names, but do not
520     // prevent *.appspot.com (a private registry controlled domain).
521     // In addition, unknown top-level domains (such as 'intranet' domains or
522     // new TLDs/gTLDs not yet added to the registry controlled domain dataset)
523     // are also implicitly prevented.
524     // Because |reference_domain| must contain at least one name component that
525     // is not registry controlled, this ensures that all reference domains
526     // contain at least three domain components when using wildcards.
527     size_t registry_length =
528         registry_controlled_domains::GetCanonicalHostRegistryLength(
529             reference_name,
530             registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES,
531             registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
532 
533     // Because |reference_name| was already canonicalized, the following
534     // should never happen.
535     CHECK_NE(std::string::npos, registry_length);
536 
537     // Account for the leading dot in |reference_domain|.
538     bool is_registry_controlled =
539         registry_length != 0 &&
540         registry_length == (reference_domain.size() - 1);
541 
542     // Additionally, do not attempt wildcard matching for purely numeric
543     // hostnames.
544     allow_wildcards =
545         !is_registry_controlled &&
546         reference_name.find_first_not_of("0123456789.") != std::string::npos;
547   }
548 
549   // Now step through the DNS names doing wild card comparison (if necessary)
550   // on each against the reference name.
551   for (const auto& cert_san_dns_name : cert_san_dns_names) {
552     // Catch badly corrupt cert names up front.
553     if (cert_san_dns_name.empty() ||
554         cert_san_dns_name.find('\0') != std::string::npos) {
555       DVLOG(1) << "Bad name in cert: " << cert_san_dns_name;
556       continue;
557     }
558     std::string presented_name(base::ToLowerASCII(cert_san_dns_name));
559 
560     // Remove trailing dot, if any.
561     if (*presented_name.rbegin() == '.')
562       presented_name.resize(presented_name.length() - 1);
563 
564     // The hostname must be at least as long as the cert name it is matching,
565     // as we require the wildcard (if present) to match at least one character.
566     if (presented_name.length() > reference_name.length())
567       continue;
568 
569     base::StringPiece presented_host, presented_domain;
570     SplitOnChar(presented_name, '.', &presented_host, &presented_domain);
571 
572     if (presented_domain != reference_domain)
573       continue;
574 
575     if (presented_host != "*") {
576       if (presented_host == reference_host)
577         return true;
578       continue;
579     }
580 
581     if (!allow_wildcards)
582       continue;
583 
584     return true;
585   }
586   return false;
587 }
588 
VerifyNameMatch(const std::string & hostname) const589 bool X509Certificate::VerifyNameMatch(const std::string& hostname) const {
590   std::vector<std::string> dns_names, ip_addrs;
591   GetSubjectAltName(&dns_names, &ip_addrs);
592   return VerifyHostname(hostname, dns_names, ip_addrs);
593 }
594 
595 // static
GetPEMEncodedFromDER(base::StringPiece der_encoded,std::string * pem_encoded)596 bool X509Certificate::GetPEMEncodedFromDER(base::StringPiece der_encoded,
597                                            std::string* pem_encoded) {
598   if (der_encoded.empty())
599     return false;
600 
601   *pem_encoded = PEMEncode(der_encoded, "CERTIFICATE");
602   return true;
603 }
604 
605 // static
GetPEMEncoded(const CRYPTO_BUFFER * cert_buffer,std::string * pem_encoded)606 bool X509Certificate::GetPEMEncoded(const CRYPTO_BUFFER* cert_buffer,
607                                     std::string* pem_encoded) {
608   return GetPEMEncodedFromDER(x509_util::CryptoBufferAsStringPiece(cert_buffer),
609                               pem_encoded);
610 }
611 
GetPEMEncodedChain(std::vector<std::string> * pem_encoded) const612 bool X509Certificate::GetPEMEncodedChain(
613     std::vector<std::string>* pem_encoded) const {
614   std::vector<std::string> encoded_chain;
615   std::string pem_data;
616   if (!GetPEMEncoded(cert_buffer(), &pem_data))
617     return false;
618   encoded_chain.push_back(pem_data);
619   for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) {
620     if (!GetPEMEncoded(intermediate_ca_certs_[i].get(), &pem_data))
621       return false;
622     encoded_chain.push_back(pem_data);
623   }
624   pem_encoded->swap(encoded_chain);
625   return true;
626 }
627 
628 // static
GetPublicKeyInfo(const CRYPTO_BUFFER * cert_buffer,size_t * size_bits,PublicKeyType * type)629 void X509Certificate::GetPublicKeyInfo(const CRYPTO_BUFFER* cert_buffer,
630                                        size_t* size_bits,
631                                        PublicKeyType* type) {
632   *type = kPublicKeyTypeUnknown;
633   *size_bits = 0;
634 
635   base::StringPiece spki;
636   if (!asn1::ExtractSPKIFromDERCert(
637           base::StringPiece(
638               reinterpret_cast<const char*>(CRYPTO_BUFFER_data(cert_buffer)),
639               CRYPTO_BUFFER_len(cert_buffer)),
640           &spki)) {
641     return;
642   }
643 
644   bssl::UniquePtr<EVP_PKEY> pkey;
645   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
646   CBS cbs;
647   CBS_init(&cbs, reinterpret_cast<const uint8_t*>(spki.data()), spki.size());
648   pkey.reset(EVP_parse_public_key(&cbs));
649   if (!pkey)
650     return;
651 
652   switch (pkey->type) {
653     case EVP_PKEY_RSA:
654       *type = kPublicKeyTypeRSA;
655       break;
656     case EVP_PKEY_DSA:
657       *type = kPublicKeyTypeDSA;
658       break;
659     case EVP_PKEY_EC:
660       *type = kPublicKeyTypeECDSA;
661       break;
662     case EVP_PKEY_DH:
663       *type = kPublicKeyTypeDH;
664       break;
665   }
666   *size_bits = base::saturated_cast<size_t>(EVP_PKEY_bits(pkey.get()));
667 }
668 
669 // static
CreateCertBufferFromBytes(const char * data,size_t length)670 bssl::UniquePtr<CRYPTO_BUFFER> X509Certificate::CreateCertBufferFromBytes(
671     const char* data,
672     size_t length) {
673   der::Input tbs_certificate_tlv;
674   der::Input signature_algorithm_tlv;
675   der::BitString signature_value;
676   // Do a bare minimum of DER parsing here to make sure the input is not
677   // completely crazy. (This is required for at least
678   // CreateCertificateListFromBytes with FORMAT_AUTO, if not more.)
679   if (!ParseCertificate(
680           der::Input(reinterpret_cast<const uint8_t*>(data), length),
681           &tbs_certificate_tlv, &signature_algorithm_tlv, &signature_value,
682           nullptr)) {
683     return nullptr;
684   }
685 
686   return x509_util::CreateCryptoBuffer(reinterpret_cast<const uint8_t*>(data),
687                                        length);
688 }
689 
690 // static
691 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>
CreateCertBuffersFromBytes(const char * data,size_t length,Format format)692 X509Certificate::CreateCertBuffersFromBytes(const char* data,
693                                             size_t length,
694                                             Format format) {
695   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> results;
696 
697   switch (format) {
698     case FORMAT_SINGLE_CERTIFICATE: {
699       bssl::UniquePtr<CRYPTO_BUFFER> handle =
700           CreateCertBufferFromBytes(data, length);
701       if (handle)
702         results.push_back(std::move(handle));
703       break;
704     }
705     case FORMAT_PKCS7: {
706       CreateCertBuffersFromPKCS7Bytes(data, length, &results);
707       break;
708     }
709     default: {
710       NOTREACHED() << "Certificate format " << format << " unimplemented";
711       break;
712     }
713   }
714 
715   return results;
716 }
717 
718 // static
CalculateFingerprint256(const CRYPTO_BUFFER * cert)719 SHA256HashValue X509Certificate::CalculateFingerprint256(
720     const CRYPTO_BUFFER* cert) {
721   SHA256HashValue sha256;
722 
723   SHA256(CRYPTO_BUFFER_data(cert), CRYPTO_BUFFER_len(cert), sha256.data);
724   return sha256;
725 }
726 
CalculateChainFingerprint256() const727 SHA256HashValue X509Certificate::CalculateChainFingerprint256() const {
728   SHA256HashValue sha256;
729   memset(sha256.data, 0, sizeof(sha256.data));
730 
731   SHA256_CTX sha256_ctx;
732   SHA256_Init(&sha256_ctx);
733   SHA256_Update(&sha256_ctx, CRYPTO_BUFFER_data(cert_buffer_.get()),
734                 CRYPTO_BUFFER_len(cert_buffer_.get()));
735   for (const auto& cert : intermediate_ca_certs_) {
736     SHA256_Update(&sha256_ctx, CRYPTO_BUFFER_data(cert.get()),
737                   CRYPTO_BUFFER_len(cert.get()));
738   }
739   SHA256_Final(sha256.data, &sha256_ctx);
740 
741   return sha256;
742 }
743 
744 // static
IsSelfSigned(const CRYPTO_BUFFER * cert_buffer)745 bool X509Certificate::IsSelfSigned(const CRYPTO_BUFFER* cert_buffer) {
746   der::Input tbs_certificate_tlv;
747   der::Input signature_algorithm_tlv;
748   der::BitString signature_value;
749   if (!ParseCertificate(der::Input(CRYPTO_BUFFER_data(cert_buffer),
750                                    CRYPTO_BUFFER_len(cert_buffer)),
751                         &tbs_certificate_tlv, &signature_algorithm_tlv,
752                         &signature_value, nullptr)) {
753     return false;
754   }
755   ParsedTbsCertificate tbs;
756   if (!ParseTbsCertificate(tbs_certificate_tlv,
757                            x509_util::DefaultParseCertificateOptions(), &tbs,
758                            nullptr)) {
759     return false;
760   }
761 
762   der::Input subject_value;
763   CertErrors errors;
764   std::string normalized_subject;
765   if (!ParseSequenceValue(tbs.subject_tlv, &subject_value) ||
766       !NormalizeName(subject_value, &normalized_subject, &errors)) {
767     return false;
768   }
769   der::Input issuer_value;
770   std::string normalized_issuer;
771   if (!ParseSequenceValue(tbs.issuer_tlv, &issuer_value) ||
772       !NormalizeName(issuer_value, &normalized_issuer, &errors)) {
773     return false;
774   }
775 
776   if (normalized_subject != normalized_issuer)
777     return false;
778 
779   std::unique_ptr<SignatureAlgorithm> signature_algorithm =
780       SignatureAlgorithm::Create(signature_algorithm_tlv, nullptr /* errors */);
781   if (!signature_algorithm)
782     return false;
783 
784   // Don't enforce any minimum key size or restrict the algorithm, since when
785   // self signed not very relevant.
786   return VerifySignedData(*signature_algorithm, tbs_certificate_tlv,
787                           signature_value, tbs.spki_tlv);
788 }
789 
X509Certificate(bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates)790 X509Certificate::X509Certificate(
791     bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
792     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates)
793     : X509Certificate(std::move(cert_buffer), std::move(intermediates), {}) {}
794 
X509Certificate(bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,UnsafeCreateOptions options)795 X509Certificate::X509Certificate(
796     bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer,
797     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates,
798     UnsafeCreateOptions options)
799     : cert_buffer_(std::move(cert_buffer)),
800       intermediate_ca_certs_(std::move(intermediates)) {
801   // Platform-specific initialization.
802   if (!Initialize(options) && cert_buffer_) {
803     // Signal initialization failure by clearing cert_buffer_.
804     cert_buffer_.reset();
805   }
806 }
807 
808 X509Certificate::~X509Certificate() = default;
809 
Initialize(UnsafeCreateOptions options)810 bool X509Certificate::Initialize(UnsafeCreateOptions options) {
811   der::Input tbs_certificate_tlv;
812   der::Input signature_algorithm_tlv;
813   der::BitString signature_value;
814 
815   if (!ParseCertificate(der::Input(CRYPTO_BUFFER_data(cert_buffer_.get()),
816                                    CRYPTO_BUFFER_len(cert_buffer_.get())),
817                         &tbs_certificate_tlv, &signature_algorithm_tlv,
818                         &signature_value, nullptr)) {
819     return false;
820   }
821 
822   ParsedTbsCertificate tbs;
823   if (!ParseTbsCertificate(tbs_certificate_tlv,
824                            x509_util::DefaultParseCertificateOptions(), &tbs,
825                            nullptr))
826     return false;
827 
828   CertPrincipal::PrintableStringHandling printable_string_handling =
829       options.printable_string_is_utf8
830           ? CertPrincipal::PrintableStringHandling::kAsUTF8Hack
831           : CertPrincipal::PrintableStringHandling::kDefault;
832   if (!subject_.ParseDistinguishedName(tbs.subject_tlv.UnsafeData(),
833                                        tbs.subject_tlv.Length(),
834                                        printable_string_handling) ||
835       !issuer_.ParseDistinguishedName(tbs.issuer_tlv.UnsafeData(),
836                                       tbs.issuer_tlv.Length(),
837                                       printable_string_handling)) {
838     return false;
839   }
840 
841   if (!der::GeneralizedTimeToTime(tbs.validity_not_before, &valid_start_) ||
842       !der::GeneralizedTimeToTime(tbs.validity_not_after, &valid_expiry_)) {
843     return false;
844   }
845   serial_number_ = tbs.serial_number.AsString();
846   return true;
847 }
848 
849 }  // namespace net
850