Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / net / cert / x509_certificate_openssl.cc
blobfdd0e48d8551eef12623ea3e7d3b397d039147de
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"
30 #endif
32 namespace net {
34 namespace {
36 typedef crypto::ScopedOpenSSL<GENERAL_NAMES, GENERAL_NAMES_free>::Type
37 ScopedGENERAL_NAMES;
39 void CreateOSCertHandlesFromPKCS7Bytes(
40 const char* data, int length,
41 X509Certificate::OSCertHandles* handles) {
42 crypto::EnsureOpenSSLInit();
43 crypto::OpenSSLErrStackTracer err_cleaner(FROM_HERE);
45 CBS der_data;
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) {
51 X509* x509_cert =
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,
60 int nid,
61 std::vector<std::string>* fields) {
62 for (int index = -1;
63 (index = X509_NAME_get_index_by_NID(name, nid, index)) != -1;) {
64 std::string field;
65 if (!x509_util::ParsePrincipalValueByIndex(name, index, &field))
66 break;
67 fields->push_back(field);
71 void ParsePrincipal(X509Certificate::OSCertHandle cert,
72 X509_NAME* x509_name,
73 CertPrincipal* principal) {
74 if (!x509_name)
75 return;
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);
102 if (!alt_name_ext)
103 return;
105 ScopedGENERAL_NAMES alt_names(
106 reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(alt_name_ext)));
107 if (!alt_names.get())
108 return;
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);
114 if (!dns_name)
115 continue;
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;
121 if (!ip_addr)
122 continue;
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;
130 continue;
132 ip_addresses->push_back(
133 std::string(reinterpret_cast<const char*>(ip_addr), ip_addr_len));
138 struct DERCache {
139 unsigned char* data;
140 int data_length;
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);
146 if (!der_cache)
147 return;
148 if (der_cache->data)
149 OPENSSL_free(der_cache->data);
150 OPENSSL_free(der_cache);
153 class X509InitSingleton {
154 public:
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)).
172 private:
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);
178 ResetCertStore();
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,
190 unsigned char* data,
191 int data_length) {
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
196 // |cert|.
197 OPENSSL_free(data);
198 return NULL;
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
209 // not free it).
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)
224 return false;
225 internal_cache = SetDERCache(cert, x509_der_cache_index, data, data_length);
226 if (!internal_cache)
227 return false;
229 *der_cache = *internal_cache;
230 return true;
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);
238 } // namespace
240 // static
241 X509Certificate::OSCertHandle X509Certificate::DupOSCertHandle(
242 OSCertHandle cert_handle) {
243 DCHECK(cert_handle);
244 return X509_up_ref(cert_handle);
247 // static
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
251 // certificate.
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_);
261 if (serial_num) {
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)
267 // value.
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_);
281 // static
282 void X509Certificate::ResetCertStore() {
283 X509InitSingleton::GetInstance()->ResetCertStore();
286 // static
287 SHA1HashValue X509Certificate::CalculateFingerprint(OSCertHandle cert) {
288 SHA1HashValue sha1;
289 unsigned int sha1_size = static_cast<unsigned int>(sizeof(sha1.data));
290 int ret = X509_digest(cert, EVP_sha1(), sha1.data, &sha1_size);
291 CHECK(ret);
292 CHECK_EQ(sha1_size, sizeof(sha1.data));
293 return sha1;
296 // static
297 SHA1HashValue X509Certificate::CalculateCAFingerprint(
298 const OSCertHandles& intermediates) {
299 SHA1HashValue sha1;
300 memset(sha1.data, 0, sizeof(sha1.data));
302 SHA_CTX sha1_ctx;
303 SHA1_Init(&sha1_ctx);
304 DERCache der_cache;
305 for (size_t i = 0; i < intermediates.size(); ++i) {
306 if (!GetDERAndCacheIfNeeded(intermediates[i], &der_cache))
307 return sha1;
308 SHA1_Update(&sha1_ctx, der_cache.data, der_cache.data_length);
310 SHA1_Final(sha1.data, &sha1_ctx);
312 return sha1;
315 // static
316 X509Certificate::OSCertHandle X509Certificate::CreateOSCertHandleFromBytes(
317 const char* data, int length) {
318 if (length < 0)
319 return NULL;
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);
326 return cert;
329 // static
330 X509Certificate::OSCertHandles X509Certificate::CreateOSCertHandlesFromBytes(
331 const char* data, int length, Format format) {
332 OSCertHandles results;
333 if (length < 0)
334 return results;
336 switch (format) {
337 case FORMAT_SINGLE_CERTIFICATE: {
338 OSCertHandle handle = CreateOSCertHandleFromBytes(data, length);
339 if (handle)
340 results.push_back(handle);
341 break;
343 case FORMAT_PKCS7: {
344 CreateOSCertHandlesFromPKCS7Bytes(data, length, &results);
345 break;
347 default: {
348 NOTREACHED() << "Certificate format " << format << " unimplemented";
349 break;
353 return results;
356 void X509Certificate::GetSubjectAltName(
357 std::vector<std::string>* dns_names,
358 std::vector<std::string>* ip_addrs) const {
359 if (dns_names)
360 dns_names->clear();
361 if (ip_addrs)
362 ip_addrs->clear();
364 ParseSubjectAltName(cert_handle_, dns_names, ip_addrs);
367 // static
368 X509_STORE* X509Certificate::cert_store() {
369 return X509InitSingleton::GetInstance()->store();
372 // static
373 bool X509Certificate::GetDEREncoded(X509Certificate::OSCertHandle cert_handle,
374 std::string* encoded) {
375 DERCache der_cache;
376 if (!GetDERAndCacheIfNeeded(cert_handle, &der_cache))
377 return false;
378 encoded->assign(reinterpret_cast<const char*>(der_cache.data),
379 der_cache.data_length);
380 return true;
383 // static
384 bool X509Certificate::IsSameOSCert(X509Certificate::OSCertHandle a,
385 X509Certificate::OSCertHandle b) {
386 DCHECK(a && b);
387 if (a == b)
388 return true;
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;
401 // static
402 X509Certificate::OSCertHandle
403 X509Certificate::ReadOSCertHandleFromPickle(PickleIterator* pickle_iter) {
404 const char* data;
405 int length;
406 if (!pickle_iter->ReadData(&data, &length))
407 return NULL;
409 return CreateOSCertHandleFromBytes(data, length);
412 // static
413 bool X509Certificate::WriteOSCertHandleToPickle(OSCertHandle cert_handle,
414 Pickle* pickle) {
415 DERCache der_cache;
416 if (!GetDERAndCacheIfNeeded(cert_handle, &der_cache))
417 return false;
419 return pickle->WriteData(
420 reinterpret_cast<const char*>(der_cache.data),
421 der_cache.data_length);
424 // static
425 void X509Certificate::GetPublicKeyInfo(OSCertHandle cert_handle,
426 size_t* size_bits,
427 PublicKeyType* type) {
428 *type = kPublicKeyTypeUnknown;
429 *size_bits = 0;
431 crypto::ScopedEVP_PKEY scoped_key(X509_get_pubkey(cert_handle));
432 if (!scoped_key.get())
433 return;
435 CHECK(scoped_key.get());
436 EVP_PKEY* key = scoped_key.get();
438 switch (key->type) {
439 case EVP_PKEY_RSA:
440 *type = kPublicKeyTypeRSA;
441 *size_bits = EVP_PKEY_size(key) * 8;
442 break;
443 case EVP_PKEY_DSA:
444 *type = kPublicKeyTypeDSA;
445 *size_bits = EVP_PKEY_size(key) * 8;
446 break;
447 case EVP_PKEY_EC:
448 *type = kPublicKeyTypeECDSA;
449 *size_bits = EVP_PKEY_bits(key);
450 break;
451 case EVP_PKEY_DH:
452 *type = kPublicKeyTypeDH;
453 *size_bits = EVP_PKEY_size(key) * 8;
454 break;
458 bool X509Certificate::IsIssuedByEncoded(
459 const std::vector<std::string>& valid_issuers) {
460 if (valid_issuers.empty())
461 return false;
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())
468 return false;
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);
476 if (ca_name == NULL)
477 return false;
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_);
485 if (issuer == NULL)
486 return false;
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);
492 if (issuer == NULL)
493 return false;
494 cert_names.push_back(issuer);
497 // and 'cert_names'.
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) {
502 return true;
507 return false;
510 } // namespace net