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/crypto.h>
9 #include <openssl/obj_mac.h>
10 #include <openssl/pem.h>
11 #include <openssl/pkcs7.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/string_number_conversions.h"
20 #include "base/string_util.h"
21 #include "crypto/openssl_util.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/net_util.h"
24 #include "net/cert/x509_util_openssl.h"
26 #if defined(OS_ANDROID)
27 #include "base/logging.h"
28 #include "net/android/network_library.h"
35 void CreateOSCertHandlesFromPKCS7Bytes(
36 const char* data
, int length
,
37 X509Certificate::OSCertHandles
* handles
) {
38 crypto::EnsureOpenSSLInit();
39 const unsigned char* der_data
= reinterpret_cast<const unsigned char*>(data
);
40 crypto::ScopedOpenSSL
<PKCS7
, PKCS7_free
> pkcs7_cert(
41 d2i_PKCS7(NULL
, &der_data
, length
));
42 if (!pkcs7_cert
.get())
45 STACK_OF(X509
)* certs
= NULL
;
46 int nid
= OBJ_obj2nid(pkcs7_cert
.get()->type
);
47 if (nid
== NID_pkcs7_signed
) {
48 certs
= pkcs7_cert
.get()->d
.sign
->cert
;
49 } else if (nid
== NID_pkcs7_signedAndEnveloped
) {
50 certs
= pkcs7_cert
.get()->d
.signed_and_enveloped
->cert
;
54 for (int i
= 0; i
< sk_X509_num(certs
); ++i
) {
56 X509Certificate::DupOSCertHandle(sk_X509_value(certs
, i
));
57 handles
->push_back(x509_cert
);
62 void ParsePrincipalValues(X509_NAME
* name
,
64 std::vector
<std::string
>* fields
) {
66 (index
= X509_NAME_get_index_by_NID(name
, nid
, index
)) != -1;) {
68 if (!x509_util::ParsePrincipalValueByIndex(name
, index
, &field
))
70 fields
->push_back(field
);
74 void ParsePrincipal(X509Certificate::OSCertHandle cert
,
76 CertPrincipal
* principal
) {
80 ParsePrincipalValues(x509_name
, NID_streetAddress
,
81 &principal
->street_addresses
);
82 ParsePrincipalValues(x509_name
, NID_organizationName
,
83 &principal
->organization_names
);
84 ParsePrincipalValues(x509_name
, NID_organizationalUnitName
,
85 &principal
->organization_unit_names
);
86 ParsePrincipalValues(x509_name
, NID_domainComponent
,
87 &principal
->domain_components
);
89 x509_util::ParsePrincipalValueByNID(x509_name
, NID_commonName
,
90 &principal
->common_name
);
91 x509_util::ParsePrincipalValueByNID(x509_name
, NID_localityName
,
92 &principal
->locality_name
);
93 x509_util::ParsePrincipalValueByNID(x509_name
, NID_stateOrProvinceName
,
94 &principal
->state_or_province_name
);
95 x509_util::ParsePrincipalValueByNID(x509_name
, NID_countryName
,
96 &principal
->country_name
);
99 void ParseSubjectAltName(X509Certificate::OSCertHandle cert
,
100 std::vector
<std::string
>* dns_names
,
101 std::vector
<std::string
>* ip_addresses
) {
102 DCHECK(dns_names
|| ip_addresses
);
103 int index
= X509_get_ext_by_NID(cert
, NID_subject_alt_name
, -1);
104 X509_EXTENSION
* alt_name_ext
= X509_get_ext(cert
, index
);
108 crypto::ScopedOpenSSL
<GENERAL_NAMES
, GENERAL_NAMES_free
> alt_names(
109 reinterpret_cast<GENERAL_NAMES
*>(X509V3_EXT_d2i(alt_name_ext
)));
110 if (!alt_names
.get())
113 for (int i
= 0; i
< sk_GENERAL_NAME_num(alt_names
.get()); ++i
) {
114 const GENERAL_NAME
* name
= sk_GENERAL_NAME_value(alt_names
.get(), i
);
115 if (name
->type
== GEN_DNS
&& dns_names
) {
116 const unsigned char* dns_name
= ASN1_STRING_data(name
->d
.dNSName
);
119 int dns_name_len
= ASN1_STRING_length(name
->d
.dNSName
);
120 dns_names
->push_back(
121 std::string(reinterpret_cast<const char*>(dns_name
), dns_name_len
));
122 } else if (name
->type
== GEN_IPADD
&& ip_addresses
) {
123 const unsigned char* ip_addr
= name
->d
.iPAddress
->data
;
126 int ip_addr_len
= name
->d
.iPAddress
->length
;
127 if (ip_addr_len
!= static_cast<int>(kIPv4AddressSize
) &&
128 ip_addr_len
!= static_cast<int>(kIPv6AddressSize
)) {
129 // http://www.ietf.org/rfc/rfc3280.txt requires subjectAltName iPAddress
130 // to have 4 or 16 bytes, whereas in a name constraint it includes a
131 // net mask hence 8 or 32 bytes. Logging to help diagnose any mixup.
132 LOG(WARNING
) << "Bad sized IP Address in cert: " << ip_addr_len
;
135 ip_addresses
->push_back(
136 std::string(reinterpret_cast<const char*>(ip_addr
), ip_addr_len
));
146 void DERCache_free(void* parent
, void* ptr
, CRYPTO_EX_DATA
* ad
, int idx
,
147 long argl
, void* argp
) {
148 DERCache
* der_cache
= static_cast<DERCache
*>(ptr
);
152 OPENSSL_free(der_cache
->data
);
153 OPENSSL_free(der_cache
);
156 class X509InitSingleton
{
158 static X509InitSingleton
* GetInstance() {
159 // We allow the X509 store to leak, because it is used from a non-joinable
160 // worker that is not stopped on shutdown, hence may still be using
161 // OpenSSL library after the AtExit runner has completed.
162 return Singleton
<X509InitSingleton
,
163 LeakySingletonTraits
<X509InitSingleton
> >::get();
165 int der_cache_ex_index() const { return der_cache_ex_index_
; }
166 X509_STORE
* store() const { return store_
.get(); }
168 void ResetCertStore() {
169 store_
.reset(X509_STORE_new());
170 DCHECK(store_
.get());
171 X509_STORE_set_default_paths(store_
.get());
172 // TODO(joth): Enable CRL (see X509_STORE_set_flags(X509_V_FLAG_CRL_CHECK)).
176 friend struct DefaultSingletonTraits
<X509InitSingleton
>;
177 X509InitSingleton() {
178 crypto::EnsureOpenSSLInit();
179 der_cache_ex_index_
= X509_get_ex_new_index(0, 0, 0, 0, DERCache_free
);
180 DCHECK_NE(der_cache_ex_index_
, -1);
184 int der_cache_ex_index_
;
185 crypto::ScopedOpenSSL
<X509_STORE
, X509_STORE_free
> store_
;
187 DISALLOW_COPY_AND_ASSIGN(X509InitSingleton
);
190 // Takes ownership of |data| (which must have been allocated by OpenSSL).
191 DERCache
* SetDERCache(X509Certificate::OSCertHandle cert
,
192 int x509_der_cache_index
,
195 DERCache
* internal_cache
= static_cast<DERCache
*>(
196 OPENSSL_malloc(sizeof(*internal_cache
)));
197 if (!internal_cache
) {
198 // We took ownership of |data|, so we must free if we can't add it to
204 internal_cache
->data
= data
;
205 internal_cache
->data_length
= data_length
;
206 X509_set_ex_data(cert
, x509_der_cache_index
, internal_cache
);
207 return internal_cache
;
210 // Returns true if |der_cache| points to valid data, false otherwise.
211 // (note: the DER-encoded data in |der_cache| is owned by |cert|, callers should
213 bool GetDERAndCacheIfNeeded(X509Certificate::OSCertHandle cert
,
214 DERCache
* der_cache
) {
215 int x509_der_cache_index
=
216 X509InitSingleton::GetInstance()->der_cache_ex_index();
218 // Re-encoding the DER data via i2d_X509 is an expensive operation, but it's
219 // necessary for comparing two certificates. We re-encode at most once per
220 // certificate and cache the data within the X509 cert using X509_set_ex_data.
221 DERCache
* internal_cache
= static_cast<DERCache
*>(
222 X509_get_ex_data(cert
, x509_der_cache_index
));
223 if (!internal_cache
) {
224 unsigned char* data
= NULL
;
225 int data_length
= i2d_X509(cert
, &data
);
226 if (data_length
<= 0 || !data
)
228 internal_cache
= SetDERCache(cert
, x509_der_cache_index
, data
, data_length
);
232 *der_cache
= *internal_cache
;
236 // Used to free a list of X509_NAMEs and the objects it points to.
237 void sk_X509_NAME_free_all(STACK_OF(X509_NAME
)* sk
) {
238 sk_X509_NAME_pop_free(sk
, X509_NAME_free
);
244 X509Certificate::OSCertHandle
X509Certificate::DupOSCertHandle(
245 OSCertHandle cert_handle
) {
247 // Using X509_dup causes the entire certificate to be reparsed. This
248 // conversion, besides being non-trivial, drops any associated
249 // application-specific data set by X509_set_ex_data. Using CRYPTO_add
250 // just bumps up the ref-count for the cert, without causing any allocations
252 CRYPTO_add(&cert_handle
->references
, 1, CRYPTO_LOCK_X509
);
257 void X509Certificate::FreeOSCertHandle(OSCertHandle cert_handle
) {
258 // Decrement the ref-count for the cert and, if all references are gone,
259 // free the memory and any application-specific data associated with the
261 X509_free(cert_handle
);
264 void X509Certificate::Initialize() {
265 crypto::EnsureOpenSSLInit();
266 fingerprint_
= CalculateFingerprint(cert_handle_
);
267 ca_fingerprint_
= CalculateCAFingerprint(intermediate_ca_certs_
);
269 ASN1_INTEGER
* serial_num
= X509_get_serialNumber(cert_handle_
);
271 // ASN1_INTEGERS represent the decoded number, in a format internal to
272 // OpenSSL. Most notably, this may have leading zeroes stripped off for
273 // numbers whose first byte is >= 0x80. Thus, it is necessary to
274 // re-encoded the integer back into DER, which is what the interface
275 // of X509Certificate exposes, to ensure callers get the proper (DER)
277 int bytes_required
= i2c_ASN1_INTEGER(serial_num
, NULL
);
278 unsigned char* buffer
= reinterpret_cast<unsigned char*>(
279 WriteInto(&serial_number_
, bytes_required
+ 1));
280 int bytes_written
= i2c_ASN1_INTEGER(serial_num
, &buffer
);
281 DCHECK_EQ(static_cast<size_t>(bytes_written
), serial_number_
.size());
284 ParsePrincipal(cert_handle_
, X509_get_subject_name(cert_handle_
), &subject_
);
285 ParsePrincipal(cert_handle_
, X509_get_issuer_name(cert_handle_
), &issuer_
);
286 x509_util::ParseDate(X509_get_notBefore(cert_handle_
), &valid_start_
);
287 x509_util::ParseDate(X509_get_notAfter(cert_handle_
), &valid_expiry_
);
291 void X509Certificate::ResetCertStore() {
292 X509InitSingleton::GetInstance()->ResetCertStore();
296 SHA1HashValue
X509Certificate::CalculateFingerprint(OSCertHandle cert
) {
298 unsigned int sha1_size
= static_cast<unsigned int>(sizeof(sha1
.data
));
299 int ret
= X509_digest(cert
, EVP_sha1(), sha1
.data
, &sha1_size
);
301 CHECK_EQ(sha1_size
, sizeof(sha1
.data
));
306 SHA1HashValue
X509Certificate::CalculateCAFingerprint(
307 const OSCertHandles
& intermediates
) {
309 memset(sha1
.data
, 0, sizeof(sha1
.data
));
312 SHA1_Init(&sha1_ctx
);
314 for (size_t i
= 0; i
< intermediates
.size(); ++i
) {
315 if (!GetDERAndCacheIfNeeded(intermediates
[i
], &der_cache
))
317 SHA1_Update(&sha1_ctx
, der_cache
.data
, der_cache
.data_length
);
319 SHA1_Final(sha1
.data
, &sha1_ctx
);
325 X509Certificate::OSCertHandle
X509Certificate::CreateOSCertHandleFromBytes(
326 const char* data
, int length
) {
329 crypto::EnsureOpenSSLInit();
330 const unsigned char* d2i_data
=
331 reinterpret_cast<const unsigned char*>(data
);
332 // Don't cache this data via SetDERCache as this wire format may be not be
333 // identical from the i2d_X509 roundtrip.
334 X509
* cert
= d2i_X509(NULL
, &d2i_data
, length
);
339 X509Certificate::OSCertHandles
X509Certificate::CreateOSCertHandlesFromBytes(
340 const char* data
, int length
, Format format
) {
341 OSCertHandles results
;
346 case FORMAT_SINGLE_CERTIFICATE
: {
347 OSCertHandle handle
= CreateOSCertHandleFromBytes(data
, length
);
349 results
.push_back(handle
);
353 CreateOSCertHandlesFromPKCS7Bytes(data
, length
, &results
);
357 NOTREACHED() << "Certificate format " << format
<< " unimplemented";
366 X509Certificate
* X509Certificate::CreateSelfSigned(
367 crypto::RSAPrivateKey
* key
,
368 const std::string
& subject
,
369 uint32 serial_number
,
370 base::TimeDelta valid_duration
) {
371 // TODO(port): Implement. See http://crbug.com/91512.
376 void X509Certificate::GetSubjectAltName(
377 std::vector
<std::string
>* dns_names
,
378 std::vector
<std::string
>* ip_addrs
) const {
384 ParseSubjectAltName(cert_handle_
, dns_names
, ip_addrs
);
388 X509_STORE
* X509Certificate::cert_store() {
389 return X509InitSingleton::GetInstance()->store();
393 bool X509Certificate::GetDEREncoded(X509Certificate::OSCertHandle cert_handle
,
394 std::string
* encoded
) {
396 if (!GetDERAndCacheIfNeeded(cert_handle
, &der_cache
))
398 encoded
->assign(reinterpret_cast<const char*>(der_cache
.data
),
399 der_cache
.data_length
);
404 bool X509Certificate::IsSameOSCert(X509Certificate::OSCertHandle a
,
405 X509Certificate::OSCertHandle b
) {
410 // X509_cmp only checks the fingerprint, but we want to compare the whole
411 // DER data. Encoding it from OSCertHandle is an expensive operation, so we
412 // cache the DER (if not already cached via X509_set_ex_data).
413 DERCache der_cache_a
, der_cache_b
;
415 return GetDERAndCacheIfNeeded(a
, &der_cache_a
) &&
416 GetDERAndCacheIfNeeded(b
, &der_cache_b
) &&
417 der_cache_a
.data_length
== der_cache_b
.data_length
&&
418 memcmp(der_cache_a
.data
, der_cache_b
.data
, der_cache_a
.data_length
) == 0;
422 X509Certificate::OSCertHandle
423 X509Certificate::ReadOSCertHandleFromPickle(PickleIterator
* pickle_iter
) {
426 if (!pickle_iter
->ReadData(&data
, &length
))
429 return CreateOSCertHandleFromBytes(data
, length
);
433 bool X509Certificate::WriteOSCertHandleToPickle(OSCertHandle cert_handle
,
436 if (!GetDERAndCacheIfNeeded(cert_handle
, &der_cache
))
439 return pickle
->WriteData(
440 reinterpret_cast<const char*>(der_cache
.data
),
441 der_cache
.data_length
);
445 void X509Certificate::GetPublicKeyInfo(OSCertHandle cert_handle
,
447 PublicKeyType
* type
) {
448 *type
= kPublicKeyTypeUnknown
;
451 crypto::ScopedOpenSSL
<EVP_PKEY
, EVP_PKEY_free
> scoped_key(
452 X509_get_pubkey(cert_handle
));
453 if (!scoped_key
.get())
456 CHECK(scoped_key
.get());
457 EVP_PKEY
* key
= scoped_key
.get();
461 *type
= kPublicKeyTypeRSA
;
462 *size_bits
= EVP_PKEY_size(key
) * 8;
465 *type
= kPublicKeyTypeDSA
;
466 *size_bits
= EVP_PKEY_size(key
) * 8;
469 *type
= kPublicKeyTypeECDSA
;
470 *size_bits
= EVP_PKEY_size(key
);
473 *type
= kPublicKeyTypeDH
;
474 *size_bits
= EVP_PKEY_size(key
) * 8;
479 bool X509Certificate::IsIssuedByEncoded(
480 const std::vector
<std::string
>& valid_issuers
) {
481 if (valid_issuers
.empty())
484 // Convert to a temporary list of X509_NAME objects.
485 // It will own the objects it points to.
486 crypto::ScopedOpenSSL
<STACK_OF(X509_NAME
), sk_X509_NAME_free_all
>
487 issuer_names(sk_X509_NAME_new_null());
488 if (!issuer_names
.get())
491 for (std::vector
<std::string
>::const_iterator it
= valid_issuers
.begin();
492 it
!= valid_issuers
.end(); ++it
) {
493 const unsigned char* p
=
494 reinterpret_cast<const unsigned char*>(it
->data());
495 long len
= static_cast<long>(it
->length());
496 X509_NAME
* ca_name
= d2i_X509_NAME(NULL
, &p
, len
);
499 sk_X509_NAME_push(issuer_names
.get(), ca_name
);
502 // Create a temporary list of X509_NAME objects corresponding
503 // to the certificate chain. It doesn't own the object it points to.
504 std::vector
<X509_NAME
*> cert_names
;
505 X509_NAME
* issuer
= X509_get_issuer_name(cert_handle_
);
509 cert_names
.push_back(issuer
);
510 for (OSCertHandles::iterator it
= intermediate_ca_certs_
.begin();
511 it
!= intermediate_ca_certs_
.end(); ++it
) {
512 issuer
= X509_get_issuer_name(*it
);
515 cert_names
.push_back(issuer
);
519 for (size_t n
= 0; n
< cert_names
.size(); ++n
) {
520 for (int m
= 0; m
< sk_X509_NAME_num(issuer_names
.get()); ++m
) {
521 X509_NAME
* issuer
= sk_X509_NAME_value(issuer_names
.get(), m
);
522 if (X509_NAME_cmp(issuer
, cert_names
[n
]) == 0) {