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
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"
36 class ChannelIDOIDWrapper
{
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
42 return Singleton
<ChannelIDOIDWrapper
,
43 LeakySingletonTraits
<ChannelIDOIDWrapper
> >::get();
46 SECOidTag
domain_bound_cert_oid_tag() const {
47 return domain_bound_cert_oid_tag_
;
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
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
85 // Caller responsible for freeing returned certificate object.
86 CERTCertificate
* CreateCertificate(
87 SECKEYPublicKey
* public_key
,
88 const std::string
& subject
,
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
);
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
);
106 PRErrorCode prerr
= PR_GetError();
107 LOG(ERROR
) << "Failed to create certificate request: " << prerr
;
108 CERT_DestroyName(subject_name
);
112 CERTValidity
* validity
= CERT_CreateValidity(
113 crypto::BaseTimeToPRTime(not_valid_before
),
114 crypto::BaseTimeToPRTime(not_valid_after
));
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
);
122 CERTCertificate
* cert
= CERT_CreateCertificate(serial_number
, subject_name
,
123 validity
, cert_request
);
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
);
137 SECOidTag
ToSECOid(x509_util::DigestAlgorithm alg
) {
139 case x509_util::DIGEST_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
,
161 if (algo_id
== SEC_OID_UNKNOWN
)
164 SECStatus rv
= SECOID_SetAlgorithmID(arena
, &cert
->signature
, algo_id
, 0);
165 if (rv
!= SECSuccess
)
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
));
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
);
186 if (rv
!= SECSuccess
) {
187 DLOG(ERROR
) << "DerSignData: " << PORT_GetError();
191 // Save the signed result to the cert.
192 cert
->derCert
= result
;
197 #if defined(USE_NSS) || defined(OS_IOS)
198 // Callback for CERT_DecodeCertPackage(), used in
199 // CreateOSCertHandlesFromBytes().
200 SECStatus PR_CALLBACK
CollectCertsCallback(void* arg
,
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
);
211 results
->push_back(handle
);
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
) {
230 ScopedCERTName
name(PORT_ArenaZNew(arena
, CERTName
));
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
)
244 return name
.release();
247 #endif // defined(USE_NSS) || defined(OS_IOS)
251 namespace x509_util
{
253 bool CreateSelfSignedCert(crypto::RSAPrivateKey
* key
,
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
) {
261 DCHECK(!strncmp(subject
.c_str(), "CN=", 3U));
262 CERTCertificate
* cert
= CreateCertificate(key
->public_key(),
270 if (!SignCertificate(cert
, key
->key(), ToSECOid(alg
))) {
271 CERT_DestroyCertificate(cert
);
275 der_cert
->assign(reinterpret_cast<char*>(cert
->derCert
.data
),
277 CERT_DestroyCertificate(cert
);
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
));
290 CERT_DestroyValidity(validity
);
294 bool CreateChannelIDEC(crypto::ECPrivateKey
* key
,
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
) {
303 CERTCertificate
* cert
= CreateCertificate(key
->public_key(),
304 "CN=anonymous.invalid",
312 // Create opaque handle used to add extensions later.
314 if ((cert_handle
= CERT_StartCertExtensions(cert
)) == NULL
) {
315 LOG(ERROR
) << "Unable to get opaque handle for adding extensions";
316 CERT_DestroyCertificate(cert
);
320 // Create SECItem for IA5String encoding.
321 SECItem domain_string_item
= {
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"
334 CERT_DestroyCertificate(cert
);
338 // Add the extension to the opaque handle
339 if (CERT_AddExtension(
341 ChannelIDOIDWrapper::GetInstance()->domain_bound_cert_oid_tag(),
344 PR_TRUE
) != SECSuccess
){
345 LOG(ERROR
) << "Unable to add domain bound cert extension to opaque handle";
346 CERT_DestroyCertificate(cert
);
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
);
357 if (!SignCertificate(cert
, key
->key(), ToSECOid(alg
))) {
358 CERT_DestroyCertificate(cert
);
362 DCHECK(cert
->derCert
.len
);
363 // XXX copied from X509Certificate::GetDEREncoded
365 der_cert
->append(reinterpret_cast<char*>(cert
->derCert
.data
),
367 CERT_DestroyCertificate(cert
);
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.
375 typedef char* (*CERTGetNameFunc
)(const CERTName
* name
);
377 typedef char* (*CERTGetNameFunc
)(CERTName
* name
);
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
385 static const SECOidTag kOIDs
[] = {
386 SEC_OID_AVA_STREET_ADDRESS
,
387 SEC_OID_AVA_ORGANIZATION_NAME
,
388 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME
,
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
);
408 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
409 std::string
value(reinterpret_cast<char*>(decode_item
->data
),
411 values
[oid
]->push_back(value
);
412 SECITEM_FreeItem(decode_item
, PR_TRUE
);
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
);
429 single_values
[i
]->assign(value
);
435 void ParseDate(const SECItem
* der_date
, base::Time
* result
) {
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
) {
456 SECStatus rv
= CERT_FindCertExtension(cert_handle
,
457 SEC_OID_X509_SUBJECT_ALT_NAME
,
459 if (rv
!= SECSuccess
)
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
;
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
)
487 PORT_FreeArena(arena
, PR_FALSE
);
490 X509Certificate::OSCertHandles
CreateOSCertHandlesFromBytes(
493 X509Certificate::Format format
) {
494 X509Certificate::OSCertHandles results
;
498 crypto::EnsureNSSInit();
500 if (!NSS_IsInitialized())
504 case X509Certificate::FORMAT_SINGLE_CERTIFICATE
: {
505 X509Certificate::OSCertHandle handle
=
506 X509Certificate::CreateOSCertHandleFromBytes(data
, length
);
508 results
.push_back(handle
);
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
)
522 NOTREACHED() << "Certificate format " << format
<< " unimplemented";
529 X509Certificate::OSCertHandle
ReadOSCertHandleFromPickle(
530 PickleIterator
* pickle_iter
) {
533 if (!pickle_iter
->ReadData(&data
, &length
))
536 return X509Certificate::CreateOSCertHandleFromBytes(data
, length
);
539 void GetPublicKeyInfo(CERTCertificate
* handle
,
541 X509Certificate::PublicKeyType
* type
) {
542 // Since we might fail, set the output parameters to default values first.
543 *type
= X509Certificate::kPublicKeyTypeUnknown
;
546 crypto::ScopedSECKEYPublicKey
key(CERT_ExtractPublicKey(handle
));
550 *size_bits
= SECKEY_PublicKeyStrengthInBits(key
.get());
552 switch (key
->keyType
) {
554 *type
= X509Certificate::kPublicKeyTypeRSA
;
557 *type
= X509Certificate::kPublicKeyTypeDSA
;
560 *type
= X509Certificate::kPublicKeyTypeDH
;
563 *type
= X509Certificate::kPublicKeyTypeECDSA
;
566 *type
= X509Certificate::kPublicKeyTypeUnknown
;
572 bool GetIssuersFromEncodedList(
573 const std::vector
<std::string
>& encoded_issuers
,
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
]);
580 result
.push_back(name
);
583 if (result
.size() == encoded_issuers
.size()) {
588 for (size_t n
= 0; n
< result
.size(); ++n
)
589 CERT_DestroyName(result
[n
]);
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
)
606 std::string
GetUniqueNicknameForSlot(const std::string
& nickname
,
607 const SECItem
* subject
,
608 PK11SlotInfo
* slot
) {
610 std::string new_name
= nickname
;
611 std::string temp_nickname
= new_name
;
612 std::string token_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
;
634 #endif // defined(USE_NSS) || defined(OS_IOS)
636 } // namespace x509_util