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 <openssl/asn1.h>
8 #include <openssl/bytestring.h>
9 #include <openssl/crypto.h>
10 #include <openssl/obj_mac.h>
11 #include <openssl/pem.h>
12 #include <openssl/sha.h>
13 #include <openssl/ssl.h>
14 #include <openssl/x509v3.h>
16 #include "base/memory/singleton.h"
17 #include "base/pickle.h"
18 #include "base/sha1.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "crypto/openssl_util.h"
22 #include "crypto/scoped_openssl_types.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_util.h"
25 #include "net/cert/x509_util_openssl.h"
27 #if defined(OS_ANDROID)
28 #include "base/logging.h"
29 #include "net/android/network_library.h"
36 typedef crypto::ScopedOpenSSL
<GENERAL_NAMES
, GENERAL_NAMES_free
>::Type
39 void CreateOSCertHandlesFromPKCS7Bytes(
40 const char* data
, int length
,
41 X509Certificate::OSCertHandles
* handles
) {
42 crypto::EnsureOpenSSLInit();
43 crypto::OpenSSLErrStackTracer
err_cleaner(FROM_HERE
);
46 CBS_init(&der_data
, reinterpret_cast<const uint8_t*>(data
), length
);
47 STACK_OF(X509
)* certs
= sk_X509_new_null();
49 if (PKCS7_get_certificates(certs
, &der_data
)) {
50 for (size_t i
= 0; i
< sk_X509_num(certs
); ++i
) {
52 X509Certificate::DupOSCertHandle(sk_X509_value(certs
, i
));
53 handles
->push_back(x509_cert
);
56 sk_X509_pop_free(certs
, X509_free
);
59 void ParsePrincipalValues(X509_NAME
* name
,
61 std::vector
<std::string
>* fields
) {
63 (index
= X509_NAME_get_index_by_NID(name
, nid
, index
)) != -1;) {
65 if (!x509_util::ParsePrincipalValueByIndex(name
, index
, &field
))
67 fields
->push_back(field
);
71 void ParsePrincipal(X509Certificate::OSCertHandle cert
,
73 CertPrincipal
* principal
) {
77 ParsePrincipalValues(x509_name
, NID_streetAddress
,
78 &principal
->street_addresses
);
79 ParsePrincipalValues(x509_name
, NID_organizationName
,
80 &principal
->organization_names
);
81 ParsePrincipalValues(x509_name
, NID_organizationalUnitName
,
82 &principal
->organization_unit_names
);
83 ParsePrincipalValues(x509_name
, NID_domainComponent
,
84 &principal
->domain_components
);
86 x509_util::ParsePrincipalValueByNID(x509_name
, NID_commonName
,
87 &principal
->common_name
);
88 x509_util::ParsePrincipalValueByNID(x509_name
, NID_localityName
,
89 &principal
->locality_name
);
90 x509_util::ParsePrincipalValueByNID(x509_name
, NID_stateOrProvinceName
,
91 &principal
->state_or_province_name
);
92 x509_util::ParsePrincipalValueByNID(x509_name
, NID_countryName
,
93 &principal
->country_name
);
96 void ParseSubjectAltName(X509Certificate::OSCertHandle cert
,
97 std::vector
<std::string
>* dns_names
,
98 std::vector
<std::string
>* ip_addresses
) {
99 DCHECK(dns_names
|| ip_addresses
);
100 int index
= X509_get_ext_by_NID(cert
, NID_subject_alt_name
, -1);
101 X509_EXTENSION
* alt_name_ext
= X509_get_ext(cert
, index
);
105 ScopedGENERAL_NAMES
alt_names(
106 reinterpret_cast<GENERAL_NAMES
*>(X509V3_EXT_d2i(alt_name_ext
)));
107 if (!alt_names
.get())
110 for (size_t i
= 0; i
< sk_GENERAL_NAME_num(alt_names
.get()); ++i
) {
111 const GENERAL_NAME
* name
= sk_GENERAL_NAME_value(alt_names
.get(), i
);
112 if (name
->type
== GEN_DNS
&& dns_names
) {
113 const unsigned char* dns_name
= ASN1_STRING_data(name
->d
.dNSName
);
116 int dns_name_len
= ASN1_STRING_length(name
->d
.dNSName
);
117 dns_names
->push_back(
118 std::string(reinterpret_cast<const char*>(dns_name
), dns_name_len
));
119 } else if (name
->type
== GEN_IPADD
&& ip_addresses
) {
120 const unsigned char* ip_addr
= name
->d
.iPAddress
->data
;
123 int ip_addr_len
= name
->d
.iPAddress
->length
;
124 if (ip_addr_len
!= static_cast<int>(kIPv4AddressSize
) &&
125 ip_addr_len
!= static_cast<int>(kIPv6AddressSize
)) {
126 // http://www.ietf.org/rfc/rfc3280.txt requires subjectAltName iPAddress
127 // to have 4 or 16 bytes, whereas in a name constraint it includes a
128 // net mask hence 8 or 32 bytes. Logging to help diagnose any mixup.
129 LOG(WARNING
) << "Bad sized IP Address in cert: " << ip_addr_len
;
132 ip_addresses
->push_back(
133 std::string(reinterpret_cast<const char*>(ip_addr
), ip_addr_len
));
143 void DERCache_free(void* parent
, void* ptr
, CRYPTO_EX_DATA
* ad
, int idx
,
144 long argl
, void* argp
) {
145 DERCache
* der_cache
= static_cast<DERCache
*>(ptr
);
149 OPENSSL_free(der_cache
->data
);
150 OPENSSL_free(der_cache
);
153 class X509InitSingleton
{
155 static X509InitSingleton
* GetInstance() {
156 // We allow the X509 store to leak, because it is used from a non-joinable
157 // worker that is not stopped on shutdown, hence may still be using
158 // OpenSSL library after the AtExit runner has completed.
159 return Singleton
<X509InitSingleton
,
160 LeakySingletonTraits
<X509InitSingleton
> >::get();
162 int der_cache_ex_index() const { return der_cache_ex_index_
; }
163 X509_STORE
* store() const { return store_
.get(); }
165 void ResetCertStore() {
166 store_
.reset(X509_STORE_new());
167 DCHECK(store_
.get());
168 X509_STORE_set_default_paths(store_
.get());
169 // TODO(joth): Enable CRL (see X509_STORE_set_flags(X509_V_FLAG_CRL_CHECK)).
173 friend struct DefaultSingletonTraits
<X509InitSingleton
>;
174 X509InitSingleton() {
175 crypto::EnsureOpenSSLInit();
176 der_cache_ex_index_
= X509_get_ex_new_index(0, 0, 0, 0, DERCache_free
);
177 DCHECK_NE(der_cache_ex_index_
, -1);
181 int der_cache_ex_index_
;
182 crypto::ScopedOpenSSL
<X509_STORE
, X509_STORE_free
>::Type store_
;
184 DISALLOW_COPY_AND_ASSIGN(X509InitSingleton
);
187 // Takes ownership of |data| (which must have been allocated by OpenSSL).
188 DERCache
* SetDERCache(X509Certificate::OSCertHandle cert
,
189 int x509_der_cache_index
,
192 DERCache
* internal_cache
= static_cast<DERCache
*>(
193 OPENSSL_malloc(sizeof(*internal_cache
)));
194 if (!internal_cache
) {
195 // We took ownership of |data|, so we must free if we can't add it to
201 internal_cache
->data
= data
;
202 internal_cache
->data_length
= data_length
;
203 X509_set_ex_data(cert
, x509_der_cache_index
, internal_cache
);
204 return internal_cache
;
207 // Returns true if |der_cache| points to valid data, false otherwise.
208 // (note: the DER-encoded data in |der_cache| is owned by |cert|, callers should
210 bool GetDERAndCacheIfNeeded(X509Certificate::OSCertHandle cert
,
211 DERCache
* der_cache
) {
212 int x509_der_cache_index
=
213 X509InitSingleton::GetInstance()->der_cache_ex_index();
215 // Re-encoding the DER data via i2d_X509 is an expensive operation, but it's
216 // necessary for comparing two certificates. We re-encode at most once per
217 // certificate and cache the data within the X509 cert using X509_set_ex_data.
218 DERCache
* internal_cache
= static_cast<DERCache
*>(
219 X509_get_ex_data(cert
, x509_der_cache_index
));
220 if (!internal_cache
) {
221 unsigned char* data
= NULL
;
222 int data_length
= i2d_X509(cert
, &data
);
223 if (data_length
<= 0 || !data
)
225 internal_cache
= SetDERCache(cert
, x509_der_cache_index
, data
, data_length
);
229 *der_cache
= *internal_cache
;
233 // Used to free a list of X509_NAMEs and the objects it points to.
234 void sk_X509_NAME_free_all(STACK_OF(X509_NAME
)* sk
) {
235 sk_X509_NAME_pop_free(sk
, X509_NAME_free
);
241 X509Certificate::OSCertHandle
X509Certificate::DupOSCertHandle(
242 OSCertHandle cert_handle
) {
244 return X509_up_ref(cert_handle
);
248 void X509Certificate::FreeOSCertHandle(OSCertHandle cert_handle
) {
249 // Decrement the ref-count for the cert and, if all references are gone,
250 // free the memory and any application-specific data associated with the
252 X509_free(cert_handle
);
255 void X509Certificate::Initialize() {
256 crypto::EnsureOpenSSLInit();
257 fingerprint_
= CalculateFingerprint(cert_handle_
);
258 ca_fingerprint_
= CalculateCAFingerprint(intermediate_ca_certs_
);
260 ASN1_INTEGER
* serial_num
= X509_get_serialNumber(cert_handle_
);
262 // ASN1_INTEGERS represent the decoded number, in a format internal to
263 // OpenSSL. Most notably, this may have leading zeroes stripped off for
264 // numbers whose first byte is >= 0x80. Thus, it is necessary to
265 // re-encoded the integer back into DER, which is what the interface
266 // of X509Certificate exposes, to ensure callers get the proper (DER)
268 int bytes_required
= i2c_ASN1_INTEGER(serial_num
, NULL
);
269 unsigned char* buffer
= reinterpret_cast<unsigned char*>(
270 WriteInto(&serial_number_
, bytes_required
+ 1));
271 int bytes_written
= i2c_ASN1_INTEGER(serial_num
, &buffer
);
272 DCHECK_EQ(static_cast<size_t>(bytes_written
), serial_number_
.size());
275 ParsePrincipal(cert_handle_
, X509_get_subject_name(cert_handle_
), &subject_
);
276 ParsePrincipal(cert_handle_
, X509_get_issuer_name(cert_handle_
), &issuer_
);
277 x509_util::ParseDate(X509_get_notBefore(cert_handle_
), &valid_start_
);
278 x509_util::ParseDate(X509_get_notAfter(cert_handle_
), &valid_expiry_
);
282 void X509Certificate::ResetCertStore() {
283 X509InitSingleton::GetInstance()->ResetCertStore();
287 SHA1HashValue
X509Certificate::CalculateFingerprint(OSCertHandle cert
) {
289 unsigned int sha1_size
= static_cast<unsigned int>(sizeof(sha1
.data
));
290 int ret
= X509_digest(cert
, EVP_sha1(), sha1
.data
, &sha1_size
);
292 CHECK_EQ(sha1_size
, sizeof(sha1
.data
));
297 SHA1HashValue
X509Certificate::CalculateCAFingerprint(
298 const OSCertHandles
& intermediates
) {
300 memset(sha1
.data
, 0, sizeof(sha1
.data
));
303 SHA1_Init(&sha1_ctx
);
305 for (size_t i
= 0; i
< intermediates
.size(); ++i
) {
306 if (!GetDERAndCacheIfNeeded(intermediates
[i
], &der_cache
))
308 SHA1_Update(&sha1_ctx
, der_cache
.data
, der_cache
.data_length
);
310 SHA1_Final(sha1
.data
, &sha1_ctx
);
316 X509Certificate::OSCertHandle
X509Certificate::CreateOSCertHandleFromBytes(
317 const char* data
, int length
) {
320 crypto::EnsureOpenSSLInit();
321 const unsigned char* d2i_data
=
322 reinterpret_cast<const unsigned char*>(data
);
323 // Don't cache this data via SetDERCache as this wire format may be not be
324 // identical from the i2d_X509 roundtrip.
325 X509
* cert
= d2i_X509(NULL
, &d2i_data
, length
);
330 X509Certificate::OSCertHandles
X509Certificate::CreateOSCertHandlesFromBytes(
331 const char* data
, int length
, Format format
) {
332 OSCertHandles results
;
337 case FORMAT_SINGLE_CERTIFICATE
: {
338 OSCertHandle handle
= CreateOSCertHandleFromBytes(data
, length
);
340 results
.push_back(handle
);
344 CreateOSCertHandlesFromPKCS7Bytes(data
, length
, &results
);
348 NOTREACHED() << "Certificate format " << format
<< " unimplemented";
356 void X509Certificate::GetSubjectAltName(
357 std::vector
<std::string
>* dns_names
,
358 std::vector
<std::string
>* ip_addrs
) const {
364 ParseSubjectAltName(cert_handle_
, dns_names
, ip_addrs
);
368 X509_STORE
* X509Certificate::cert_store() {
369 return X509InitSingleton::GetInstance()->store();
373 bool X509Certificate::GetDEREncoded(X509Certificate::OSCertHandle cert_handle
,
374 std::string
* encoded
) {
376 if (!GetDERAndCacheIfNeeded(cert_handle
, &der_cache
))
378 encoded
->assign(reinterpret_cast<const char*>(der_cache
.data
),
379 der_cache
.data_length
);
384 bool X509Certificate::IsSameOSCert(X509Certificate::OSCertHandle a
,
385 X509Certificate::OSCertHandle b
) {
390 // X509_cmp only checks the fingerprint, but we want to compare the whole
391 // DER data. Encoding it from OSCertHandle is an expensive operation, so we
392 // cache the DER (if not already cached via X509_set_ex_data).
393 DERCache der_cache_a
, der_cache_b
;
395 return GetDERAndCacheIfNeeded(a
, &der_cache_a
) &&
396 GetDERAndCacheIfNeeded(b
, &der_cache_b
) &&
397 der_cache_a
.data_length
== der_cache_b
.data_length
&&
398 memcmp(der_cache_a
.data
, der_cache_b
.data
, der_cache_a
.data_length
) == 0;
402 X509Certificate::OSCertHandle
403 X509Certificate::ReadOSCertHandleFromPickle(PickleIterator
* pickle_iter
) {
406 if (!pickle_iter
->ReadData(&data
, &length
))
409 return CreateOSCertHandleFromBytes(data
, length
);
413 bool X509Certificate::WriteOSCertHandleToPickle(OSCertHandle cert_handle
,
416 if (!GetDERAndCacheIfNeeded(cert_handle
, &der_cache
))
419 return pickle
->WriteData(
420 reinterpret_cast<const char*>(der_cache
.data
),
421 der_cache
.data_length
);
425 void X509Certificate::GetPublicKeyInfo(OSCertHandle cert_handle
,
427 PublicKeyType
* type
) {
428 *type
= kPublicKeyTypeUnknown
;
431 crypto::ScopedEVP_PKEY
scoped_key(X509_get_pubkey(cert_handle
));
432 if (!scoped_key
.get())
435 CHECK(scoped_key
.get());
436 EVP_PKEY
* key
= scoped_key
.get();
440 *type
= kPublicKeyTypeRSA
;
441 *size_bits
= EVP_PKEY_size(key
) * 8;
444 *type
= kPublicKeyTypeDSA
;
445 *size_bits
= EVP_PKEY_size(key
) * 8;
448 *type
= kPublicKeyTypeECDSA
;
449 *size_bits
= EVP_PKEY_bits(key
);
452 *type
= kPublicKeyTypeDH
;
453 *size_bits
= EVP_PKEY_size(key
) * 8;
458 bool X509Certificate::IsIssuedByEncoded(
459 const std::vector
<std::string
>& valid_issuers
) {
460 if (valid_issuers
.empty())
463 // Convert to a temporary list of X509_NAME objects.
464 // It will own the objects it points to.
465 crypto::ScopedOpenSSL
<STACK_OF(X509_NAME
), sk_X509_NAME_free_all
>::Type
466 issuer_names(sk_X509_NAME_new_null());
467 if (!issuer_names
.get())
470 for (std::vector
<std::string
>::const_iterator it
= valid_issuers
.begin();
471 it
!= valid_issuers
.end(); ++it
) {
472 const unsigned char* p
=
473 reinterpret_cast<const unsigned char*>(it
->data());
474 long len
= static_cast<long>(it
->length());
475 X509_NAME
* ca_name
= d2i_X509_NAME(NULL
, &p
, len
);
478 sk_X509_NAME_push(issuer_names
.get(), ca_name
);
481 // Create a temporary list of X509_NAME objects corresponding
482 // to the certificate chain. It doesn't own the object it points to.
483 std::vector
<X509_NAME
*> cert_names
;
484 X509_NAME
* issuer
= X509_get_issuer_name(cert_handle_
);
488 cert_names
.push_back(issuer
);
489 for (OSCertHandles::iterator it
= intermediate_ca_certs_
.begin();
490 it
!= intermediate_ca_certs_
.end(); ++it
) {
491 issuer
= X509_get_issuer_name(*it
);
494 cert_names
.push_back(issuer
);
498 for (size_t n
= 0; n
< cert_names
.size(); ++n
) {
499 for (size_t m
= 0; m
< sk_X509_NAME_num(issuer_names
.get()); ++m
) {
500 X509_NAME
* issuer
= sk_X509_NAME_value(issuer_names
.get(), m
);
501 if (X509_NAME_cmp(issuer
, cert_names
[n
]) == 0) {