Changed GPU Service traces to use nestable async traces.
[chromium-blink-merge.git] / net / cert / x509_util_nss.cc
blobecdf08ba8d741d7b96aaace1669fd69d69874059
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 } // namespace
199 namespace x509_util {
201 bool CreateSelfSignedCert(crypto::RSAPrivateKey* key,
202 DigestAlgorithm alg,
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) {
208 DCHECK(key);
209 DCHECK(!strncmp(subject.c_str(), "CN=", 3U));
210 CERTCertificate* cert = CreateCertificate(key->public_key(),
211 subject,
212 serial_number,
213 not_valid_before,
214 not_valid_after);
215 if (!cert)
216 return false;
218 if (!SignCertificate(cert, key->key(), ToSECOid(alg))) {
219 CERT_DestroyCertificate(cert);
220 return false;
223 der_cert->assign(reinterpret_cast<char*>(cert->derCert.data),
224 cert->derCert.len);
225 CERT_DestroyCertificate(cert);
226 return true;
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));
235 if (!validity)
236 return false;
238 CERT_DestroyValidity(validity);
239 return true;
242 bool CreateChannelIDEC(crypto::ECPrivateKey* key,
243 DigestAlgorithm alg,
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) {
249 DCHECK(key);
251 CERTCertificate* cert = CreateCertificate(key->public_key(),
252 "CN=anonymous.invalid",
253 serial_number,
254 not_valid_before,
255 not_valid_after);
257 if (!cert)
258 return false;
260 // Create opaque handle used to add extensions later.
261 void* cert_handle;
262 if ((cert_handle = CERT_StartCertExtensions(cert)) == NULL) {
263 LOG(ERROR) << "Unable to get opaque handle for adding extensions";
264 CERT_DestroyCertificate(cert);
265 return false;
268 // Create SECItem for IA5String encoding.
269 SECItem domain_string_item = {
270 siAsciiString,
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"
281 " extension";
282 CERT_DestroyCertificate(cert);
283 return false;
286 // Add the extension to the opaque handle
287 if (CERT_AddExtension(
288 cert_handle,
289 ChannelIDOIDWrapper::GetInstance()->domain_bound_cert_oid_tag(),
290 asn1_domain_string,
291 PR_TRUE,
292 PR_TRUE) != SECSuccess){
293 LOG(ERROR) << "Unable to add domain bound cert extension to opaque handle";
294 CERT_DestroyCertificate(cert);
295 return false;
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);
302 return false;
305 if (!SignCertificate(cert, key->key(), ToSECOid(alg))) {
306 CERT_DestroyCertificate(cert);
307 return false;
310 DCHECK(cert->derCert.len);
311 // XXX copied from X509Certificate::GetDEREncoded
312 der_cert->clear();
313 der_cert->append(reinterpret_cast<char*>(cert->derCert.data),
314 cert->derCert.len);
315 CERT_DestroyCertificate(cert);
316 return true;
319 } // namespace x509_util
321 } // namespace net