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"
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"
33 class DomainBoundCertOIDWrapper
{
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
39 return Singleton
<DomainBoundCertOIDWrapper
,
40 LeakySingletonTraits
<DomainBoundCertOIDWrapper
> >::get();
43 SECOidTag
domain_bound_cert_oid_tag() const {
44 return domain_bound_cert_oid_tag_
;
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
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
82 // Caller responsible for freeing returned certificate object.
83 CERTCertificate
* CreateCertificate(
84 SECKEYPublicKey
* public_key
,
85 const std::string
& subject
,
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
);
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
);
103 PRErrorCode prerr
= PR_GetError();
104 LOG(ERROR
) << "Failed to create certificate request: " << prerr
;
105 CERT_DestroyName(subject_name
);
109 CERTValidity
* validity
= CERT_CreateValidity(
110 crypto::BaseTimeToPRTime(not_valid_before
),
111 crypto::BaseTimeToPRTime(not_valid_after
));
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
);
119 CERTCertificate
* cert
= CERT_CreateCertificate(serial_number
, subject_name
,
120 validity
, cert_request
);
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
);
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
,
147 if (algo_id
== SEC_OID_UNKNOWN
)
150 SECStatus rv
= SECOID_SetAlgorithmID(arena
, &cert
->signature
, algo_id
, 0);
151 if (rv
!= SECSuccess
)
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
));
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
);
172 if (rv
!= SECSuccess
) {
173 DLOG(ERROR
) << "DerSignData: " << PORT_GetError();
177 // Save the signed result to the cert.
178 cert
->derCert
= result
;
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",
200 // Create opaque handle used to add extensions later.
202 if ((cert_handle
= CERT_StartCertExtensions(cert
)) == NULL
) {
203 LOG(ERROR
) << "Unable to get opaque handle for adding extensions";
204 CERT_DestroyCertificate(cert
);
208 // Create SECItem for IA5String encoding.
209 SECItem domain_string_item
= {
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"
222 CERT_DestroyCertificate(cert
);
226 // Add the extension to the opaque handle
227 if (CERT_AddExtension(
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
);
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
);
243 if (!SignCertificate(cert
, private_key
)) {
244 CERT_DestroyCertificate(cert
);
248 DCHECK(cert
->derCert
.len
);
249 // XXX copied from X509Certificate::GetDEREncoded
251 der_cert
->append(reinterpret_cast<char*>(cert
->derCert
.data
),
253 CERT_DestroyCertificate(cert
);
257 #if defined(USE_NSS) || defined(OS_IOS)
258 // Callback for CERT_DecodeCertPackage(), used in
259 // CreateOSCertHandlesFromBytes().
260 SECStatus PR_CALLBACK
CollectCertsCallback(void* arg
,
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
);
271 results
->push_back(handle
);
277 typedef scoped_ptr_malloc
<
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
) {
290 ScopedCERTName
name(PORT_ArenaZNew(arena
, CERTName
));
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
)
304 return name
.release();
307 #endif // defined(USE_NSS) || defined(OS_IOS)
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
,
328 if (!SignCertificate(cert
, private_key
)) {
329 CERT_DestroyCertificate(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
));
345 CERT_DestroyValidity(validity
);
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
) {
357 return CreateDomainBoundCertInternal(key
->public_key(),
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.
370 typedef char* (*CERTGetNameFunc
)(const CERTName
* name
);
372 typedef char* (*CERTGetNameFunc
)(CERTName
* name
);
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
380 static const SECOidTag kOIDs
[] = {
381 SEC_OID_AVA_STREET_ADDRESS
,
382 SEC_OID_AVA_ORGANIZATION_NAME
,
383 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME
,
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
);
403 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
404 std::string
value(reinterpret_cast<char*>(decode_item
->data
),
406 values
[oid
]->push_back(value
);
407 SECITEM_FreeItem(decode_item
, PR_TRUE
);
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
);
424 single_values
[i
]->assign(value
);
430 void ParseDate(const SECItem
* der_date
, base::Time
* result
) {
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
) {
451 SECStatus rv
= CERT_FindCertExtension(cert_handle
,
452 SEC_OID_X509_SUBJECT_ALT_NAME
,
454 if (rv
!= SECSuccess
)
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
;
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
)
482 PORT_FreeArena(arena
, PR_FALSE
);
485 X509Certificate::OSCertHandles
CreateOSCertHandlesFromBytes(
488 X509Certificate::Format format
) {
489 X509Certificate::OSCertHandles results
;
493 crypto::EnsureNSSInit();
495 if (!NSS_IsInitialized())
499 case X509Certificate::FORMAT_SINGLE_CERTIFICATE
: {
500 X509Certificate::OSCertHandle handle
=
501 X509Certificate::CreateOSCertHandleFromBytes(data
, length
);
503 results
.push_back(handle
);
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
)
517 NOTREACHED() << "Certificate format " << format
<< " unimplemented";
524 X509Certificate::OSCertHandle
ReadOSCertHandleFromPickle(
525 PickleIterator
* pickle_iter
) {
528 if (!pickle_iter
->ReadData(&data
, &length
))
531 return X509Certificate::CreateOSCertHandleFromBytes(data
, length
);
534 void GetPublicKeyInfo(CERTCertificate
* handle
,
536 X509Certificate::PublicKeyType
* type
) {
537 // Since we might fail, set the output parameters to default values first.
538 *type
= X509Certificate::kPublicKeyTypeUnknown
;
541 crypto::ScopedSECKEYPublicKey
key(CERT_ExtractPublicKey(handle
));
545 *size_bits
= SECKEY_PublicKeyStrengthInBits(key
.get());
547 switch (key
->keyType
) {
549 *type
= X509Certificate::kPublicKeyTypeRSA
;
552 *type
= X509Certificate::kPublicKeyTypeDSA
;
555 *type
= X509Certificate::kPublicKeyTypeDH
;
558 *type
= X509Certificate::kPublicKeyTypeECDSA
;
561 *type
= X509Certificate::kPublicKeyTypeUnknown
;
567 bool GetIssuersFromEncodedList(
568 const std::vector
<std::string
>& encoded_issuers
,
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
]);
575 result
.push_back(name
);
578 if (result
.size() == encoded_issuers
.size()) {
583 for (size_t n
= 0; n
< result
.size(); ++n
)
584 CERT_DestroyName(result
[n
]);
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
)
601 #endif // defined(USE_NSS) || defined(OS_IOS)
603 } // namespace x509_util