This source file includes following definitions.
- InsertOrUpdate
- Remove
- InsertOrUpdateCache
- RemoveFromCache
- SplitOnChar
- cert_handle_
- CreateFromHandle
- CreateFromDERCertChain
- CreateFromBytes
- CreateFromPickle
- CreateCertificateListFromBytes
- Persist
- GetDNSNames
- HasExpired
- Equals
- VerifyHostname
- VerifyNameMatch
- GetPEMEncodedFromDER
- GetPEMEncoded
- GetPEMEncodedChain
#include "net/cert/x509_certificate.h"
#include <stdlib.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/metrics/histogram.h"
#include "base/pickle.h"
#include "base/sha1.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/synchronization/lock.h"
#include "base/time/time.h"
#include "net/base/net_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/cert/pem_tokenizer.h"
#include "url/url_canon.h"
namespace net {
namespace {
const X509Certificate::Format kFormatDecodePriority[] = {
X509Certificate::FORMAT_SINGLE_CERTIFICATE,
X509Certificate::FORMAT_PKCS7
};
const char kCertificateHeader[] = "CERTIFICATE";
const char kPKCS7Header[] = "PKCS7";
#if !defined(USE_NSS)
class X509CertificateCache {
public:
void InsertOrUpdate(X509Certificate::OSCertHandle* cert_handle);
void Remove(X509Certificate::OSCertHandle cert_handle);
private:
struct Entry {
Entry() : cert_handle(NULL), ref_count(0) {}
X509Certificate::OSCertHandle cert_handle;
int ref_count;
};
typedef std::map<SHA1HashValue, Entry, SHA1HashValueLessThan> CertMap;
X509CertificateCache() {}
~X509CertificateCache() {}
friend struct base::DefaultLazyInstanceTraits<X509CertificateCache>;
base::Lock lock_;
CertMap cache_;
DISALLOW_COPY_AND_ASSIGN(X509CertificateCache);
};
base::LazyInstance<X509CertificateCache>::Leaky
g_x509_certificate_cache = LAZY_INSTANCE_INITIALIZER;
void X509CertificateCache::InsertOrUpdate(
X509Certificate::OSCertHandle* cert_handle) {
DCHECK(cert_handle);
SHA1HashValue fingerprint =
X509Certificate::CalculateFingerprint(*cert_handle);
X509Certificate::OSCertHandle old_handle = NULL;
{
base::AutoLock lock(lock_);
CertMap::iterator pos = cache_.find(fingerprint);
if (pos == cache_.end()) {
Entry cache_entry;
cache_entry.cert_handle = *cert_handle;
cache_entry.ref_count = 0;
CertMap::value_type cache_value(fingerprint, cache_entry);
pos = cache_.insert(cache_value).first;
} else {
bool is_same_cert =
X509Certificate::IsSameOSCert(*cert_handle, pos->second.cert_handle);
if (!is_same_cert) {
return;
}
old_handle = *cert_handle;
}
++pos->second.ref_count;
*cert_handle = X509Certificate::DupOSCertHandle(pos->second.cert_handle);
}
if (old_handle) {
X509Certificate::FreeOSCertHandle(old_handle);
DHISTOGRAM_COUNTS("X509CertificateReuseCount", 1);
}
}
void X509CertificateCache::Remove(X509Certificate::OSCertHandle cert_handle) {
SHA1HashValue fingerprint =
X509Certificate::CalculateFingerprint(cert_handle);
base::AutoLock lock(lock_);
CertMap::iterator pos = cache_.find(fingerprint);
if (pos == cache_.end())
return;
bool is_same_cert = X509Certificate::IsSameOSCert(cert_handle,
pos->second.cert_handle);
if (!is_same_cert)
return;
if (--pos->second.ref_count == 0) {
X509Certificate::FreeOSCertHandle(pos->second.cert_handle);
cache_.erase(pos);
}
}
#endif
void InsertOrUpdateCache(X509Certificate::OSCertHandle* cert_handle) {
#if !defined(USE_NSS)
g_x509_certificate_cache.Pointer()->InsertOrUpdate(cert_handle);
#endif
}
void RemoveFromCache(X509Certificate::OSCertHandle cert_handle) {
#if !defined(USE_NSS)
g_x509_certificate_cache.Pointer()->Remove(cert_handle);
#endif
}
void SplitOnChar(const base::StringPiece& src,
char c,
base::StringPiece* left,
base::StringPiece* right) {
size_t pos = src.find(c);
if (pos == base::StringPiece::npos) {
*left = src;
right->clear();
} else {
*left = src.substr(0, pos);
*right = src.substr(pos);
}
}
}
bool X509Certificate::LessThan::operator()(
const scoped_refptr<X509Certificate>& lhs,
const scoped_refptr<X509Certificate>& rhs) const {
if (lhs.get() == rhs.get())
return false;
int rv = memcmp(lhs->fingerprint_.data, rhs->fingerprint_.data,
sizeof(lhs->fingerprint_.data));
if (rv != 0)
return rv < 0;
rv = memcmp(lhs->ca_fingerprint_.data, rhs->ca_fingerprint_.data,
sizeof(lhs->ca_fingerprint_.data));
return rv < 0;
}
X509Certificate::X509Certificate(const std::string& subject,
const std::string& issuer,
base::Time start_date,
base::Time expiration_date)
: subject_(subject),
issuer_(issuer),
valid_start_(start_date),
valid_expiry_(expiration_date),
cert_handle_(NULL) {
memset(fingerprint_.data, 0, sizeof(fingerprint_.data));
memset(ca_fingerprint_.data, 0, sizeof(ca_fingerprint_.data));
}
X509Certificate* X509Certificate::CreateFromHandle(
OSCertHandle cert_handle,
const OSCertHandles& intermediates) {
DCHECK(cert_handle);
return new X509Certificate(cert_handle, intermediates);
}
X509Certificate* X509Certificate::CreateFromDERCertChain(
const std::vector<base::StringPiece>& der_certs) {
if (der_certs.empty())
return NULL;
X509Certificate::OSCertHandles intermediate_ca_certs;
for (size_t i = 1; i < der_certs.size(); i++) {
OSCertHandle handle = CreateOSCertHandleFromBytes(
const_cast<char*>(der_certs[i].data()), der_certs[i].size());
if (!handle)
break;
intermediate_ca_certs.push_back(handle);
}
OSCertHandle handle = NULL;
if (der_certs.size() - 1 == intermediate_ca_certs.size()) {
handle = CreateOSCertHandleFromBytes(
const_cast<char*>(der_certs[0].data()), der_certs[0].size());
}
X509Certificate* cert = NULL;
if (handle) {
cert = CreateFromHandle(handle, intermediate_ca_certs);
FreeOSCertHandle(handle);
}
for (size_t i = 0; i < intermediate_ca_certs.size(); i++)
FreeOSCertHandle(intermediate_ca_certs[i]);
return cert;
}
X509Certificate* X509Certificate::CreateFromBytes(const char* data,
int length) {
OSCertHandle cert_handle = CreateOSCertHandleFromBytes(data, length);
if (!cert_handle)
return NULL;
X509Certificate* cert = CreateFromHandle(cert_handle, OSCertHandles());
FreeOSCertHandle(cert_handle);
return cert;
}
X509Certificate* X509Certificate::CreateFromPickle(const Pickle& pickle,
PickleIterator* pickle_iter,
PickleType type) {
if (type == PICKLETYPE_CERTIFICATE_CHAIN_V3) {
int chain_length = 0;
if (!pickle_iter->ReadLength(&chain_length))
return NULL;
std::vector<base::StringPiece> cert_chain;
const char* data = NULL;
int data_length = 0;
for (int i = 0; i < chain_length; ++i) {
if (!pickle_iter->ReadData(&data, &data_length))
return NULL;
cert_chain.push_back(base::StringPiece(data, data_length));
}
return CreateFromDERCertChain(cert_chain);
}
OSCertHandle cert_handle = ReadOSCertHandleFromPickle(pickle_iter);
if (!cert_handle)
return NULL;
OSCertHandles intermediates;
uint32 num_intermediates = 0;
if (type != PICKLETYPE_SINGLE_CERTIFICATE) {
if (!pickle_iter->ReadUInt32(&num_intermediates)) {
FreeOSCertHandle(cert_handle);
return NULL;
}
#if defined(OS_POSIX) && !defined(OS_MACOSX) && defined(__x86_64__)
PickleIterator saved_iter = *pickle_iter;
uint32 zero_check = 0;
if (!pickle_iter->ReadUInt32(&zero_check)) {
if (num_intermediates) {
FreeOSCertHandle(cert_handle);
return NULL;
}
}
if (zero_check)
*pickle_iter = saved_iter;
#endif
for (uint32 i = 0; i < num_intermediates; ++i) {
OSCertHandle intermediate = ReadOSCertHandleFromPickle(pickle_iter);
if (!intermediate)
break;
intermediates.push_back(intermediate);
}
}
X509Certificate* cert = NULL;
if (intermediates.size() == num_intermediates)
cert = CreateFromHandle(cert_handle, intermediates);
FreeOSCertHandle(cert_handle);
for (size_t i = 0; i < intermediates.size(); ++i)
FreeOSCertHandle(intermediates[i]);
return cert;
}
CertificateList X509Certificate::CreateCertificateListFromBytes(
const char* data, int length, int format) {
OSCertHandles certificates;
base::StringPiece data_string(data, length);
std::vector<std::string> pem_headers;
pem_headers.push_back(kCertificateHeader);
if (format & FORMAT_PKCS7)
pem_headers.push_back(kPKCS7Header);
PEMTokenizer pem_tok(data_string, pem_headers);
while (pem_tok.GetNext()) {
std::string decoded(pem_tok.data());
OSCertHandle handle = NULL;
if (format & FORMAT_PEM_CERT_SEQUENCE)
handle = CreateOSCertHandleFromBytes(decoded.c_str(), decoded.size());
if (handle != NULL) {
format = FORMAT_PEM_CERT_SEQUENCE;
certificates.push_back(handle);
continue;
}
if (format & ~FORMAT_PEM_CERT_SEQUENCE) {
for (size_t i = 0; certificates.empty() &&
i < arraysize(kFormatDecodePriority); ++i) {
if (format & kFormatDecodePriority[i]) {
certificates = CreateOSCertHandlesFromBytes(decoded.c_str(),
decoded.size(), kFormatDecodePriority[i]);
}
}
}
break;
}
for (size_t i = 0; certificates.empty() &&
i < arraysize(kFormatDecodePriority); ++i) {
if (format & kFormatDecodePriority[i])
certificates = CreateOSCertHandlesFromBytes(data, length,
kFormatDecodePriority[i]);
}
CertificateList results;
if (certificates.empty())
return results;
for (OSCertHandles::iterator it = certificates.begin();
it != certificates.end(); ++it) {
X509Certificate* result = CreateFromHandle(*it, OSCertHandles());
results.push_back(scoped_refptr<X509Certificate>(result));
FreeOSCertHandle(*it);
}
return results;
}
void X509Certificate::Persist(Pickle* pickle) {
DCHECK(cert_handle_);
if (intermediate_ca_certs_.size() > static_cast<size_t>(INT_MAX) - 1) {
NOTREACHED();
return;
}
if (!pickle->WriteInt(
static_cast<int>(intermediate_ca_certs_.size() + 1)) ||
!WriteOSCertHandleToPickle(cert_handle_, pickle)) {
NOTREACHED();
return;
}
for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) {
if (!WriteOSCertHandleToPickle(intermediate_ca_certs_[i], pickle)) {
NOTREACHED();
return;
}
}
}
void X509Certificate::GetDNSNames(std::vector<std::string>* dns_names) const {
GetSubjectAltName(dns_names, NULL);
if (dns_names->empty())
dns_names->push_back(subject_.common_name);
}
bool X509Certificate::HasExpired() const {
return base::Time::Now() > valid_expiry();
}
bool X509Certificate::Equals(const X509Certificate* other) const {
return IsSameOSCert(cert_handle_, other->cert_handle_);
}
bool X509Certificate::VerifyHostname(
const std::string& hostname,
const std::string& cert_common_name,
const std::vector<std::string>& cert_san_dns_names,
const std::vector<std::string>& cert_san_ip_addrs,
bool* common_name_fallback_used) {
DCHECK(!hostname.empty());
const std::string host_or_ip = hostname.find(':') != std::string::npos ?
"[" + hostname + "]" : hostname;
url_canon::CanonHostInfo host_info;
std::string reference_name = CanonicalizeHost(host_or_ip, &host_info);
if (!reference_name.empty() && *reference_name.rbegin() == '.')
reference_name.resize(reference_name.size() - 1);
if (reference_name.empty())
return false;
const bool common_name_fallback = cert_san_dns_names.empty() &&
cert_san_ip_addrs.empty();
*common_name_fallback_used = common_name_fallback;
if (host_info.IsIPAddress()) {
if (common_name_fallback &&
host_info.family == url_canon::CanonHostInfo::IPV4) {
return reference_name == cert_common_name;
}
base::StringPiece ip_addr_string(
reinterpret_cast<const char*>(host_info.address),
host_info.AddressLength());
return std::find(cert_san_ip_addrs.begin(), cert_san_ip_addrs.end(),
ip_addr_string) != cert_san_ip_addrs.end();
}
base::StringPiece reference_host, reference_domain;
SplitOnChar(reference_name, '.', &reference_host, &reference_domain);
bool allow_wildcards = false;
if (!reference_domain.empty()) {
DCHECK(reference_domain.starts_with("."));
size_t registry_length =
registry_controlled_domains::GetRegistryLength(
reference_name,
registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES,
registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
CHECK_NE(std::string::npos, registry_length);
bool is_registry_controlled =
registry_length != 0 &&
registry_length == (reference_domain.size() - 1);
allow_wildcards =
!is_registry_controlled &&
reference_name.find_first_not_of("0123456789.") != std::string::npos;
}
std::vector<std::string> common_name_as_vector;
const std::vector<std::string>* presented_names = &cert_san_dns_names;
if (common_name_fallback) {
common_name_as_vector.push_back(cert_common_name);
presented_names = &common_name_as_vector;
}
for (std::vector<std::string>::const_iterator it =
presented_names->begin();
it != presented_names->end(); ++it) {
if (it->empty() || it->find('\0') != std::string::npos) {
DVLOG(1) << "Bad name in cert: " << *it;
continue;
}
std::string presented_name(StringToLowerASCII(*it));
if (*presented_name.rbegin() == '.')
presented_name.resize(presented_name.length() - 1);
if (presented_name.length() > reference_name.length())
continue;
base::StringPiece presented_host, presented_domain;
SplitOnChar(presented_name, '.', &presented_host, &presented_domain);
if (presented_domain != reference_domain)
continue;
base::StringPiece pattern_begin, pattern_end;
SplitOnChar(presented_host, '*', &pattern_begin, &pattern_end);
if (pattern_end.empty()) {
if (presented_host == reference_host)
return true;
continue;
}
pattern_end.remove_prefix(1);
if (!allow_wildcards)
continue;
if (reference_host.starts_with("xn--") &&
!(pattern_begin.empty() && pattern_end.empty()))
continue;
if (reference_host.starts_with(pattern_begin) &&
reference_host.ends_with(pattern_end))
return true;
}
return false;
}
bool X509Certificate::VerifyNameMatch(const std::string& hostname,
bool* common_name_fallback_used) const {
std::vector<std::string> dns_names, ip_addrs;
GetSubjectAltName(&dns_names, &ip_addrs);
return VerifyHostname(hostname, subject_.common_name, dns_names, ip_addrs,
common_name_fallback_used);
}
bool X509Certificate::GetPEMEncodedFromDER(const std::string& der_encoded,
std::string* pem_encoded) {
if (der_encoded.empty())
return false;
std::string b64_encoded;
base::Base64Encode(der_encoded, &b64_encoded);
*pem_encoded = "-----BEGIN CERTIFICATE-----\n";
static const size_t kChunkSize = 64;
size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize;
for (size_t i = 0, chunk_offset = 0; i < chunks;
++i, chunk_offset += kChunkSize) {
pem_encoded->append(b64_encoded, chunk_offset, kChunkSize);
pem_encoded->append("\n");
}
pem_encoded->append("-----END CERTIFICATE-----\n");
return true;
}
bool X509Certificate::GetPEMEncoded(OSCertHandle cert_handle,
std::string* pem_encoded) {
std::string der_encoded;
if (!GetDEREncoded(cert_handle, &der_encoded))
return false;
return GetPEMEncodedFromDER(der_encoded, pem_encoded);
}
bool X509Certificate::GetPEMEncodedChain(
std::vector<std::string>* pem_encoded) const {
std::vector<std::string> encoded_chain;
std::string pem_data;
if (!GetPEMEncoded(os_cert_handle(), &pem_data))
return false;
encoded_chain.push_back(pem_data);
for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) {
if (!GetPEMEncoded(intermediate_ca_certs_[i], &pem_data))
return false;
encoded_chain.push_back(pem_data);
}
pem_encoded->swap(encoded_chain);
return true;
}
X509Certificate::X509Certificate(OSCertHandle cert_handle,
const OSCertHandles& intermediates)
: cert_handle_(DupOSCertHandle(cert_handle)) {
InsertOrUpdateCache(&cert_handle_);
for (size_t i = 0; i < intermediates.size(); ++i) {
OSCertHandle intermediate = DupOSCertHandle(intermediates[i]);
InsertOrUpdateCache(&intermediate);
intermediate_ca_certs_.push_back(intermediate);
}
Initialize();
}
X509Certificate::~X509Certificate() {
if (cert_handle_) {
RemoveFromCache(cert_handle_);
FreeOSCertHandle(cert_handle_);
}
for (size_t i = 0; i < intermediate_ca_certs_.size(); ++i) {
RemoveFromCache(intermediate_ca_certs_[i]);
FreeOSCertHandle(intermediate_ca_certs_[i]);
}
}
}