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/base/x509_util.h"
6 #include "net/base/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/base/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
);
276 #endif // defined(USE_NSS) || defined(OS_IOS)
280 namespace x509_util
{
282 CERTCertificate
* CreateSelfSignedCert(
283 SECKEYPublicKey
* public_key
,
284 SECKEYPrivateKey
* private_key
,
285 const std::string
& subject
,
286 uint32 serial_number
,
287 base::Time not_valid_before
,
288 base::Time not_valid_after
) {
289 CERTCertificate
* cert
= CreateCertificate(public_key
,
297 if (!SignCertificate(cert
, private_key
)) {
298 CERT_DestroyCertificate(cert
);
305 bool IsSupportedValidityRange(base::Time not_valid_before
,
306 base::Time not_valid_after
) {
307 CERTValidity
* validity
= CERT_CreateValidity(
308 crypto::BaseTimeToPRTime(not_valid_before
),
309 crypto::BaseTimeToPRTime(not_valid_after
));
314 CERT_DestroyValidity(validity
);
318 bool CreateDomainBoundCertEC(
319 crypto::ECPrivateKey
* key
,
320 const std::string
& domain
,
321 uint32 serial_number
,
322 base::Time not_valid_before
,
323 base::Time not_valid_after
,
324 std::string
* der_cert
) {
326 return CreateDomainBoundCertInternal(key
->public_key(),
335 #if defined(USE_NSS) || defined(OS_IOS)
336 void ParsePrincipal(CERTName
* name
, CertPrincipal
* principal
) {
337 typedef char* (*CERTGetNameFunc
)(CERTName
* name
);
339 // TODO(jcampan): add business_category and serial_number.
340 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
341 // CERT_GetDomainComponentName functions, but they return only the most
342 // general (the first) RDN. NSS doesn't have a function for the street
344 static const SECOidTag kOIDs
[] = {
345 SEC_OID_AVA_STREET_ADDRESS
,
346 SEC_OID_AVA_ORGANIZATION_NAME
,
347 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME
,
350 std::vector
<std::string
>* values
[] = {
351 &principal
->street_addresses
,
352 &principal
->organization_names
,
353 &principal
->organization_unit_names
,
354 &principal
->domain_components
};
355 DCHECK_EQ(arraysize(kOIDs
), arraysize(values
));
357 CERTRDN
** rdns
= name
->rdns
;
358 for (size_t rdn
= 0; rdns
[rdn
]; ++rdn
) {
359 CERTAVA
** avas
= rdns
[rdn
]->avas
;
360 for (size_t pair
= 0; avas
[pair
] != 0; ++pair
) {
361 SECOidTag tag
= CERT_GetAVATag(avas
[pair
]);
362 for (size_t oid
= 0; oid
< arraysize(kOIDs
); ++oid
) {
363 if (kOIDs
[oid
] == tag
) {
364 SECItem
* decode_item
= CERT_DecodeAVAValue(&avas
[pair
]->value
);
367 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
368 std::string
value(reinterpret_cast<char*>(decode_item
->data
),
370 values
[oid
]->push_back(value
);
371 SECITEM_FreeItem(decode_item
, PR_TRUE
);
378 // Get CN, L, S, and C.
379 CERTGetNameFunc get_name_funcs
[4] = {
380 CERT_GetCommonName
, CERT_GetLocalityName
,
381 CERT_GetStateName
, CERT_GetCountryName
};
382 std::string
* single_values
[4] = {
383 &principal
->common_name
, &principal
->locality_name
,
384 &principal
->state_or_province_name
, &principal
->country_name
};
385 for (size_t i
= 0; i
< arraysize(get_name_funcs
); ++i
) {
386 char* value
= get_name_funcs
[i
](name
);
388 single_values
[i
]->assign(value
);
394 void ParseDate(const SECItem
* der_date
, base::Time
* result
) {
396 SECStatus rv
= DER_DecodeTimeChoice(&prtime
, der_date
);
397 DCHECK_EQ(SECSuccess
, rv
);
398 *result
= crypto::PRTimeToBaseTime(prtime
);
401 std::string
ParseSerialNumber(const CERTCertificate
* certificate
) {
402 return std::string(reinterpret_cast<char*>(certificate
->serialNumber
.data
),
403 certificate
->serialNumber
.len
);
406 void GetSubjectAltName(CERTCertificate
* cert_handle
,
407 std::vector
<std::string
>* dns_names
,
408 std::vector
<std::string
>* ip_addrs
) {
415 SECStatus rv
= CERT_FindCertExtension(cert_handle
,
416 SEC_OID_X509_SUBJECT_ALT_NAME
,
418 if (rv
!= SECSuccess
)
421 PLArenaPool
* arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
422 DCHECK(arena
!= NULL
);
424 CERTGeneralName
* alt_name_list
;
425 alt_name_list
= CERT_DecodeAltNameExtension(arena
, &alt_name
);
426 SECITEM_FreeItem(&alt_name
, PR_FALSE
);
428 CERTGeneralName
* name
= alt_name_list
;
430 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
431 // respectively, both of which can be byte copied from
432 // SECItemType::data into the appropriate output vector.
433 if (dns_names
&& name
->type
== certDNSName
) {
434 dns_names
->push_back(std::string(
435 reinterpret_cast<char*>(name
->name
.other
.data
),
436 name
->name
.other
.len
));
437 } else if (ip_addrs
&& name
->type
== certIPAddress
) {
438 ip_addrs
->push_back(std::string(
439 reinterpret_cast<char*>(name
->name
.other
.data
),
440 name
->name
.other
.len
));
442 name
= CERT_GetNextGeneralName(name
);
443 if (name
== alt_name_list
)
446 PORT_FreeArena(arena
, PR_FALSE
);
449 X509Certificate::OSCertHandles
CreateOSCertHandlesFromBytes(
452 X509Certificate::Format format
) {
453 X509Certificate::OSCertHandles results
;
457 crypto::EnsureNSSInit();
459 if (!NSS_IsInitialized())
463 case X509Certificate::FORMAT_SINGLE_CERTIFICATE
: {
464 X509Certificate::OSCertHandle handle
=
465 X509Certificate::CreateOSCertHandleFromBytes(data
, length
);
467 results
.push_back(handle
);
470 case X509Certificate::FORMAT_PKCS7
: {
471 // Make a copy since CERT_DecodeCertPackage may modify it
472 std::vector
<char> data_copy(data
, data
+ length
);
474 SECStatus result
= CERT_DecodeCertPackage(&data_copy
[0],
475 length
, CollectCertsCallback
, &results
);
476 if (result
!= SECSuccess
)
481 NOTREACHED() << "Certificate format " << format
<< " unimplemented";
488 X509Certificate::OSCertHandle
ReadOSCertHandleFromPickle(
489 PickleIterator
* pickle_iter
) {
492 if (!pickle_iter
->ReadData(&data
, &length
))
495 return X509Certificate::CreateOSCertHandleFromBytes(data
, length
);
498 void GetPublicKeyInfo(CERTCertificate
* handle
,
500 X509Certificate::PublicKeyType
* type
) {
501 // Since we might fail, set the output parameters to default values first.
502 *type
= X509Certificate::kPublicKeyTypeUnknown
;
505 crypto::ScopedSECKEYPublicKey
key(CERT_ExtractPublicKey(handle
));
509 *size_bits
= SECKEY_PublicKeyStrengthInBits(key
.get());
511 switch (key
->keyType
) {
513 *type
= X509Certificate::kPublicKeyTypeRSA
;
516 *type
= X509Certificate::kPublicKeyTypeDSA
;
519 *type
= X509Certificate::kPublicKeyTypeDH
;
522 *type
= X509Certificate::kPublicKeyTypeECDSA
;
525 *type
= X509Certificate::kPublicKeyTypeUnknown
;
530 #endif // defined(USE_NSS) || defined(OS_IOS)
532 } // namespace x509_util