Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(147)

Side by Side Diff: net/base/x509_util_nss.cc

Issue 8296014: Use NSS to generate Origin-Bound Certs on Win and Mac. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: review changes Created 9 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2011 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.
4
5 #include "net/base/x509_util.h"
6 #include "net/base/x509_util_nss.h"
7
8 #include <cert.h>
9 #include <cryptohi.h>
10 #include <pk11pub.h>
11 #include <prerror.h>
12 #include <secmod.h>
13 #include <secport.h>
14
15 #include "base/debug/leak_annotations.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/singleton.h"
19 #include "crypto/nss_util.h"
20 #include "crypto/nss_util_internal.h"
21 #include "crypto/rsa_private_key.h"
22 #include "crypto/scoped_nss_types.h"
23
24 namespace {
25
26 class ObCertOIDWrapper {
27 public:
28 static ObCertOIDWrapper* GetInstance() {
29 // Instantiated as a leaky singleton to allow the singleton to be
30 // constructed on a worker thead that is not joined when a process
31 // shuts down.
32 return Singleton<ObCertOIDWrapper,
33 LeakySingletonTraits<ObCertOIDWrapper> >::get();
34 }
35
36 SECOidTag ob_cert_oid_tag() const {
37 return ob_cert_oid_tag_;
38 }
39
40 private:
41 friend struct DefaultSingletonTraits<ObCertOIDWrapper>;
42
43 ObCertOIDWrapper();
44
45 SECOidTag ob_cert_oid_tag_;
46
47 DISALLOW_COPY_AND_ASSIGN(ObCertOIDWrapper);
48 };
49
50 ObCertOIDWrapper::ObCertOIDWrapper(): ob_cert_oid_tag_(SEC_OID_UNKNOWN) {
51 // 1.3.6.1.4.1.11129.2.1.6
52 // (iso.org.dod.internet.private.enterprises.google.googleSecurity.
53 // certificateExtensions.originBoundCertificate)
54 static const uint8 kObCertOID[] = {
55 0x2b, 0x06, 0x01, 0x04, 0x01, 0xd6, 0x79, 0x02, 0x01, 0x06
56 };
57 SECOidData oid_data;
58 memset(&oid_data, 0, sizeof(oid_data));
59 oid_data.oid.data = const_cast<uint8*>(kObCertOID);
60 oid_data.oid.len = sizeof(kObCertOID);
61 oid_data.offset = SEC_OID_UNKNOWN;
62 oid_data.desc = "Origin Bound Certificate";
63 oid_data.mechanism = CKM_INVALID_MECHANISM;
64 oid_data.supportedExtension = SUPPORTED_CERT_EXTENSION;
65 ob_cert_oid_tag_ = SECOID_AddEntry(&oid_data);
66 if (ob_cert_oid_tag_ == SEC_OID_UNKNOWN)
67 LOG(ERROR) << "OB_CERT OID tag creation failed";
68 }
69
70 // Creates a Certificate object that may be passed to the SignCertificate
71 // method to generate an X509 certificate.
72 // Returns NULL if an error is encountered in the certificate creation
73 // process.
74 // Caller responsible for freeing returned certificate object.
75 CERTCertificate* CreateCertificate(
76 SECKEYPublicKey* public_key,
77 const std::string& subject,
78 uint32 serial_number,
79 base::TimeDelta valid_duration) {
80 // Create info about public key.
81 CERTSubjectPublicKeyInfo* spki =
82 SECKEY_CreateSubjectPublicKeyInfo(public_key);
83 if (!spki)
84 return NULL;
85
86 // Create the certificate request.
87 CERTName* subject_name =
88 CERT_AsciiToName(const_cast<char*>(subject.c_str()));
89 CERTCertificateRequest* cert_request =
90 CERT_CreateCertificateRequest(subject_name, spki, NULL);
91 SECKEY_DestroySubjectPublicKeyInfo(spki);
92
93 if (!cert_request) {
94 PRErrorCode prerr = PR_GetError();
95 LOG(ERROR) << "Failed to create certificate request: " << prerr;
96 CERT_DestroyName(subject_name);
97 return NULL;
98 }
99
100 PRTime now = PR_Now();
101 PRTime not_after = now + valid_duration.InMicroseconds();
102
103 // Note that the time is now in micro-second unit.
104 CERTValidity* validity = CERT_CreateValidity(now, not_after);
105 CERTCertificate* cert = CERT_CreateCertificate(serial_number, subject_name,
106 validity, cert_request);
107 if (!cert) {
108 PRErrorCode prerr = PR_GetError();
109 LOG(ERROR) << "Failed to create certificate: " << prerr;
110 }
111
112 // Cleanup for resources used to generate the cert.
113 CERT_DestroyName(subject_name);
114 CERT_DestroyValidity(validity);
115 CERT_DestroyCertificateRequest(cert_request);
116
117 return cert;
118 }
119
120 // Signs a certificate object, with |key| generating a new X509Certificate
121 // and destroying the passed certificate object (even when NULL is returned).
122 // The logic of this method references SignCert() in NSS utility certutil:
123 // http://mxr.mozilla.org/security/ident?i=SignCert.
124 // Returns true on success or false if an error is encountered in the
125 // certificate signing process.
126 bool SignCertificate(
127 CERTCertificate* cert,
128 SECKEYPrivateKey* key) {
129 // |arena| is used to encode the cert.
130 PLArenaPool* arena = cert->arena;
131 SECOidTag algo_id = SEC_GetSignatureAlgorithmOidTag(key->keyType,
132 SEC_OID_SHA1);
133 if (algo_id == SEC_OID_UNKNOWN)
134 return false;
135
136 SECStatus rv = SECOID_SetAlgorithmID(arena, &cert->signature, algo_id, 0);
137 if (rv != SECSuccess)
138 return false;
139
140 // Generate a cert of version 3.
141 *(cert->version.data) = 2;
142 cert->version.len = 1;
143
144 SECItem der;
145 der.len = 0;
146 der.data = NULL;
147
148 // Use ASN1 DER to encode the cert.
149 void* encode_result = SEC_ASN1EncodeItem(
150 arena, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate));
151 if (!encode_result)
152 return false;
153
154 // Allocate space to contain the signed cert.
155 SECItem* result = SECITEM_AllocItem(arena, NULL, 0);
156 if (!result)
157 return false;
158
159 // Sign the ASN1 encoded cert and save it to |result|.
160 rv = SEC_DerSignData(arena, result, der.data, der.len, key, algo_id);
161 if (rv != SECSuccess)
162 return false;
163
164 // Save the signed result to the cert.
165 cert->derCert = *result;
166
167 return true;
168 }
169
170 } // namespace
171
172 namespace net {
173
174 namespace x509_util {
175
176 CERTCertificate* CreateSelfSignedCert(
177 SECKEYPublicKey* public_key,
178 SECKEYPrivateKey* private_key,
179 const std::string& subject,
180 uint32 serial_number,
181 base::TimeDelta valid_duration) {
182 CERTCertificate* cert = CreateCertificate(public_key,
183 subject,
184 serial_number,
185 valid_duration);
186 if (!cert)
187 return NULL;
188
189 if (!SignCertificate(cert, private_key)) {
190 CERT_DestroyCertificate(cert);
191 return NULL;
192 }
193
194 return cert;
195 }
196
197 bool CreateOriginBoundCert(
198 crypto::RSAPrivateKey* key,
199 const std::string& origin,
200 uint32 serial_number,
201 base::TimeDelta valid_duration,
202 std::string* der_cert) {
203 DCHECK(key);
204
205 SECKEYPublicKey* public_key;
206 SECKEYPrivateKey* private_key;
207 #if defined(USE_NSS)
208 public_key = key->public_key();
209 private_key = key->key();
210 #else
211 crypto::ScopedSECKEYPublicKey scoped_public_key;
212 crypto::ScopedSECKEYPrivateKey scoped_private_key;
213 {
214 // Based on the NSS RSAPrivateKey::CreateFromPrivateKeyInfoWithParams.
215 // This method currently leaks some memory.
216 // See http://crbug.com/34742.
217 ANNOTATE_SCOPED_MEMORY_LEAK;
218 crypto::EnsureNSSInit();
219
220 std::vector<uint8> key_data;
221 key->ExportPrivateKey(&key_data);
222
223 crypto::ScopedPK11Slot slot(crypto::GetPrivateNSSKeySlot());
224 if (!slot.get())
225 return NULL;
226
227 SECItem der_private_key_info;
228 der_private_key_info.data = const_cast<unsigned char*>(&key_data[0]);
229 der_private_key_info.len = key_data.size();
230 // Allow the private key to be used for key unwrapping, data decryption,
231 // and signature generation.
232 const unsigned int key_usage = KU_KEY_ENCIPHERMENT | KU_DATA_ENCIPHERMENT |
233 KU_DIGITAL_SIGNATURE;
234 SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(
235 slot.get(), &der_private_key_info, NULL, NULL, PR_FALSE, PR_FALSE,
236 key_usage, &private_key, NULL);
237 scoped_private_key.reset(private_key);
238 if (rv != SECSuccess) {
239 NOTREACHED();
240 return NULL;
241 }
242
243 public_key = SECKEY_ConvertToPublicKey(private_key);
244 if (!public_key) {
245 NOTREACHED();
246 return NULL;
247 }
248 scoped_public_key.reset(public_key);
249 }
250 #endif
251
252 CERTCertificate* cert = CreateCertificate(public_key,
253 "CN=anonymous.invalid",
254 serial_number,
255 valid_duration);
256
257 if (!cert)
258 return false;
259
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;
266 }
267
268 // Create SECItem for IA5String encoding.
269 SECItem origin_string_item = {
270 siAsciiString,
271 (unsigned char*)origin.data(),
272 origin.size()
273 };
274
275 // IA5Encode and arena allocate SECItem
276 SECItem* asn1_origin_string = SEC_ASN1EncodeItem(
277 cert->arena, NULL, &origin_string_item,
278 SEC_ASN1_GET(SEC_IA5StringTemplate));
279 if (asn1_origin_string == NULL) {
280 LOG(ERROR) << "Unable to get ASN1 encoding for origin in ob_cert extension";
281 CERT_DestroyCertificate(cert);
282 return false;
283 }
284
285 // Add the extension to the opaque handle
286 if (CERT_AddExtension(cert_handle,
287 ObCertOIDWrapper::GetInstance()->ob_cert_oid_tag(),
288 asn1_origin_string,
289 PR_TRUE, PR_TRUE) != SECSuccess){
290 LOG(ERROR) << "Unable to add origin bound cert extension to opaque handle";
291 CERT_DestroyCertificate(cert);
292 return false;
293 }
294
295 // Copy extension into x509 cert
296 if (CERT_FinishExtensions(cert_handle) != SECSuccess){
297 LOG(ERROR) << "Unable to copy extension to X509 cert";
298 CERT_DestroyCertificate(cert);
299 return false;
300 }
301
302 if (!SignCertificate(cert, private_key)) {
303 CERT_DestroyCertificate(cert);
304 return false;
305 }
306
307 DCHECK(cert->derCert.len);
308 // XXX copied from X509Certificate::GetDEREncoded
309 der_cert->clear();
310 der_cert->append(reinterpret_cast<char*>(cert->derCert.data),
311 cert->derCert.len);
312 CERT_DestroyCertificate(cert);
313 return true;
314 }
315
316 } // namespace x509_util
317
318 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698