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