Add signalSyncPoint to the WebGraphicsContext3D command buffer impls.
[chromium-blink-merge.git] / net / cert / x509_util_nss.cc
blobbf08681de43a76e765e58ed61e8e3023b1c5c465
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_util.h"
6 #include "net/cert/x509_util_nss.h"
8 #include <cert.h>
9 #include <cryptohi.h>
10 #include <nss.h>
11 #include <pk11pub.h>
12 #include <prerror.h>
13 #include <secder.h>
14 #include <secmod.h>
15 #include <secport.h>
17 #include "base/debug/leak_annotations.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/singleton.h"
21 #include "base/pickle.h"
22 #include "crypto/ec_private_key.h"
23 #include "crypto/nss_util.h"
24 #include "crypto/nss_util_internal.h"
25 #include "crypto/scoped_nss_types.h"
26 #include "crypto/third_party/nss/chromium-nss.h"
27 #include "net/cert/x509_certificate.h"
29 namespace net {
31 namespace {
33 class DomainBoundCertOIDWrapper {
34 public:
35 static DomainBoundCertOIDWrapper* GetInstance() {
36 // Instantiated as a leaky singleton to allow the singleton to be
37 // constructed on a worker thead that is not joined when a process
38 // shuts down.
39 return Singleton<DomainBoundCertOIDWrapper,
40 LeakySingletonTraits<DomainBoundCertOIDWrapper> >::get();
43 SECOidTag domain_bound_cert_oid_tag() const {
44 return domain_bound_cert_oid_tag_;
47 private:
48 friend struct DefaultSingletonTraits<DomainBoundCertOIDWrapper>;
50 DomainBoundCertOIDWrapper();
52 SECOidTag domain_bound_cert_oid_tag_;
54 DISALLOW_COPY_AND_ASSIGN(DomainBoundCertOIDWrapper);
57 DomainBoundCertOIDWrapper::DomainBoundCertOIDWrapper()
58 : domain_bound_cert_oid_tag_(SEC_OID_UNKNOWN) {
59 // 1.3.6.1.4.1.11129.2.1.6
60 // (iso.org.dod.internet.private.enterprises.google.googleSecurity.
61 // certificateExtensions.originBoundCertificate)
62 static const uint8 kObCertOID[] = {
63 0x2b, 0x06, 0x01, 0x04, 0x01, 0xd6, 0x79, 0x02, 0x01, 0x06
65 SECOidData oid_data;
66 memset(&oid_data, 0, sizeof(oid_data));
67 oid_data.oid.data = const_cast<uint8*>(kObCertOID);
68 oid_data.oid.len = sizeof(kObCertOID);
69 oid_data.offset = SEC_OID_UNKNOWN;
70 oid_data.desc = "Origin Bound Certificate";
71 oid_data.mechanism = CKM_INVALID_MECHANISM;
72 oid_data.supportedExtension = SUPPORTED_CERT_EXTENSION;
73 domain_bound_cert_oid_tag_ = SECOID_AddEntry(&oid_data);
74 if (domain_bound_cert_oid_tag_ == SEC_OID_UNKNOWN)
75 LOG(ERROR) << "OB_CERT OID tag creation failed";
78 // Creates a Certificate object that may be passed to the SignCertificate
79 // method to generate an X509 certificate.
80 // Returns NULL if an error is encountered in the certificate creation
81 // process.
82 // Caller responsible for freeing returned certificate object.
83 CERTCertificate* CreateCertificate(
84 SECKEYPublicKey* public_key,
85 const std::string& subject,
86 uint32 serial_number,
87 base::Time not_valid_before,
88 base::Time not_valid_after) {
89 // Create info about public key.
90 CERTSubjectPublicKeyInfo* spki =
91 SECKEY_CreateSubjectPublicKeyInfo(public_key);
92 if (!spki)
93 return NULL;
95 // Create the certificate request.
96 CERTName* subject_name =
97 CERT_AsciiToName(const_cast<char*>(subject.c_str()));
98 CERTCertificateRequest* cert_request =
99 CERT_CreateCertificateRequest(subject_name, spki, NULL);
100 SECKEY_DestroySubjectPublicKeyInfo(spki);
102 if (!cert_request) {
103 PRErrorCode prerr = PR_GetError();
104 LOG(ERROR) << "Failed to create certificate request: " << prerr;
105 CERT_DestroyName(subject_name);
106 return NULL;
109 CERTValidity* validity = CERT_CreateValidity(
110 crypto::BaseTimeToPRTime(not_valid_before),
111 crypto::BaseTimeToPRTime(not_valid_after));
112 if (!validity) {
113 PRErrorCode prerr = PR_GetError();
114 LOG(ERROR) << "Failed to create certificate validity object: " << prerr;
115 CERT_DestroyName(subject_name);
116 CERT_DestroyCertificateRequest(cert_request);
117 return NULL;
119 CERTCertificate* cert = CERT_CreateCertificate(serial_number, subject_name,
120 validity, cert_request);
121 if (!cert) {
122 PRErrorCode prerr = PR_GetError();
123 LOG(ERROR) << "Failed to create certificate: " << prerr;
126 // Cleanup for resources used to generate the cert.
127 CERT_DestroyName(subject_name);
128 CERT_DestroyValidity(validity);
129 CERT_DestroyCertificateRequest(cert_request);
131 return cert;
134 // Signs a certificate object, with |key| generating a new X509Certificate
135 // and destroying the passed certificate object (even when NULL is returned).
136 // The logic of this method references SignCert() in NSS utility certutil:
137 // http://mxr.mozilla.org/security/ident?i=SignCert.
138 // Returns true on success or false if an error is encountered in the
139 // certificate signing process.
140 bool SignCertificate(
141 CERTCertificate* cert,
142 SECKEYPrivateKey* key) {
143 // |arena| is used to encode the cert.
144 PLArenaPool* arena = cert->arena;
145 SECOidTag algo_id = SEC_GetSignatureAlgorithmOidTag(key->keyType,
146 SEC_OID_SHA1);
147 if (algo_id == SEC_OID_UNKNOWN)
148 return false;
150 SECStatus rv = SECOID_SetAlgorithmID(arena, &cert->signature, algo_id, 0);
151 if (rv != SECSuccess)
152 return false;
154 // Generate a cert of version 3.
155 *(cert->version.data) = 2;
156 cert->version.len = 1;
158 SECItem der = { siBuffer, NULL, 0 };
160 // Use ASN1 DER to encode the cert.
161 void* encode_result = SEC_ASN1EncodeItem(
162 NULL, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate));
163 if (!encode_result)
164 return false;
166 // Allocate space to contain the signed cert.
167 SECItem result = { siBuffer, NULL, 0 };
169 // Sign the ASN1 encoded cert and save it to |result|.
170 rv = DerSignData(arena, &result, &der, key, algo_id);
171 PORT_Free(der.data);
172 if (rv != SECSuccess) {
173 DLOG(ERROR) << "DerSignData: " << PORT_GetError();
174 return false;
177 // Save the signed result to the cert.
178 cert->derCert = result;
180 return true;
183 bool CreateDomainBoundCertInternal(
184 SECKEYPublicKey* public_key,
185 SECKEYPrivateKey* private_key,
186 const std::string& domain,
187 uint32 serial_number,
188 base::Time not_valid_before,
189 base::Time not_valid_after,
190 std::string* der_cert) {
191 CERTCertificate* cert = CreateCertificate(public_key,
192 "CN=anonymous.invalid",
193 serial_number,
194 not_valid_before,
195 not_valid_after);
197 if (!cert)
198 return false;
200 // Create opaque handle used to add extensions later.
201 void* cert_handle;
202 if ((cert_handle = CERT_StartCertExtensions(cert)) == NULL) {
203 LOG(ERROR) << "Unable to get opaque handle for adding extensions";
204 CERT_DestroyCertificate(cert);
205 return false;
208 // Create SECItem for IA5String encoding.
209 SECItem domain_string_item = {
210 siAsciiString,
211 (unsigned char*)domain.data(),
212 static_cast<unsigned>(domain.size())
215 // IA5Encode and arena allocate SECItem
216 SECItem* asn1_domain_string = SEC_ASN1EncodeItem(
217 cert->arena, NULL, &domain_string_item,
218 SEC_ASN1_GET(SEC_IA5StringTemplate));
219 if (asn1_domain_string == NULL) {
220 LOG(ERROR) << "Unable to get ASN1 encoding for domain in domain_bound_cert"
221 " extension";
222 CERT_DestroyCertificate(cert);
223 return false;
226 // Add the extension to the opaque handle
227 if (CERT_AddExtension(
228 cert_handle,
229 DomainBoundCertOIDWrapper::GetInstance()->domain_bound_cert_oid_tag(),
230 asn1_domain_string, PR_TRUE, PR_TRUE) != SECSuccess){
231 LOG(ERROR) << "Unable to add domain bound cert extension to opaque handle";
232 CERT_DestroyCertificate(cert);
233 return false;
236 // Copy extension into x509 cert
237 if (CERT_FinishExtensions(cert_handle) != SECSuccess){
238 LOG(ERROR) << "Unable to copy extension to X509 cert";
239 CERT_DestroyCertificate(cert);
240 return false;
243 if (!SignCertificate(cert, private_key)) {
244 CERT_DestroyCertificate(cert);
245 return false;
248 DCHECK(cert->derCert.len);
249 // XXX copied from X509Certificate::GetDEREncoded
250 der_cert->clear();
251 der_cert->append(reinterpret_cast<char*>(cert->derCert.data),
252 cert->derCert.len);
253 CERT_DestroyCertificate(cert);
254 return true;
257 #if defined(USE_NSS) || defined(OS_IOS)
258 // Callback for CERT_DecodeCertPackage(), used in
259 // CreateOSCertHandlesFromBytes().
260 SECStatus PR_CALLBACK CollectCertsCallback(void* arg,
261 SECItem** certs,
262 int num_certs) {
263 X509Certificate::OSCertHandles* results =
264 reinterpret_cast<X509Certificate::OSCertHandles*>(arg);
266 for (int i = 0; i < num_certs; ++i) {
267 X509Certificate::OSCertHandle handle =
268 X509Certificate::CreateOSCertHandleFromBytes(
269 reinterpret_cast<char*>(certs[i]->data), certs[i]->len);
270 if (handle)
271 results->push_back(handle);
274 return SECSuccess;
277 typedef scoped_ptr_malloc<
278 CERTName,
279 crypto::NSSDestroyer<CERTName, CERT_DestroyName> > ScopedCERTName;
281 // Create a new CERTName object from its encoded representation.
282 // |arena| is the allocation pool to use.
283 // |data| points to a DER-encoded X.509 DistinguishedName.
284 // Return a new CERTName pointer on success, or NULL.
285 CERTName* CreateCertNameFromEncoded(PLArenaPool* arena,
286 const base::StringPiece& data) {
287 if (!arena)
288 return NULL;
290 ScopedCERTName name(PORT_ArenaZNew(arena, CERTName));
291 if (!name.get())
292 return NULL;
294 SECItem item;
295 item.len = static_cast<unsigned int>(data.length());
296 item.data = reinterpret_cast<unsigned char*>(
297 const_cast<char*>(data.data()));
299 SECStatus rv = SEC_ASN1DecodeItem(
300 arena, name.get(), SEC_ASN1_GET(CERT_NameTemplate), &item);
301 if (rv != SECSuccess)
302 return NULL;
304 return name.release();
307 #endif // defined(USE_NSS) || defined(OS_IOS)
309 } // namespace
311 namespace x509_util {
313 CERTCertificate* CreateSelfSignedCert(
314 SECKEYPublicKey* public_key,
315 SECKEYPrivateKey* private_key,
316 const std::string& subject,
317 uint32 serial_number,
318 base::Time not_valid_before,
319 base::Time not_valid_after) {
320 CERTCertificate* cert = CreateCertificate(public_key,
321 subject,
322 serial_number,
323 not_valid_before,
324 not_valid_after);
325 if (!cert)
326 return NULL;
328 if (!SignCertificate(cert, private_key)) {
329 CERT_DestroyCertificate(cert);
330 return NULL;
333 return cert;
336 bool IsSupportedValidityRange(base::Time not_valid_before,
337 base::Time not_valid_after) {
338 CERTValidity* validity = CERT_CreateValidity(
339 crypto::BaseTimeToPRTime(not_valid_before),
340 crypto::BaseTimeToPRTime(not_valid_after));
342 if (!validity)
343 return false;
345 CERT_DestroyValidity(validity);
346 return true;
349 bool CreateDomainBoundCertEC(
350 crypto::ECPrivateKey* key,
351 const std::string& domain,
352 uint32 serial_number,
353 base::Time not_valid_before,
354 base::Time not_valid_after,
355 std::string* der_cert) {
356 DCHECK(key);
357 return CreateDomainBoundCertInternal(key->public_key(),
358 key->key(),
359 domain,
360 serial_number,
361 not_valid_before,
362 not_valid_after,
363 der_cert);
366 #if defined(USE_NSS) || defined(OS_IOS)
367 void ParsePrincipal(CERTName* name, CertPrincipal* principal) {
368 // Starting in NSS 3.15, CERTGetNameFunc takes a const CERTName* argument.
369 #if NSS_VMINOR >= 15
370 typedef char* (*CERTGetNameFunc)(const CERTName* name);
371 #else
372 typedef char* (*CERTGetNameFunc)(CERTName* name);
373 #endif
375 // TODO(jcampan): add business_category and serial_number.
376 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
377 // CERT_GetDomainComponentName functions, but they return only the most
378 // general (the first) RDN. NSS doesn't have a function for the street
379 // address.
380 static const SECOidTag kOIDs[] = {
381 SEC_OID_AVA_STREET_ADDRESS,
382 SEC_OID_AVA_ORGANIZATION_NAME,
383 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
384 SEC_OID_AVA_DC };
386 std::vector<std::string>* values[] = {
387 &principal->street_addresses,
388 &principal->organization_names,
389 &principal->organization_unit_names,
390 &principal->domain_components };
391 DCHECK_EQ(arraysize(kOIDs), arraysize(values));
393 CERTRDN** rdns = name->rdns;
394 for (size_t rdn = 0; rdns[rdn]; ++rdn) {
395 CERTAVA** avas = rdns[rdn]->avas;
396 for (size_t pair = 0; avas[pair] != 0; ++pair) {
397 SECOidTag tag = CERT_GetAVATag(avas[pair]);
398 for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
399 if (kOIDs[oid] == tag) {
400 SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
401 if (!decode_item)
402 break;
403 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
404 std::string value(reinterpret_cast<char*>(decode_item->data),
405 decode_item->len);
406 values[oid]->push_back(value);
407 SECITEM_FreeItem(decode_item, PR_TRUE);
408 break;
414 // Get CN, L, S, and C.
415 CERTGetNameFunc get_name_funcs[4] = {
416 CERT_GetCommonName, CERT_GetLocalityName,
417 CERT_GetStateName, CERT_GetCountryName };
418 std::string* single_values[4] = {
419 &principal->common_name, &principal->locality_name,
420 &principal->state_or_province_name, &principal->country_name };
421 for (size_t i = 0; i < arraysize(get_name_funcs); ++i) {
422 char* value = get_name_funcs[i](name);
423 if (value) {
424 single_values[i]->assign(value);
425 PORT_Free(value);
430 void ParseDate(const SECItem* der_date, base::Time* result) {
431 PRTime prtime;
432 SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
433 DCHECK_EQ(SECSuccess, rv);
434 *result = crypto::PRTimeToBaseTime(prtime);
437 std::string ParseSerialNumber(const CERTCertificate* certificate) {
438 return std::string(reinterpret_cast<char*>(certificate->serialNumber.data),
439 certificate->serialNumber.len);
442 void GetSubjectAltName(CERTCertificate* cert_handle,
443 std::vector<std::string>* dns_names,
444 std::vector<std::string>* ip_addrs) {
445 if (dns_names)
446 dns_names->clear();
447 if (ip_addrs)
448 ip_addrs->clear();
450 SECItem alt_name;
451 SECStatus rv = CERT_FindCertExtension(cert_handle,
452 SEC_OID_X509_SUBJECT_ALT_NAME,
453 &alt_name);
454 if (rv != SECSuccess)
455 return;
457 PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
458 DCHECK(arena != NULL);
460 CERTGeneralName* alt_name_list;
461 alt_name_list = CERT_DecodeAltNameExtension(arena, &alt_name);
462 SECITEM_FreeItem(&alt_name, PR_FALSE);
464 CERTGeneralName* name = alt_name_list;
465 while (name) {
466 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
467 // respectively, both of which can be byte copied from
468 // SECItemType::data into the appropriate output vector.
469 if (dns_names && name->type == certDNSName) {
470 dns_names->push_back(std::string(
471 reinterpret_cast<char*>(name->name.other.data),
472 name->name.other.len));
473 } else if (ip_addrs && name->type == certIPAddress) {
474 ip_addrs->push_back(std::string(
475 reinterpret_cast<char*>(name->name.other.data),
476 name->name.other.len));
478 name = CERT_GetNextGeneralName(name);
479 if (name == alt_name_list)
480 break;
482 PORT_FreeArena(arena, PR_FALSE);
485 X509Certificate::OSCertHandles CreateOSCertHandlesFromBytes(
486 const char* data,
487 int length,
488 X509Certificate::Format format) {
489 X509Certificate::OSCertHandles results;
490 if (length < 0)
491 return results;
493 crypto::EnsureNSSInit();
495 if (!NSS_IsInitialized())
496 return results;
498 switch (format) {
499 case X509Certificate::FORMAT_SINGLE_CERTIFICATE: {
500 X509Certificate::OSCertHandle handle =
501 X509Certificate::CreateOSCertHandleFromBytes(data, length);
502 if (handle)
503 results.push_back(handle);
504 break;
506 case X509Certificate::FORMAT_PKCS7: {
507 // Make a copy since CERT_DecodeCertPackage may modify it
508 std::vector<char> data_copy(data, data + length);
510 SECStatus result = CERT_DecodeCertPackage(&data_copy[0],
511 length, CollectCertsCallback, &results);
512 if (result != SECSuccess)
513 results.clear();
514 break;
516 default:
517 NOTREACHED() << "Certificate format " << format << " unimplemented";
518 break;
521 return results;
524 X509Certificate::OSCertHandle ReadOSCertHandleFromPickle(
525 PickleIterator* pickle_iter) {
526 const char* data;
527 int length;
528 if (!pickle_iter->ReadData(&data, &length))
529 return NULL;
531 return X509Certificate::CreateOSCertHandleFromBytes(data, length);
534 void GetPublicKeyInfo(CERTCertificate* handle,
535 size_t* size_bits,
536 X509Certificate::PublicKeyType* type) {
537 // Since we might fail, set the output parameters to default values first.
538 *type = X509Certificate::kPublicKeyTypeUnknown;
539 *size_bits = 0;
541 crypto::ScopedSECKEYPublicKey key(CERT_ExtractPublicKey(handle));
542 if (!key.get())
543 return;
545 *size_bits = SECKEY_PublicKeyStrengthInBits(key.get());
547 switch (key->keyType) {
548 case rsaKey:
549 *type = X509Certificate::kPublicKeyTypeRSA;
550 break;
551 case dsaKey:
552 *type = X509Certificate::kPublicKeyTypeDSA;
553 break;
554 case dhKey:
555 *type = X509Certificate::kPublicKeyTypeDH;
556 break;
557 case ecKey:
558 *type = X509Certificate::kPublicKeyTypeECDSA;
559 break;
560 default:
561 *type = X509Certificate::kPublicKeyTypeUnknown;
562 *size_bits = 0;
563 break;
567 bool GetIssuersFromEncodedList(
568 const std::vector<std::string>& encoded_issuers,
569 PLArenaPool* arena,
570 std::vector<CERTName*>* out) {
571 std::vector<CERTName*> result;
572 for (size_t n = 0; n < encoded_issuers.size(); ++n) {
573 CERTName* name = CreateCertNameFromEncoded(arena, encoded_issuers[n]);
574 if (name != NULL)
575 result.push_back(name);
578 if (result.size() == encoded_issuers.size()) {
579 out->swap(result);
580 return true;
583 for (size_t n = 0; n < result.size(); ++n)
584 CERT_DestroyName(result[n]);
585 return false;
589 bool IsCertificateIssuedBy(const std::vector<CERTCertificate*>& cert_chain,
590 const std::vector<CERTName*>& valid_issuers) {
591 for (size_t n = 0; n < cert_chain.size(); ++n) {
592 CERTName* cert_issuer = &cert_chain[n]->issuer;
593 for (size_t i = 0; i < valid_issuers.size(); ++i) {
594 if (CERT_CompareName(valid_issuers[i], cert_issuer) == SECEqual)
595 return true;
598 return false;
601 #endif // defined(USE_NSS) || defined(OS_IOS)
603 } // namespace x509_util
605 } // namespace net