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
;
199 namespace x509_util
{
201 bool CreateSelfSignedCert(crypto::RSAPrivateKey
* key
,
203 const std::string
& subject
,
204 uint32 serial_number
,
205 base::Time not_valid_before
,
206 base::Time not_valid_after
,
207 std::string
* der_cert
) {
209 DCHECK(!strncmp(subject
.c_str(), "CN=", 3U));
210 CERTCertificate
* cert
= CreateCertificate(key
->public_key(),
218 if (!SignCertificate(cert
, key
->key(), ToSECOid(alg
))) {
219 CERT_DestroyCertificate(cert
);
223 der_cert
->assign(reinterpret_cast<char*>(cert
->derCert
.data
),
225 CERT_DestroyCertificate(cert
);
229 bool IsSupportedValidityRange(base::Time not_valid_before
,
230 base::Time not_valid_after
) {
231 CERTValidity
* validity
= CERT_CreateValidity(
232 crypto::BaseTimeToPRTime(not_valid_before
),
233 crypto::BaseTimeToPRTime(not_valid_after
));
238 CERT_DestroyValidity(validity
);
242 bool CreateChannelIDEC(crypto::ECPrivateKey
* key
,
244 const std::string
& domain
,
245 uint32 serial_number
,
246 base::Time not_valid_before
,
247 base::Time not_valid_after
,
248 std::string
* der_cert
) {
251 CERTCertificate
* cert
= CreateCertificate(key
->public_key(),
252 "CN=anonymous.invalid",
260 // Create opaque handle used to add extensions later.
262 if ((cert_handle
= CERT_StartCertExtensions(cert
)) == NULL
) {
263 LOG(ERROR
) << "Unable to get opaque handle for adding extensions";
264 CERT_DestroyCertificate(cert
);
268 // Create SECItem for IA5String encoding.
269 SECItem domain_string_item
= {
271 (unsigned char*)domain
.data(),
272 static_cast<unsigned>(domain
.size())
275 // IA5Encode and arena allocate SECItem
276 SECItem
* asn1_domain_string
= SEC_ASN1EncodeItem(
277 cert
->arena
, NULL
, &domain_string_item
,
278 SEC_ASN1_GET(SEC_IA5StringTemplate
));
279 if (asn1_domain_string
== NULL
) {
280 LOG(ERROR
) << "Unable to get ASN1 encoding for domain in domain_bound_cert"
282 CERT_DestroyCertificate(cert
);
286 // Add the extension to the opaque handle
287 if (CERT_AddExtension(
289 ChannelIDOIDWrapper::GetInstance()->domain_bound_cert_oid_tag(),
292 PR_TRUE
) != SECSuccess
){
293 LOG(ERROR
) << "Unable to add domain bound cert extension to opaque handle";
294 CERT_DestroyCertificate(cert
);
298 // Copy extension into x509 cert
299 if (CERT_FinishExtensions(cert_handle
) != SECSuccess
){
300 LOG(ERROR
) << "Unable to copy extension to X509 cert";
301 CERT_DestroyCertificate(cert
);
305 if (!SignCertificate(cert
, key
->key(), ToSECOid(alg
))) {
306 CERT_DestroyCertificate(cert
);
310 DCHECK(cert
->derCert
.len
);
311 // XXX copied from X509Certificate::GetDEREncoded
313 der_cert
->append(reinterpret_cast<char*>(cert
->derCert
.data
),
315 CERT_DestroyCertificate(cert
);
319 } // namespace x509_util