OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #include "net/base/x509_certificate.h" | |
6 | |
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> | |
15 | |
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/base/x509_util_openssl.h" | |
25 | |
26 #if defined(OS_ANDROID) | |
27 #include "base/logging.h" | |
28 #include "net/android/network_library.h" | |
29 #endif | |
30 | |
31 namespace net { | |
32 | |
33 namespace { | |
34 | |
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()) | |
43 return; | |
44 | |
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; | |
51 } | |
52 | |
53 if (certs) { | |
54 for (int i = 0; i < sk_X509_num(certs); ++i) { | |
55 X509* x509_cert = | |
56 X509Certificate::DupOSCertHandle(sk_X509_value(certs, i)); | |
57 handles->push_back(x509_cert); | |
58 } | |
59 } | |
60 } | |
61 | |
62 void ParsePrincipalValues(X509_NAME* name, | |
63 int nid, | |
64 std::vector<std::string>* fields) { | |
65 for (int index = -1; | |
66 (index = X509_NAME_get_index_by_NID(name, nid, index)) != -1;) { | |
67 std::string field; | |
68 if (!x509_util::ParsePrincipalValueByIndex(name, index, &field)) | |
69 break; | |
70 fields->push_back(field); | |
71 } | |
72 } | |
73 | |
74 void ParsePrincipal(X509Certificate::OSCertHandle cert, | |
75 X509_NAME* x509_name, | |
76 CertPrincipal* principal) { | |
77 if (!x509_name) | |
78 return; | |
79 | |
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); | |
88 | |
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); | |
97 } | |
98 | |
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); | |
105 if (!alt_name_ext) | |
106 return; | |
107 | |
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()) | |
111 return; | |
112 | |
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); | |
117 if (!dns_name) | |
118 continue; | |
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; | |
124 if (!ip_addr) | |
125 continue; | |
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; | |
133 continue; | |
134 } | |
135 ip_addresses->push_back( | |
136 std::string(reinterpret_cast<const char*>(ip_addr), ip_addr_len)); | |
137 } | |
138 } | |
139 } | |
140 | |
141 struct DERCache { | |
142 unsigned char* data; | |
143 int data_length; | |
144 }; | |
145 | |
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); | |
149 if (!der_cache) | |
150 return; | |
151 if (der_cache->data) | |
152 OPENSSL_free(der_cache->data); | |
153 OPENSSL_free(der_cache); | |
154 } | |
155 | |
156 class X509InitSingleton { | |
157 public: | |
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(); | |
164 } | |
165 int der_cache_ex_index() const { return der_cache_ex_index_; } | |
166 X509_STORE* store() const { return store_.get(); } | |
167 | |
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)). | |
173 } | |
174 | |
175 private: | |
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); | |
181 ResetCertStore(); | |
182 } | |
183 | |
184 int der_cache_ex_index_; | |
185 crypto::ScopedOpenSSL<X509_STORE, X509_STORE_free> store_; | |
186 | |
187 DISALLOW_COPY_AND_ASSIGN(X509InitSingleton); | |
188 }; | |
189 | |
190 // Takes ownership of |data| (which must have been allocated by OpenSSL). | |
191 DERCache* SetDERCache(X509Certificate::OSCertHandle cert, | |
192 int x509_der_cache_index, | |
193 unsigned char* data, | |
194 int data_length) { | |
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 | |
199 // |cert|. | |
200 OPENSSL_free(data); | |
201 return NULL; | |
202 } | |
203 | |
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; | |
208 } | |
209 | |
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 | |
212 // not free it). | |
213 bool GetDERAndCacheIfNeeded(X509Certificate::OSCertHandle cert, | |
214 DERCache* der_cache) { | |
215 int x509_der_cache_index = | |
216 X509InitSingleton::GetInstance()->der_cache_ex_index(); | |
217 | |
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) | |
227 return false; | |
228 internal_cache = SetDERCache(cert, x509_der_cache_index, data, data_length); | |
229 if (!internal_cache) | |
230 return false; | |
231 } | |
232 *der_cache = *internal_cache; | |
233 return true; | |
234 } | |
235 | |
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); | |
239 } | |
240 | |
241 } // namespace | |
242 | |
243 // static | |
244 X509Certificate::OSCertHandle X509Certificate::DupOSCertHandle( | |
245 OSCertHandle cert_handle) { | |
246 DCHECK(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 | |
251 // or deallocations. | |
252 CRYPTO_add(&cert_handle->references, 1, CRYPTO_LOCK_X509); | |
253 return cert_handle; | |
254 } | |
255 | |
256 // static | |
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 | |
260 // certificate. | |
261 X509_free(cert_handle); | |
262 } | |
263 | |
264 void X509Certificate::Initialize() { | |
265 crypto::EnsureOpenSSLInit(); | |
266 fingerprint_ = CalculateFingerprint(cert_handle_); | |
267 ca_fingerprint_ = CalculateCAFingerprint(intermediate_ca_certs_); | |
268 | |
269 ASN1_INTEGER* serial_num = X509_get_serialNumber(cert_handle_); | |
270 if (serial_num) { | |
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) | |
276 // value. | |
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()); | |
282 } | |
283 | |
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_); | |
288 } | |
289 | |
290 // static | |
291 void X509Certificate::ResetCertStore() { | |
292 X509InitSingleton::GetInstance()->ResetCertStore(); | |
293 } | |
294 | |
295 // static | |
296 SHA1HashValue X509Certificate::CalculateFingerprint(OSCertHandle cert) { | |
297 SHA1HashValue sha1; | |
298 unsigned int sha1_size = static_cast<unsigned int>(sizeof(sha1.data)); | |
299 int ret = X509_digest(cert, EVP_sha1(), sha1.data, &sha1_size); | |
300 CHECK(ret); | |
301 CHECK_EQ(sha1_size, sizeof(sha1.data)); | |
302 return sha1; | |
303 } | |
304 | |
305 // static | |
306 SHA1HashValue X509Certificate::CalculateCAFingerprint( | |
307 const OSCertHandles& intermediates) { | |
308 SHA1HashValue sha1; | |
309 memset(sha1.data, 0, sizeof(sha1.data)); | |
310 | |
311 SHA_CTX sha1_ctx; | |
312 SHA1_Init(&sha1_ctx); | |
313 DERCache der_cache; | |
314 for (size_t i = 0; i < intermediates.size(); ++i) { | |
315 if (!GetDERAndCacheIfNeeded(intermediates[i], &der_cache)) | |
316 return sha1; | |
317 SHA1_Update(&sha1_ctx, der_cache.data, der_cache.data_length); | |
318 } | |
319 SHA1_Final(sha1.data, &sha1_ctx); | |
320 | |
321 return sha1; | |
322 } | |
323 | |
324 // static | |
325 X509Certificate::OSCertHandle X509Certificate::CreateOSCertHandleFromBytes( | |
326 const char* data, int length) { | |
327 if (length < 0) | |
328 return NULL; | |
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); | |
335 return cert; | |
336 } | |
337 | |
338 // static | |
339 X509Certificate::OSCertHandles X509Certificate::CreateOSCertHandlesFromBytes( | |
340 const char* data, int length, Format format) { | |
341 OSCertHandles results; | |
342 if (length < 0) | |
343 return results; | |
344 | |
345 switch (format) { | |
346 case FORMAT_SINGLE_CERTIFICATE: { | |
347 OSCertHandle handle = CreateOSCertHandleFromBytes(data, length); | |
348 if (handle) | |
349 results.push_back(handle); | |
350 break; | |
351 } | |
352 case FORMAT_PKCS7: { | |
353 CreateOSCertHandlesFromPKCS7Bytes(data, length, &results); | |
354 break; | |
355 } | |
356 default: { | |
357 NOTREACHED() << "Certificate format " << format << " unimplemented"; | |
358 break; | |
359 } | |
360 } | |
361 | |
362 return results; | |
363 } | |
364 | |
365 // static | |
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. | |
372 NOTIMPLEMENTED(); | |
373 return NULL; | |
374 } | |
375 | |
376 void X509Certificate::GetSubjectAltName( | |
377 std::vector<std::string>* dns_names, | |
378 std::vector<std::string>* ip_addrs) const { | |
379 if (dns_names) | |
380 dns_names->clear(); | |
381 if (ip_addrs) | |
382 ip_addrs->clear(); | |
383 | |
384 ParseSubjectAltName(cert_handle_, dns_names, ip_addrs); | |
385 } | |
386 | |
387 // static | |
388 X509_STORE* X509Certificate::cert_store() { | |
389 return X509InitSingleton::GetInstance()->store(); | |
390 } | |
391 | |
392 // static | |
393 bool X509Certificate::GetDEREncoded(X509Certificate::OSCertHandle cert_handle, | |
394 std::string* encoded) { | |
395 DERCache der_cache; | |
396 if (!GetDERAndCacheIfNeeded(cert_handle, &der_cache)) | |
397 return false; | |
398 encoded->assign(reinterpret_cast<const char*>(der_cache.data), | |
399 der_cache.data_length); | |
400 return true; | |
401 } | |
402 | |
403 // static | |
404 bool X509Certificate::IsSameOSCert(X509Certificate::OSCertHandle a, | |
405 X509Certificate::OSCertHandle b) { | |
406 DCHECK(a && b); | |
407 if (a == b) | |
408 return true; | |
409 | |
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; | |
414 | |
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; | |
419 } | |
420 | |
421 // static | |
422 X509Certificate::OSCertHandle | |
423 X509Certificate::ReadOSCertHandleFromPickle(PickleIterator* pickle_iter) { | |
424 const char* data; | |
425 int length; | |
426 if (!pickle_iter->ReadData(&data, &length)) | |
427 return NULL; | |
428 | |
429 return CreateOSCertHandleFromBytes(data, length); | |
430 } | |
431 | |
432 // static | |
433 bool X509Certificate::WriteOSCertHandleToPickle(OSCertHandle cert_handle, | |
434 Pickle* pickle) { | |
435 DERCache der_cache; | |
436 if (!GetDERAndCacheIfNeeded(cert_handle, &der_cache)) | |
437 return false; | |
438 | |
439 return pickle->WriteData( | |
440 reinterpret_cast<const char*>(der_cache.data), | |
441 der_cache.data_length); | |
442 } | |
443 | |
444 // static | |
445 void X509Certificate::GetPublicKeyInfo(OSCertHandle cert_handle, | |
446 size_t* size_bits, | |
447 PublicKeyType* type) { | |
448 *type = kPublicKeyTypeUnknown; | |
449 *size_bits = 0; | |
450 | |
451 crypto::ScopedOpenSSL<EVP_PKEY, EVP_PKEY_free> scoped_key( | |
452 X509_get_pubkey(cert_handle)); | |
453 if (!scoped_key.get()) | |
454 return; | |
455 | |
456 CHECK(scoped_key.get()); | |
457 EVP_PKEY* key = scoped_key.get(); | |
458 | |
459 switch (key->type) { | |
460 case EVP_PKEY_RSA: | |
461 *type = kPublicKeyTypeRSA; | |
462 *size_bits = EVP_PKEY_size(key) * 8; | |
463 break; | |
464 case EVP_PKEY_DSA: | |
465 *type = kPublicKeyTypeDSA; | |
466 *size_bits = EVP_PKEY_size(key) * 8; | |
467 break; | |
468 case EVP_PKEY_EC: | |
469 *type = kPublicKeyTypeECDSA; | |
470 *size_bits = EVP_PKEY_size(key); | |
471 break; | |
472 case EVP_PKEY_DH: | |
473 *type = kPublicKeyTypeDH; | |
474 *size_bits = EVP_PKEY_size(key) * 8; | |
475 break; | |
476 } | |
477 } | |
478 | |
479 bool X509Certificate::IsIssuedByEncoded( | |
480 const std::vector<std::string>& valid_issuers) { | |
481 if (valid_issuers.empty()) | |
482 return false; | |
483 | |
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()) | |
489 return false; | |
490 | |
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); | |
497 if (ca_name == NULL) | |
498 return false; | |
499 sk_X509_NAME_push(issuer_names.get(), ca_name); | |
500 } | |
501 | |
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_); | |
506 if (issuer == NULL) | |
507 return false; | |
508 | |
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); | |
513 if (issuer == NULL) | |
514 return false; | |
515 cert_names.push_back(issuer); | |
516 } | |
517 | |
518 // and 'cert_names'. | |
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) { | |
523 return true; | |
524 } | |
525 } | |
526 } | |
527 | |
528 return false; | |
529 } | |
530 | |
531 } // namespace net | |
OLD | NEW |