x509_certificate.cc revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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 <stdlib.h> 8 9#include <algorithm> 10#include <map> 11#include <string> 12#include <vector> 13 14#include "base/base64.h" 15#include "base/lazy_instance.h" 16#include "base/logging.h" 17#include "base/memory/singleton.h" 18#include "base/metrics/histogram.h" 19#include "base/pickle.h" 20#include "base/sha1.h" 21#include "base/string_util.h" 22#include "base/strings/string_piece.h" 23#include "base/synchronization/lock.h" 24#include "base/time.h" 25#include "googleurl/src/url_canon.h" 26#include "net/base/net_util.h" 27#include "net/base/registry_controlled_domains/registry_controlled_domain.h" 28#include "net/cert/pem_tokenizer.h" 29 30namespace net { 31 32namespace { 33 34// Indicates the order to use when trying to decode binary data, which is 35// based on (speculation) as to what will be most common -> least common 36const X509Certificate::Format kFormatDecodePriority[] = { 37 X509Certificate::FORMAT_SINGLE_CERTIFICATE, 38 X509Certificate::FORMAT_PKCS7 39}; 40 41// The PEM block header used for DER certificates 42const char kCertificateHeader[] = "CERTIFICATE"; 43// The PEM block header used for PKCS#7 data 44const char kPKCS7Header[] = "PKCS7"; 45 46#if !defined(USE_NSS) 47// A thread-safe cache for OS certificate handles. 48// 49// Within each of the supported underlying crypto libraries, a certificate 50// handle is represented as a ref-counted object that contains the parsed 51// data for the certificate. In addition, the underlying OS handle may also 52// contain a copy of the original ASN.1 DER used to constructed the handle. 53// 54// In order to reduce the memory usage when multiple SSL connections exist, 55// with each connection storing the server's identity certificate plus any 56// intermediates supplied, the certificate handles are cached. Any two 57// X509Certificates that were created from the same ASN.1 DER data, 58// regardless of where that data came from, will share the same underlying 59// OS certificate handle. 60class X509CertificateCache { 61 public: 62 // Performs a compare-and-swap like operation. If an OS certificate handle 63 // for the same certificate data as |*cert_handle| already exists in the 64 // cache, the original |*cert_handle| will be freed and |cert_handle| 65 // will be updated to point to a duplicated reference to the existing cached 66 // certificate, with the caller taking ownership of this duplicated handle. 67 // If an equivalent OS certificate handle is not found, a duplicated 68 // reference to |*cert_handle| will be added to the cache. In either case, 69 // upon return, the caller fully owns |*cert_handle| and is responsible for 70 // calling FreeOSCertHandle(), after first calling Remove(). 71 void InsertOrUpdate(X509Certificate::OSCertHandle* cert_handle); 72 73 // Decrements the cache reference count for |cert_handle|, a handle that was 74 // previously obtained by calling InsertOrUpdate(). If this is the last 75 // cached reference held, this will remove the handle from the cache. The 76 // caller retains ownership of |cert_handle| and remains responsible for 77 // calling FreeOSCertHandle() to release the underlying OS certificate 78 void Remove(X509Certificate::OSCertHandle cert_handle); 79 80 private: 81 // A single entry in the cache. Certificates will be keyed by their SHA1 82 // fingerprints, but will not be considered equivalent unless the entire 83 // certificate data matches. 84 struct Entry { 85 Entry() : cert_handle(NULL), ref_count(0) {} 86 87 X509Certificate::OSCertHandle cert_handle; 88 89 // Increased by each call to InsertOrUpdate(), and balanced by each call 90 // to Remove(). When it equals 0, all references created by 91 // InsertOrUpdate() have been released, so the cache entry will be removed 92 // the cached OS certificate handle will be freed. 93 int ref_count; 94 }; 95 typedef std::map<SHA1HashValue, Entry, SHA1HashValueLessThan> CertMap; 96 97 // Obtain an instance of X509CertificateCache via a LazyInstance. 98 X509CertificateCache() {} 99 ~X509CertificateCache() {} 100 friend struct base::DefaultLazyInstanceTraits<X509CertificateCache>; 101 102 // You must acquire this lock before using any private data of this object 103 // You must not block while holding this lock. 104 base::Lock lock_; 105 106 // The certificate cache. You must acquire |lock_| before using |cache_|. 107 CertMap cache_; 108 109 DISALLOW_COPY_AND_ASSIGN(X509CertificateCache); 110}; 111 112base::LazyInstance<X509CertificateCache>::Leaky 113 g_x509_certificate_cache = LAZY_INSTANCE_INITIALIZER; 114 115void X509CertificateCache::InsertOrUpdate( 116 X509Certificate::OSCertHandle* cert_handle) { 117 DCHECK(cert_handle); 118 SHA1HashValue fingerprint = 119 X509Certificate::CalculateFingerprint(*cert_handle); 120 121 X509Certificate::OSCertHandle old_handle = NULL; 122 { 123 base::AutoLock lock(lock_); 124 CertMap::iterator pos = cache_.find(fingerprint); 125 if (pos == cache_.end()) { 126 // A cached entry was not found, so initialize a new entry. The entry 127 // assumes ownership of the current |*cert_handle|. 128 Entry cache_entry; 129 cache_entry.cert_handle = *cert_handle; 130 cache_entry.ref_count = 0; 131 CertMap::value_type cache_value(fingerprint, cache_entry); 132 pos = cache_.insert(cache_value).first; 133 } else { 134 bool is_same_cert = 135 X509Certificate::IsSameOSCert(*cert_handle, pos->second.cert_handle); 136 if (!is_same_cert) { 137 // Two certificates don't match, due to a SHA1 hash collision. Given 138 // the low probability, the simplest solution is to not cache the 139 // certificate, which should not affect performance too negatively. 140 return; 141 } 142 // A cached entry was found and will be used instead of the caller's 143 // handle. Ensure the caller's original handle will be freed, since 144 // ownership is assumed. 145 old_handle = *cert_handle; 146 } 147 // Whether an existing cached handle or a new handle, increment the 148 // cache's reference count and return a handle that the caller can own. 149 ++pos->second.ref_count; 150 *cert_handle = X509Certificate::DupOSCertHandle(pos->second.cert_handle); 151 } 152 // If the caller's handle was replaced with a cached handle, free the 153 // original handle now. This is done outside of the lock because 154 // |old_handle| may be the only handle for this particular certificate, so 155 // freeing it may be complex or resource-intensive and does not need to 156 // be guarded by the lock. 157 if (old_handle) { 158 X509Certificate::FreeOSCertHandle(old_handle); 159 DHISTOGRAM_COUNTS("X509CertificateReuseCount", 1); 160 } 161} 162 163void X509CertificateCache::Remove(X509Certificate::OSCertHandle cert_handle) { 164 SHA1HashValue fingerprint = 165 X509Certificate::CalculateFingerprint(cert_handle); 166 base::AutoLock lock(lock_); 167 168 CertMap::iterator pos = cache_.find(fingerprint); 169 if (pos == cache_.end()) 170 return; // A hash collision where the winning cert was already freed. 171 172 bool is_same_cert = X509Certificate::IsSameOSCert(cert_handle, 173 pos->second.cert_handle); 174 if (!is_same_cert) 175 return; // A hash collision where the winning cert is still around. 176 177 if (--pos->second.ref_count == 0) { 178 // The last reference to |cert_handle| has been removed, so release the 179 // Entry's OS handle and remove the Entry. The caller still holds a 180 // reference to |cert_handle| and is responsible for freeing it. 181 X509Certificate::FreeOSCertHandle(pos->second.cert_handle); 182 cache_.erase(pos); 183 } 184} 185#endif // !defined(USE_NSS) 186 187// See X509CertificateCache::InsertOrUpdate. NSS has a built-in cache, so there 188// is no point in wrapping another cache around it. 189void InsertOrUpdateCache(X509Certificate::OSCertHandle* cert_handle) { 190#if !defined(USE_NSS) 191 g_x509_certificate_cache.Pointer()->InsertOrUpdate(cert_handle); 192#endif 193} 194 195// See X509CertificateCache::Remove. 196void RemoveFromCache(X509Certificate::OSCertHandle cert_handle) { 197#if !defined(USE_NSS) 198 g_x509_certificate_cache.Pointer()->Remove(cert_handle); 199#endif 200} 201 202// Utility to split |src| on the first occurrence of |c|, if any. |right| will 203// either be empty if |c| was not found, or will contain the remainder of the 204// string including the split character itself. 205void SplitOnChar(const base::StringPiece& src, 206 char c, 207 base::StringPiece* left, 208 base::StringPiece* right) { 209 size_t pos = src.find(c); 210 if (pos == base::StringPiece::npos) { 211 *left = src; 212 right->clear(); 213 } else { 214 *left = src.substr(0, pos); 215 *right = src.substr(pos); 216 } 217} 218 219} // namespace 220 221bool X509Certificate::LessThan::operator()(X509Certificate* lhs, 222 X509Certificate* rhs) const { 223 if (lhs == rhs) 224 return false; 225 226 int rv = memcmp(lhs->fingerprint_.data, rhs->fingerprint_.data, 227 sizeof(lhs->fingerprint_.data)); 228 if (rv != 0) 229 return rv < 0; 230 231 rv = memcmp(lhs->ca_fingerprint_.data, rhs->ca_fingerprint_.data, 232 sizeof(lhs->ca_fingerprint_.data)); 233 return rv < 0; 234} 235 236X509Certificate::X509Certificate(const std::string& subject, 237 const std::string& issuer, 238 base::Time start_date, 239 base::Time expiration_date) 240 : subject_(subject), 241 issuer_(issuer), 242 valid_start_(start_date), 243 valid_expiry_(expiration_date), 244 cert_handle_(NULL) { 245 memset(fingerprint_.data, 0, sizeof(fingerprint_.data)); 246 memset(ca_fingerprint_.data, 0, sizeof(ca_fingerprint_.data)); 247} 248 249// static 250X509Certificate* X509Certificate::CreateFromHandle( 251 OSCertHandle cert_handle, 252 const OSCertHandles& intermediates) { 253 DCHECK(cert_handle); 254 return new X509Certificate(cert_handle, intermediates); 255} 256 257// static 258X509Certificate* X509Certificate::CreateFromDERCertChain( 259 const std::vector<base::StringPiece>& der_certs) { 260 if (der_certs.empty()) 261 return NULL; 262 263 X509Certificate::OSCertHandles intermediate_ca_certs; 264 for (size_t i = 1; i < der_certs.size(); i++) { 265 OSCertHandle handle = CreateOSCertHandleFromBytes( 266 const_cast<char*>(der_certs[i].data()), der_certs[i].size()); 267 if (!handle) 268 break; 269 intermediate_ca_certs.push_back(handle); 270 } 271 272 OSCertHandle handle = NULL; 273 // Return NULL if we failed to parse any of the certs. 274 if (der_certs.size() - 1 == intermediate_ca_certs.size()) { 275 handle = CreateOSCertHandleFromBytes( 276 const_cast<char*>(der_certs[0].data()), der_certs[0].size()); 277 } 278 279 X509Certificate* cert = NULL; 280 if (handle) { 281 cert = CreateFromHandle(handle, intermediate_ca_certs); 282 FreeOSCertHandle(handle); 283 } 284 285 for (size_t i = 0; i < intermediate_ca_certs.size(); i++) 286 FreeOSCertHandle(intermediate_ca_certs[i]); 287 288 return cert; 289} 290 291// static 292X509Certificate* X509Certificate::CreateFromBytes(const char* data, 293 int length) { 294 OSCertHandle cert_handle = CreateOSCertHandleFromBytes(data, length); 295 if (!cert_handle) 296 return NULL; 297 298 X509Certificate* cert = CreateFromHandle(cert_handle, OSCertHandles()); 299 FreeOSCertHandle(cert_handle); 300 return cert; 301} 302 303// static 304X509Certificate* X509Certificate::CreateFromPickle(const Pickle& pickle, 305 PickleIterator* pickle_iter, 306 PickleType type) { 307 if (type == PICKLETYPE_CERTIFICATE_CHAIN_V3) { 308 int chain_length = 0; 309 if (!pickle_iter->ReadLength(&chain_length)) 310 return NULL; 311 312 std::vector<base::StringPiece> cert_chain; 313 const char* data = NULL; 314 int data_length = 0; 315 for (int i = 0; i < chain_length; ++i) { 316 if (!pickle_iter->ReadData(&data, &data_length)) 317 return NULL; 318 cert_chain.push_back(base::StringPiece(data, data_length)); 319 } 320 return CreateFromDERCertChain(cert_chain); 321 } 322 323 // Legacy / Migration code. This should eventually be removed once 324 // sufficient time has passed that all pickles serialized prior to 325 // PICKLETYPE_CERTIFICATE_CHAIN_V3 have been removed. 326 OSCertHandle cert_handle = ReadOSCertHandleFromPickle(pickle_iter); 327 if (!cert_handle) 328 return NULL; 329 330 OSCertHandles intermediates; 331 uint32 num_intermediates = 0; 332 if (type != PICKLETYPE_SINGLE_CERTIFICATE) { 333 if (!pickle_iter->ReadUInt32(&num_intermediates)) { 334 FreeOSCertHandle(cert_handle); 335 return NULL; 336 } 337 338#if defined(OS_POSIX) && !defined(OS_MACOSX) && defined(__x86_64__) 339 // On 64-bit Linux (and any other 64-bit platforms), the intermediate count 340 // might really be a 64-bit field since we used to use Pickle::WriteSize(), 341 // which writes either 32 or 64 bits depending on the architecture. Since 342 // x86-64 is little-endian, if that happens, the next 32 bits will be all 343 // zeroes (the high bits) and the 32 bits we already read above are the 344 // correct value (we assume there are never more than 2^32 - 1 intermediate 345 // certificates in a chain; in practice, more than a dozen or so is 346 // basically unheard of). Since it's invalid for a certificate to start with 347 // 32 bits of zeroes, we check for that here and skip it if we find it. We 348 // save a copy of the pickle iterator to restore in case we don't get 32 349 // bits of zeroes. Now we always write 32 bits, so after a while, these old 350 // cached pickles will all get replaced. 351 // TODO(mdm): remove this compatibility code in April 2013 or so. 352 PickleIterator saved_iter = *pickle_iter; 353 uint32 zero_check = 0; 354 if (!pickle_iter->ReadUInt32(&zero_check)) { 355 // This may not be an error. If there are no intermediates, and we're 356 // reading an old 32-bit pickle, and there's nothing else after this in 357 // the pickle, we should report success. Note that it is technically 358 // possible for us to skip over zeroes that should have occurred after 359 // an empty certificate list; to avoid this going forward, only do this 360 // backward-compatibility stuff for PICKLETYPE_CERTIFICATE_CHAIN_V1 361 // which comes from the pickle version number in http_response_info.cc. 362 if (num_intermediates) { 363 FreeOSCertHandle(cert_handle); 364 return NULL; 365 } 366 } 367 if (zero_check) 368 *pickle_iter = saved_iter; 369#endif // defined(OS_POSIX) && !defined(OS_MACOSX) && defined(__x86_64__) 370 371 for (uint32 i = 0; i < num_intermediates; ++i) { 372 OSCertHandle intermediate = ReadOSCertHandleFromPickle(pickle_iter); 373 if (!intermediate) 374 break; 375 intermediates.push_back(intermediate); 376 } 377 } 378 379 X509Certificate* cert = NULL; 380 if (intermediates.size() == num_intermediates) 381 cert = CreateFromHandle(cert_handle, intermediates); 382 FreeOSCertHandle(cert_handle); 383 for (size_t i = 0; i < intermediates.size(); ++i) 384 FreeOSCertHandle(intermediates[i]); 385 386 return cert; 387} 388 389// static 390CertificateList X509Certificate::CreateCertificateListFromBytes( 391 const char* data, int length, int format) { 392 OSCertHandles certificates; 393 394 // Check to see if it is in a PEM-encoded form. This check is performed 395 // first, as both OS X and NSS will both try to convert if they detect 396 // PEM encoding, except they don't do it consistently between the two. 397 base::StringPiece data_string(data, length); 398 std::vector<std::string> pem_headers; 399 400 // To maintain compatibility with NSS/Firefox, CERTIFICATE is a universally 401 // valid PEM block header for any format. 402 pem_headers.push_back(kCertificateHeader); 403 if (format & FORMAT_PKCS7) 404 pem_headers.push_back(kPKCS7Header); 405 406 PEMTokenizer pem_tok(data_string, pem_headers); 407 while (pem_tok.GetNext()) { 408 std::string decoded(pem_tok.data()); 409 410 OSCertHandle handle = NULL; 411 if (format & FORMAT_PEM_CERT_SEQUENCE) 412 handle = CreateOSCertHandleFromBytes(decoded.c_str(), decoded.size()); 413 if (handle != NULL) { 414 // Parsed a DER encoded certificate. All PEM blocks that follow must 415 // also be DER encoded certificates wrapped inside of PEM blocks. 416 format = FORMAT_PEM_CERT_SEQUENCE; 417 certificates.push_back(handle); 418 continue; 419 } 420 421 // If the first block failed to parse as a DER certificate, and 422 // formats other than PEM are acceptable, check to see if the decoded 423 // data is one of the accepted formats. 424 if (format & ~FORMAT_PEM_CERT_SEQUENCE) { 425 for (size_t i = 0; certificates.empty() && 426 i < arraysize(kFormatDecodePriority); ++i) { 427 if (format & kFormatDecodePriority[i]) { 428 certificates = CreateOSCertHandlesFromBytes(decoded.c_str(), 429 decoded.size(), kFormatDecodePriority[i]); 430 } 431 } 432 } 433 434 // Stop parsing after the first block for any format but a sequence of 435 // PEM-encoded DER certificates. The case of FORMAT_PEM_CERT_SEQUENCE 436 // is handled above, and continues processing until a certificate fails 437 // to parse. 438 break; 439 } 440 441 // Try each of the formats, in order of parse preference, to see if |data| 442 // contains the binary representation of a Format, if it failed to parse 443 // as a PEM certificate/chain. 444 for (size_t i = 0; certificates.empty() && 445 i < arraysize(kFormatDecodePriority); ++i) { 446 if (format & kFormatDecodePriority[i]) 447 certificates = CreateOSCertHandlesFromBytes(data, length, 448 kFormatDecodePriority[i]); 449 } 450 451 CertificateList results; 452 // No certificates parsed. 453 if (certificates.empty()) 454 return results; 455 456 for (OSCertHandles::iterator it = certificates.begin(); 457 it != certificates.end(); ++it) { 458 X509Certificate* result = CreateFromHandle(*it, OSCertHandles()); 459 results.push_back(scoped_refptr<X509Certificate>(result)); 460 FreeOSCertHandle(*it); 461 } 462 463 return results; 464} 465 466void X509Certificate::Persist(Pickle* pickle) { 467 DCHECK(cert_handle_); 468 // This would be an absolutely insane number of intermediates. 469 if (intermediate_ca_certs_.size() > static_cast<size_t>(INT_MAX) - 1) { 470 NOTREACHED(); 471 return; 472 } 473 if (!pickle->WriteInt( 474 static_cast<int>(intermediate_ca_certs_.size() + 1)) || 475 !WriteOSCertHandleToPickle(cert_handle_, pickle)) { 476 NOTREACHED(); 477 return; 478 } 479 for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) { 480 if (!WriteOSCertHandleToPickle(intermediate_ca_certs_[i], pickle)) { 481 NOTREACHED(); 482 return; 483 } 484 } 485} 486 487void X509Certificate::GetDNSNames(std::vector<std::string>* dns_names) const { 488 GetSubjectAltName(dns_names, NULL); 489 if (dns_names->empty()) 490 dns_names->push_back(subject_.common_name); 491} 492 493bool X509Certificate::HasExpired() const { 494 return base::Time::Now() > valid_expiry(); 495} 496 497bool X509Certificate::Equals(const X509Certificate* other) const { 498 return IsSameOSCert(cert_handle_, other->cert_handle_); 499} 500 501// static 502bool X509Certificate::VerifyHostname( 503 const std::string& hostname, 504 const std::string& cert_common_name, 505 const std::vector<std::string>& cert_san_dns_names, 506 const std::vector<std::string>& cert_san_ip_addrs) { 507 DCHECK(!hostname.empty()); 508 // Perform name verification following http://tools.ietf.org/html/rfc6125. 509 // The terminology used in this method is as per that RFC:- 510 // Reference identifier == the host the local user/agent is intending to 511 // access, i.e. the thing displayed in the URL bar. 512 // Presented identifier(s) == name(s) the server knows itself as, in its cert. 513 514 // CanonicalizeHost requires surrounding brackets to parse an IPv6 address. 515 const std::string host_or_ip = hostname.find(':') != std::string::npos ? 516 "[" + hostname + "]" : hostname; 517 url_canon::CanonHostInfo host_info; 518 std::string reference_name = CanonicalizeHost(host_or_ip, &host_info); 519 // CanonicalizeHost does not normalize absolute vs relative DNS names. If 520 // the input name was absolute (included trailing .), normalize it as if it 521 // was relative. 522 if (!reference_name.empty() && *reference_name.rbegin() == '.') 523 reference_name.resize(reference_name.size() - 1); 524 if (reference_name.empty()) 525 return false; 526 527 // Allow fallback to Common name matching? 528 const bool common_name_fallback = cert_san_dns_names.empty() && 529 cert_san_ip_addrs.empty(); 530 531 // Fully handle all cases where |hostname| contains an IP address. 532 if (host_info.IsIPAddress()) { 533 if (common_name_fallback && 534 host_info.family == url_canon::CanonHostInfo::IPV4) { 535 // Fallback to Common name matching. As this is deprecated and only 536 // supported for compatibility refuse it for IPv6 addresses. 537 return reference_name == cert_common_name; 538 } 539 base::StringPiece ip_addr_string( 540 reinterpret_cast<const char*>(host_info.address), 541 host_info.AddressLength()); 542 return std::find(cert_san_ip_addrs.begin(), cert_san_ip_addrs.end(), 543 ip_addr_string) != cert_san_ip_addrs.end(); 544 } 545 546 // |reference_domain| is the remainder of |host| after the leading host 547 // component is stripped off, but includes the leading dot e.g. 548 // "www.f.com" -> ".f.com". 549 // If there is no meaningful domain part to |host| (e.g. it contains no dots) 550 // then |reference_domain| will be empty. 551 base::StringPiece reference_host, reference_domain; 552 SplitOnChar(reference_name, '.', &reference_host, &reference_domain); 553 bool allow_wildcards = false; 554 if (!reference_domain.empty()) { 555 DCHECK(reference_domain.starts_with(".")); 556 557 // Do not allow wildcards for public/ICANN registry controlled domains - 558 // that is, prevent *.com or *.co.uk as valid presented names, but do not 559 // prevent *.appspot.com (a private registry controlled domain). 560 // In addition, unknown top-level domains (such as 'intranet' domains or 561 // new TLDs/gTLDs not yet added to the registry controlled domain dataset) 562 // are also implicitly prevented. 563 // Because |reference_domain| must contain at least one name component that 564 // is not registry controlled, this ensures that all reference domains 565 // contain at least three domain components when using wildcards. 566 size_t registry_length = 567 registry_controlled_domains::GetRegistryLength( 568 reference_name, 569 registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES, 570 registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); 571 572 // Because |reference_name| was already canonicalized, the following 573 // should never happen. 574 CHECK_NE(std::string::npos, registry_length); 575 576 // Account for the leading dot in |reference_domain|. 577 bool is_registry_controlled = 578 registry_length != 0 && 579 registry_length == (reference_domain.size() - 1); 580 581 // Additionally, do not attempt wildcard matching for purely numeric 582 // hostnames. 583 allow_wildcards = 584 !is_registry_controlled && 585 reference_name.find_first_not_of("0123456789.") != std::string::npos; 586 } 587 588 // Now step through the DNS names doing wild card comparison (if necessary) 589 // on each against the reference name. If subjectAltName is empty, then 590 // fallback to use the common name instead. 591 std::vector<std::string> common_name_as_vector; 592 const std::vector<std::string>* presented_names = &cert_san_dns_names; 593 if (common_name_fallback) { 594 // Note: there's a small possibility cert_common_name is an international 595 // domain name in non-standard encoding (e.g. UTF8String or BMPString 596 // instead of A-label). As common name fallback is deprecated we're not 597 // doing anything specific to deal with this. 598 common_name_as_vector.push_back(cert_common_name); 599 presented_names = &common_name_as_vector; 600 } 601 for (std::vector<std::string>::const_iterator it = 602 presented_names->begin(); 603 it != presented_names->end(); ++it) { 604 // Catch badly corrupt cert names up front. 605 if (it->empty() || it->find('\0') != std::string::npos) { 606 DVLOG(1) << "Bad name in cert: " << *it; 607 continue; 608 } 609 std::string presented_name(StringToLowerASCII(*it)); 610 611 // Remove trailing dot, if any. 612 if (*presented_name.rbegin() == '.') 613 presented_name.resize(presented_name.length() - 1); 614 615 // The hostname must be at least as long as the cert name it is matching, 616 // as we require the wildcard (if present) to match at least one character. 617 if (presented_name.length() > reference_name.length()) 618 continue; 619 620 base::StringPiece presented_host, presented_domain; 621 SplitOnChar(presented_name, '.', &presented_host, &presented_domain); 622 623 if (presented_domain != reference_domain) 624 continue; 625 626 base::StringPiece pattern_begin, pattern_end; 627 SplitOnChar(presented_host, '*', &pattern_begin, &pattern_end); 628 629 if (pattern_end.empty()) { // No '*' in the presented_host 630 if (presented_host == reference_host) 631 return true; 632 continue; 633 } 634 pattern_end.remove_prefix(1); // move past the * 635 636 if (!allow_wildcards) 637 continue; 638 639 // * must not match a substring of an IDN A label; just a whole fragment. 640 if (reference_host.starts_with("xn--") && 641 !(pattern_begin.empty() && pattern_end.empty())) 642 continue; 643 644 if (reference_host.starts_with(pattern_begin) && 645 reference_host.ends_with(pattern_end)) 646 return true; 647 } 648 return false; 649} 650 651bool X509Certificate::VerifyNameMatch(const std::string& hostname) const { 652 std::vector<std::string> dns_names, ip_addrs; 653 GetSubjectAltName(&dns_names, &ip_addrs); 654 return VerifyHostname(hostname, subject_.common_name, dns_names, ip_addrs); 655} 656 657// static 658bool X509Certificate::GetPEMEncoded(OSCertHandle cert_handle, 659 std::string* pem_encoded) { 660 std::string der_encoded; 661 if (!GetDEREncoded(cert_handle, &der_encoded) || der_encoded.empty()) 662 return false; 663 std::string b64_encoded; 664 if (!base::Base64Encode(der_encoded, &b64_encoded) || b64_encoded.empty()) 665 return false; 666 *pem_encoded = "-----BEGIN CERTIFICATE-----\n"; 667 668 // Divide the Base-64 encoded data into 64-character chunks, as per 669 // 4.3.2.4 of RFC 1421. 670 static const size_t kChunkSize = 64; 671 size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize; 672 for (size_t i = 0, chunk_offset = 0; i < chunks; 673 ++i, chunk_offset += kChunkSize) { 674 pem_encoded->append(b64_encoded, chunk_offset, kChunkSize); 675 pem_encoded->append("\n"); 676 } 677 pem_encoded->append("-----END CERTIFICATE-----\n"); 678 return true; 679} 680 681bool X509Certificate::GetPEMEncodedChain( 682 std::vector<std::string>* pem_encoded) const { 683 std::vector<std::string> encoded_chain; 684 std::string pem_data; 685 if (!GetPEMEncoded(os_cert_handle(), &pem_data)) 686 return false; 687 encoded_chain.push_back(pem_data); 688 for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) { 689 if (!GetPEMEncoded(intermediate_ca_certs_[i], &pem_data)) 690 return false; 691 encoded_chain.push_back(pem_data); 692 } 693 pem_encoded->swap(encoded_chain); 694 return true; 695} 696 697X509Certificate::X509Certificate(OSCertHandle cert_handle, 698 const OSCertHandles& intermediates) 699 : cert_handle_(DupOSCertHandle(cert_handle)) { 700 InsertOrUpdateCache(&cert_handle_); 701 for (size_t i = 0; i < intermediates.size(); ++i) { 702 // Duplicate the incoming certificate, as the caller retains ownership 703 // of |intermediates|. 704 OSCertHandle intermediate = DupOSCertHandle(intermediates[i]); 705 // Update the cache, which will assume ownership of the duplicated 706 // handle and return a suitable equivalent, potentially from the cache. 707 InsertOrUpdateCache(&intermediate); 708 intermediate_ca_certs_.push_back(intermediate); 709 } 710 // Platform-specific initialization. 711 Initialize(); 712} 713 714X509Certificate::~X509Certificate() { 715 if (cert_handle_) { 716 RemoveFromCache(cert_handle_); 717 FreeOSCertHandle(cert_handle_); 718 } 719 for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) { 720 RemoveFromCache(intermediate_ca_certs_[i]); 721 FreeOSCertHandle(intermediate_ca_certs_[i]); 722 } 723} 724 725} // namespace net 726