Revert of Clean up Smart Lock cryptohome keys logic: (patchset #5 id:80001 of https...
[chromium-blink-merge.git] / net / cert / x509_util_nss.cc
blobb138bd405af42ed79ea51220bed302de41b2c5a9
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> // Must be included before certdb.h
9 #include <certdb.h>
10 #include <cryptohi.h>
11 #include <nss.h>
12 #include <pk11pub.h>
13 #include <prerror.h>
14 #include <secder.h>
15 #include <secmod.h>
16 #include <secport.h>
18 #include "base/debug/leak_annotations.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/memory/singleton.h"
22 #include "base/pickle.h"
23 #include "base/strings/stringprintf.h"
24 #include "crypto/ec_private_key.h"
25 #include "crypto/nss_util.h"
26 #include "crypto/nss_util_internal.h"
27 #include "crypto/rsa_private_key.h"
28 #include "crypto/scoped_nss_types.h"
29 #include "crypto/third_party/nss/chromium-nss.h"
30 #include "net/cert/x509_certificate.h"
32 namespace net {
34 namespace {
36 class ChannelIDOIDWrapper {
37 public:
38 static ChannelIDOIDWrapper* GetInstance() {
39 // Instantiated as a leaky singleton to allow the singleton to be
40 // constructed on a worker thead that is not joined when a process
41 // shuts down.
42 return Singleton<ChannelIDOIDWrapper,
43 LeakySingletonTraits<ChannelIDOIDWrapper> >::get();
46 SECOidTag domain_bound_cert_oid_tag() const {
47 return domain_bound_cert_oid_tag_;
50 private:
51 friend struct DefaultSingletonTraits<ChannelIDOIDWrapper>;
53 ChannelIDOIDWrapper();
55 SECOidTag domain_bound_cert_oid_tag_;
57 DISALLOW_COPY_AND_ASSIGN(ChannelIDOIDWrapper);
60 ChannelIDOIDWrapper::ChannelIDOIDWrapper()
61 : domain_bound_cert_oid_tag_(SEC_OID_UNKNOWN) {
62 // 1.3.6.1.4.1.11129.2.1.6
63 // (iso.org.dod.internet.private.enterprises.google.googleSecurity.
64 // certificateExtensions.originBoundCertificate)
65 static const uint8 kObCertOID[] = {
66 0x2b, 0x06, 0x01, 0x04, 0x01, 0xd6, 0x79, 0x02, 0x01, 0x06
68 SECOidData oid_data;
69 memset(&oid_data, 0, sizeof(oid_data));
70 oid_data.oid.data = const_cast<uint8*>(kObCertOID);
71 oid_data.oid.len = sizeof(kObCertOID);
72 oid_data.offset = SEC_OID_UNKNOWN;
73 oid_data.desc = "Origin Bound Certificate";
74 oid_data.mechanism = CKM_INVALID_MECHANISM;
75 oid_data.supportedExtension = SUPPORTED_CERT_EXTENSION;
76 domain_bound_cert_oid_tag_ = SECOID_AddEntry(&oid_data);
77 if (domain_bound_cert_oid_tag_ == SEC_OID_UNKNOWN)
78 LOG(ERROR) << "OB_CERT OID tag creation failed";
81 // Creates a Certificate object that may be passed to the SignCertificate
82 // method to generate an X509 certificate.
83 // Returns NULL if an error is encountered in the certificate creation
84 // process.
85 // Caller responsible for freeing returned certificate object.
86 CERTCertificate* CreateCertificate(
87 SECKEYPublicKey* public_key,
88 const std::string& subject,
89 uint32 serial_number,
90 base::Time not_valid_before,
91 base::Time not_valid_after) {
92 // Create info about public key.
93 CERTSubjectPublicKeyInfo* spki =
94 SECKEY_CreateSubjectPublicKeyInfo(public_key);
95 if (!spki)
96 return NULL;
98 // Create the certificate request.
99 CERTName* subject_name =
100 CERT_AsciiToName(const_cast<char*>(subject.c_str()));
101 CERTCertificateRequest* cert_request =
102 CERT_CreateCertificateRequest(subject_name, spki, NULL);
103 SECKEY_DestroySubjectPublicKeyInfo(spki);
105 if (!cert_request) {
106 PRErrorCode prerr = PR_GetError();
107 LOG(ERROR) << "Failed to create certificate request: " << prerr;
108 CERT_DestroyName(subject_name);
109 return NULL;
112 CERTValidity* validity = CERT_CreateValidity(
113 crypto::BaseTimeToPRTime(not_valid_before),
114 crypto::BaseTimeToPRTime(not_valid_after));
115 if (!validity) {
116 PRErrorCode prerr = PR_GetError();
117 LOG(ERROR) << "Failed to create certificate validity object: " << prerr;
118 CERT_DestroyName(subject_name);
119 CERT_DestroyCertificateRequest(cert_request);
120 return NULL;
122 CERTCertificate* cert = CERT_CreateCertificate(serial_number, subject_name,
123 validity, cert_request);
124 if (!cert) {
125 PRErrorCode prerr = PR_GetError();
126 LOG(ERROR) << "Failed to create certificate: " << prerr;
129 // Cleanup for resources used to generate the cert.
130 CERT_DestroyName(subject_name);
131 CERT_DestroyValidity(validity);
132 CERT_DestroyCertificateRequest(cert_request);
134 return cert;
137 SECOidTag ToSECOid(x509_util::DigestAlgorithm alg) {
138 switch (alg) {
139 case x509_util::DIGEST_SHA1:
140 return SEC_OID_SHA1;
141 case x509_util::DIGEST_SHA256:
142 return SEC_OID_SHA256;
144 return SEC_OID_UNKNOWN;
147 // Signs a certificate object, with |key| generating a new X509Certificate
148 // and destroying the passed certificate object (even when NULL is returned).
149 // The logic of this method references SignCert() in NSS utility certutil:
150 // http://mxr.mozilla.org/security/ident?i=SignCert.
151 // Returns true on success or false if an error is encountered in the
152 // certificate signing process.
153 bool SignCertificate(
154 CERTCertificate* cert,
155 SECKEYPrivateKey* key,
156 SECOidTag hash_algorithm) {
157 // |arena| is used to encode the cert.
158 PLArenaPool* arena = cert->arena;
159 SECOidTag algo_id = SEC_GetSignatureAlgorithmOidTag(key->keyType,
160 hash_algorithm);
161 if (algo_id == SEC_OID_UNKNOWN)
162 return false;
164 SECStatus rv = SECOID_SetAlgorithmID(arena, &cert->signature, algo_id, 0);
165 if (rv != SECSuccess)
166 return false;
168 // Generate a cert of version 3.
169 *(cert->version.data) = 2;
170 cert->version.len = 1;
172 SECItem der = { siBuffer, NULL, 0 };
174 // Use ASN1 DER to encode the cert.
175 void* encode_result = SEC_ASN1EncodeItem(
176 NULL, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate));
177 if (!encode_result)
178 return false;
180 // Allocate space to contain the signed cert.
181 SECItem result = { siBuffer, NULL, 0 };
183 // Sign the ASN1 encoded cert and save it to |result|.
184 rv = DerSignData(arena, &result, &der, key, algo_id);
185 PORT_Free(der.data);
186 if (rv != SECSuccess) {
187 DLOG(ERROR) << "DerSignData: " << PORT_GetError();
188 return false;
191 // Save the signed result to the cert.
192 cert->derCert = result;
194 return true;
197 #if defined(USE_NSS) || defined(OS_IOS)
198 // Callback for CERT_DecodeCertPackage(), used in
199 // CreateOSCertHandlesFromBytes().
200 SECStatus PR_CALLBACK CollectCertsCallback(void* arg,
201 SECItem** certs,
202 int num_certs) {
203 X509Certificate::OSCertHandles* results =
204 reinterpret_cast<X509Certificate::OSCertHandles*>(arg);
206 for (int i = 0; i < num_certs; ++i) {
207 X509Certificate::OSCertHandle handle =
208 X509Certificate::CreateOSCertHandleFromBytes(
209 reinterpret_cast<char*>(certs[i]->data), certs[i]->len);
210 if (handle)
211 results->push_back(handle);
214 return SECSuccess;
217 typedef scoped_ptr<
218 CERTName,
219 crypto::NSSDestroyer<CERTName, CERT_DestroyName> > ScopedCERTName;
221 // Create a new CERTName object from its encoded representation.
222 // |arena| is the allocation pool to use.
223 // |data| points to a DER-encoded X.509 DistinguishedName.
224 // Return a new CERTName pointer on success, or NULL.
225 CERTName* CreateCertNameFromEncoded(PLArenaPool* arena,
226 const base::StringPiece& data) {
227 if (!arena)
228 return NULL;
230 ScopedCERTName name(PORT_ArenaZNew(arena, CERTName));
231 if (!name.get())
232 return NULL;
234 SECItem item;
235 item.len = static_cast<unsigned int>(data.length());
236 item.data = reinterpret_cast<unsigned char*>(
237 const_cast<char*>(data.data()));
239 SECStatus rv = SEC_ASN1DecodeItem(
240 arena, name.get(), SEC_ASN1_GET(CERT_NameTemplate), &item);
241 if (rv != SECSuccess)
242 return NULL;
244 return name.release();
247 #endif // defined(USE_NSS) || defined(OS_IOS)
249 } // namespace
251 namespace x509_util {
253 bool CreateSelfSignedCert(crypto::RSAPrivateKey* key,
254 DigestAlgorithm alg,
255 const std::string& subject,
256 uint32 serial_number,
257 base::Time not_valid_before,
258 base::Time not_valid_after,
259 std::string* der_cert) {
260 DCHECK(key);
261 DCHECK(!strncmp(subject.c_str(), "CN=", 3U));
262 CERTCertificate* cert = CreateCertificate(key->public_key(),
263 subject,
264 serial_number,
265 not_valid_before,
266 not_valid_after);
267 if (!cert)
268 return false;
270 if (!SignCertificate(cert, key->key(), ToSECOid(alg))) {
271 CERT_DestroyCertificate(cert);
272 return false;
275 der_cert->assign(reinterpret_cast<char*>(cert->derCert.data),
276 cert->derCert.len);
277 CERT_DestroyCertificate(cert);
278 return true;
281 bool IsSupportedValidityRange(base::Time not_valid_before,
282 base::Time not_valid_after) {
283 CERTValidity* validity = CERT_CreateValidity(
284 crypto::BaseTimeToPRTime(not_valid_before),
285 crypto::BaseTimeToPRTime(not_valid_after));
287 if (!validity)
288 return false;
290 CERT_DestroyValidity(validity);
291 return true;
294 bool CreateChannelIDEC(crypto::ECPrivateKey* key,
295 DigestAlgorithm alg,
296 const std::string& domain,
297 uint32 serial_number,
298 base::Time not_valid_before,
299 base::Time not_valid_after,
300 std::string* der_cert) {
301 DCHECK(key);
303 CERTCertificate* cert = CreateCertificate(key->public_key(),
304 "CN=anonymous.invalid",
305 serial_number,
306 not_valid_before,
307 not_valid_after);
309 if (!cert)
310 return false;
312 // Create opaque handle used to add extensions later.
313 void* cert_handle;
314 if ((cert_handle = CERT_StartCertExtensions(cert)) == NULL) {
315 LOG(ERROR) << "Unable to get opaque handle for adding extensions";
316 CERT_DestroyCertificate(cert);
317 return false;
320 // Create SECItem for IA5String encoding.
321 SECItem domain_string_item = {
322 siAsciiString,
323 (unsigned char*)domain.data(),
324 static_cast<unsigned>(domain.size())
327 // IA5Encode and arena allocate SECItem
328 SECItem* asn1_domain_string = SEC_ASN1EncodeItem(
329 cert->arena, NULL, &domain_string_item,
330 SEC_ASN1_GET(SEC_IA5StringTemplate));
331 if (asn1_domain_string == NULL) {
332 LOG(ERROR) << "Unable to get ASN1 encoding for domain in domain_bound_cert"
333 " extension";
334 CERT_DestroyCertificate(cert);
335 return false;
338 // Add the extension to the opaque handle
339 if (CERT_AddExtension(
340 cert_handle,
341 ChannelIDOIDWrapper::GetInstance()->domain_bound_cert_oid_tag(),
342 asn1_domain_string,
343 PR_TRUE,
344 PR_TRUE) != SECSuccess){
345 LOG(ERROR) << "Unable to add domain bound cert extension to opaque handle";
346 CERT_DestroyCertificate(cert);
347 return false;
350 // Copy extension into x509 cert
351 if (CERT_FinishExtensions(cert_handle) != SECSuccess){
352 LOG(ERROR) << "Unable to copy extension to X509 cert";
353 CERT_DestroyCertificate(cert);
354 return false;
357 if (!SignCertificate(cert, key->key(), ToSECOid(alg))) {
358 CERT_DestroyCertificate(cert);
359 return false;
362 DCHECK(cert->derCert.len);
363 // XXX copied from X509Certificate::GetDEREncoded
364 der_cert->clear();
365 der_cert->append(reinterpret_cast<char*>(cert->derCert.data),
366 cert->derCert.len);
367 CERT_DestroyCertificate(cert);
368 return true;
371 #if defined(USE_NSS) || defined(OS_IOS)
372 void ParsePrincipal(CERTName* name, CertPrincipal* principal) {
373 // Starting in NSS 3.15, CERTGetNameFunc takes a const CERTName* argument.
374 #if NSS_VMINOR >= 15
375 typedef char* (*CERTGetNameFunc)(const CERTName* name);
376 #else
377 typedef char* (*CERTGetNameFunc)(CERTName* name);
378 #endif
380 // TODO(jcampan): add business_category and serial_number.
381 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
382 // CERT_GetDomainComponentName functions, but they return only the most
383 // general (the first) RDN. NSS doesn't have a function for the street
384 // address.
385 static const SECOidTag kOIDs[] = {
386 SEC_OID_AVA_STREET_ADDRESS,
387 SEC_OID_AVA_ORGANIZATION_NAME,
388 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
389 SEC_OID_AVA_DC };
391 std::vector<std::string>* values[] = {
392 &principal->street_addresses,
393 &principal->organization_names,
394 &principal->organization_unit_names,
395 &principal->domain_components };
396 DCHECK_EQ(arraysize(kOIDs), arraysize(values));
398 CERTRDN** rdns = name->rdns;
399 for (size_t rdn = 0; rdns[rdn]; ++rdn) {
400 CERTAVA** avas = rdns[rdn]->avas;
401 for (size_t pair = 0; avas[pair] != 0; ++pair) {
402 SECOidTag tag = CERT_GetAVATag(avas[pair]);
403 for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
404 if (kOIDs[oid] == tag) {
405 SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
406 if (!decode_item)
407 break;
408 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
409 std::string value(reinterpret_cast<char*>(decode_item->data),
410 decode_item->len);
411 values[oid]->push_back(value);
412 SECITEM_FreeItem(decode_item, PR_TRUE);
413 break;
419 // Get CN, L, S, and C.
420 CERTGetNameFunc get_name_funcs[4] = {
421 CERT_GetCommonName, CERT_GetLocalityName,
422 CERT_GetStateName, CERT_GetCountryName };
423 std::string* single_values[4] = {
424 &principal->common_name, &principal->locality_name,
425 &principal->state_or_province_name, &principal->country_name };
426 for (size_t i = 0; i < arraysize(get_name_funcs); ++i) {
427 char* value = get_name_funcs[i](name);
428 if (value) {
429 single_values[i]->assign(value);
430 PORT_Free(value);
435 void ParseDate(const SECItem* der_date, base::Time* result) {
436 PRTime prtime;
437 SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
438 DCHECK_EQ(SECSuccess, rv);
439 *result = crypto::PRTimeToBaseTime(prtime);
442 std::string ParseSerialNumber(const CERTCertificate* certificate) {
443 return std::string(reinterpret_cast<char*>(certificate->serialNumber.data),
444 certificate->serialNumber.len);
447 void GetSubjectAltName(CERTCertificate* cert_handle,
448 std::vector<std::string>* dns_names,
449 std::vector<std::string>* ip_addrs) {
450 if (dns_names)
451 dns_names->clear();
452 if (ip_addrs)
453 ip_addrs->clear();
455 SECItem alt_name;
456 SECStatus rv = CERT_FindCertExtension(cert_handle,
457 SEC_OID_X509_SUBJECT_ALT_NAME,
458 &alt_name);
459 if (rv != SECSuccess)
460 return;
462 PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
463 DCHECK(arena != NULL);
465 CERTGeneralName* alt_name_list;
466 alt_name_list = CERT_DecodeAltNameExtension(arena, &alt_name);
467 SECITEM_FreeItem(&alt_name, PR_FALSE);
469 CERTGeneralName* name = alt_name_list;
470 while (name) {
471 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
472 // respectively, both of which can be byte copied from
473 // SECItemType::data into the appropriate output vector.
474 if (dns_names && name->type == certDNSName) {
475 dns_names->push_back(std::string(
476 reinterpret_cast<char*>(name->name.other.data),
477 name->name.other.len));
478 } else if (ip_addrs && name->type == certIPAddress) {
479 ip_addrs->push_back(std::string(
480 reinterpret_cast<char*>(name->name.other.data),
481 name->name.other.len));
483 name = CERT_GetNextGeneralName(name);
484 if (name == alt_name_list)
485 break;
487 PORT_FreeArena(arena, PR_FALSE);
490 X509Certificate::OSCertHandles CreateOSCertHandlesFromBytes(
491 const char* data,
492 int length,
493 X509Certificate::Format format) {
494 X509Certificate::OSCertHandles results;
495 if (length < 0)
496 return results;
498 crypto::EnsureNSSInit();
500 if (!NSS_IsInitialized())
501 return results;
503 switch (format) {
504 case X509Certificate::FORMAT_SINGLE_CERTIFICATE: {
505 X509Certificate::OSCertHandle handle =
506 X509Certificate::CreateOSCertHandleFromBytes(data, length);
507 if (handle)
508 results.push_back(handle);
509 break;
511 case X509Certificate::FORMAT_PKCS7: {
512 // Make a copy since CERT_DecodeCertPackage may modify it
513 std::vector<char> data_copy(data, data + length);
515 SECStatus result = CERT_DecodeCertPackage(&data_copy[0],
516 length, CollectCertsCallback, &results);
517 if (result != SECSuccess)
518 results.clear();
519 break;
521 default:
522 NOTREACHED() << "Certificate format " << format << " unimplemented";
523 break;
526 return results;
529 X509Certificate::OSCertHandle ReadOSCertHandleFromPickle(
530 PickleIterator* pickle_iter) {
531 const char* data;
532 int length;
533 if (!pickle_iter->ReadData(&data, &length))
534 return NULL;
536 return X509Certificate::CreateOSCertHandleFromBytes(data, length);
539 void GetPublicKeyInfo(CERTCertificate* handle,
540 size_t* size_bits,
541 X509Certificate::PublicKeyType* type) {
542 // Since we might fail, set the output parameters to default values first.
543 *type = X509Certificate::kPublicKeyTypeUnknown;
544 *size_bits = 0;
546 crypto::ScopedSECKEYPublicKey key(CERT_ExtractPublicKey(handle));
547 if (!key.get())
548 return;
550 *size_bits = SECKEY_PublicKeyStrengthInBits(key.get());
552 switch (key->keyType) {
553 case rsaKey:
554 *type = X509Certificate::kPublicKeyTypeRSA;
555 break;
556 case dsaKey:
557 *type = X509Certificate::kPublicKeyTypeDSA;
558 break;
559 case dhKey:
560 *type = X509Certificate::kPublicKeyTypeDH;
561 break;
562 case ecKey:
563 *type = X509Certificate::kPublicKeyTypeECDSA;
564 break;
565 default:
566 *type = X509Certificate::kPublicKeyTypeUnknown;
567 *size_bits = 0;
568 break;
572 bool GetIssuersFromEncodedList(
573 const std::vector<std::string>& encoded_issuers,
574 PLArenaPool* arena,
575 std::vector<CERTName*>* out) {
576 std::vector<CERTName*> result;
577 for (size_t n = 0; n < encoded_issuers.size(); ++n) {
578 CERTName* name = CreateCertNameFromEncoded(arena, encoded_issuers[n]);
579 if (name != NULL)
580 result.push_back(name);
583 if (result.size() == encoded_issuers.size()) {
584 out->swap(result);
585 return true;
588 for (size_t n = 0; n < result.size(); ++n)
589 CERT_DestroyName(result[n]);
590 return false;
594 bool IsCertificateIssuedBy(const std::vector<CERTCertificate*>& cert_chain,
595 const std::vector<CERTName*>& valid_issuers) {
596 for (size_t n = 0; n < cert_chain.size(); ++n) {
597 CERTName* cert_issuer = &cert_chain[n]->issuer;
598 for (size_t i = 0; i < valid_issuers.size(); ++i) {
599 if (CERT_CompareName(valid_issuers[i], cert_issuer) == SECEqual)
600 return true;
603 return false;
606 std::string GetUniqueNicknameForSlot(const std::string& nickname,
607 const SECItem* subject,
608 PK11SlotInfo* slot) {
609 int index = 2;
610 std::string new_name = nickname;
611 std::string temp_nickname = new_name;
612 std::string token_name;
614 if (!slot)
615 return new_name;
617 if (!PK11_IsInternalKeySlot(slot)) {
618 token_name.assign(PK11_GetTokenName(slot));
619 token_name.append(":");
621 temp_nickname = token_name + new_name;
624 while (SEC_CertNicknameConflict(temp_nickname.c_str(),
625 const_cast<SECItem*>(subject),
626 CERT_GetDefaultCertDB())) {
627 base::SStringPrintf(&new_name, "%s #%d", nickname.c_str(), index++);
628 temp_nickname = token_name + new_name;
631 return new_name;
634 #endif // defined(USE_NSS) || defined(OS_IOS)
636 } // namespace x509_util
638 } // namespace net