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

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

Issue 1882433002: Removing NSS files and USE_OPENSSL flag (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fixing more nits. Created 4 years, 8 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
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "net/cert/x509_util.h"
6 #include "net/cert/x509_util_nss.h"
7
8 #include <cert.h> // Must be included before certdb.h 5 #include <cert.h> // Must be included before certdb.h
9 #include <certdb.h> 6 #include <certdb.h>
10 #include <cryptohi.h> 7 #include <cryptohi.h>
11 #include <nss.h> 8 #include <nss.h>
12 #include <pk11pub.h> 9 #include <pk11pub.h>
13 #include <prerror.h> 10 #include <prerror.h>
14 #include <secder.h> 11 #include <secder.h>
15 #include <secmod.h> 12 #include <secmod.h>
16 #include <secport.h> 13 #include <secport.h>
17 14
18 #include "base/debug/leak_annotations.h" 15 #include "base/debug/leak_annotations.h"
19 #include "base/logging.h" 16 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h" 17 #include "base/memory/scoped_ptr.h"
21 #include "base/memory/singleton.h" 18 #include "base/memory/singleton.h"
19 #include "base/numerics/safe_conversions.h"
22 #include "base/pickle.h" 20 #include "base/pickle.h"
23 #include "base/strings/stringprintf.h" 21 #include "base/strings/stringprintf.h"
24 #include "crypto/ec_private_key.h" 22 #include "crypto/ec_private_key.h"
25 #include "crypto/nss_util.h" 23 #include "crypto/nss_util.h"
26 #include "crypto/nss_util_internal.h" 24 #include "crypto/nss_util_internal.h"
27 #include "crypto/rsa_private_key.h" 25 #include "crypto/rsa_private_key.h"
28 #include "crypto/scoped_nss_types.h" 26 #include "crypto/scoped_nss_types.h"
29 #include "crypto/third_party/nss/chromium-nss.h" 27 #include "crypto/third_party/nss/chromium-nss.h"
30 #include "net/cert/x509_certificate.h" 28 #include "net/cert/x509_certificate.h"
29 #include "net/cert/x509_util.h"
30 #include "net/cert/x509_util_nss.h"
31 31
32 namespace net { 32 namespace net {
33 33
34 namespace { 34 namespace {
35 35
36 // Creates a Certificate object that may be passed to the SignCertificate 36 // Microsoft User Principal Name: 1.3.6.1.4.1.311.20.2.3
37 // method to generate an X509 certificate. 37 const uint8_t kUpnOid[] = {0x2b, 0x6, 0x1, 0x4, 0x1,
38 // Returns NULL if an error is encountered in the certificate creation 38 0x82, 0x37, 0x14, 0x2, 0x3};
39 // process. 39
40 // Caller responsible for freeing returned certificate object. 40 // Callback for CERT_DecodeCertPackage(), used in
41 CERTCertificate* CreateCertificate(SECKEYPublicKey* public_key, 41 // CreateOSCertHandlesFromBytes().
42 const std::string& subject, 42 SECStatus PR_CALLBACK CollectCertsCallback(void* arg,
43 uint32_t serial_number, 43 SECItem** certs,
44 base::Time not_valid_before, 44 int num_certs) {
45 base::Time not_valid_after) { 45 X509Certificate::OSCertHandles* results =
46 // Create info about public key. 46 reinterpret_cast<X509Certificate::OSCertHandles*>(arg);
47 CERTSubjectPublicKeyInfo* spki = 47
48 SECKEY_CreateSubjectPublicKeyInfo(public_key); 48 for (int i = 0; i < num_certs; ++i) {
49 if (!spki) 49 X509Certificate::OSCertHandle handle =
50 X509Certificate::CreateOSCertHandleFromBytes(
51 reinterpret_cast<char*>(certs[i]->data), certs[i]->len);
52 if (handle)
53 results->push_back(handle);
54 }
55
56 return SECSuccess;
57 }
58
59 typedef scoped_ptr<CERTName, crypto::NSSDestroyer<CERTName, CERT_DestroyName>>
60 ScopedCERTName;
61
62 // Create a new CERTName object from its encoded representation.
63 // |arena| is the allocation pool to use.
64 // |data| points to a DER-encoded X.509 DistinguishedName.
65 // Return a new CERTName pointer on success, or NULL.
66 CERTName* CreateCertNameFromEncoded(PLArenaPool* arena,
67 const base::StringPiece& data) {
68 if (!arena)
50 return NULL; 69 return NULL;
51 70
52 // Create the certificate request. 71 ScopedCERTName name(PORT_ArenaZNew(arena, CERTName));
53 CERTName* subject_name = 72 if (!name.get())
54 CERT_AsciiToName(const_cast<char*>(subject.c_str()));
55 CERTCertificateRequest* cert_request =
56 CERT_CreateCertificateRequest(subject_name, spki, NULL);
57 SECKEY_DestroySubjectPublicKeyInfo(spki);
58
59 if (!cert_request) {
60 PRErrorCode prerr = PR_GetError();
61 LOG(ERROR) << "Failed to create certificate request: " << prerr;
62 CERT_DestroyName(subject_name);
63 return NULL; 73 return NULL;
64 } 74
65 75 SECItem item;
66 CERTValidity* validity = CERT_CreateValidity( 76 item.len = static_cast<unsigned int>(data.length());
67 crypto::BaseTimeToPRTime(not_valid_before), 77 item.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data.data()));
68 crypto::BaseTimeToPRTime(not_valid_after)); 78
69 if (!validity) { 79 SECStatus rv = SEC_ASN1DecodeItem(arena, name.get(),
70 PRErrorCode prerr = PR_GetError(); 80 SEC_ASN1_GET(CERT_NameTemplate), &item);
71 LOG(ERROR) << "Failed to create certificate validity object: " << prerr; 81 if (rv != SECSuccess)
72 CERT_DestroyName(subject_name);
73 CERT_DestroyCertificateRequest(cert_request);
74 return NULL; 82 return NULL;
75 } 83
76 CERTCertificate* cert = CERT_CreateCertificate(serial_number, subject_name, 84 return name.release();
77 validity, cert_request); 85 }
78 if (!cert) { 86
79 PRErrorCode prerr = PR_GetError(); 87 } // namespace
80 LOG(ERROR) << "Failed to create certificate: " << prerr; 88
81 } 89 namespace x509_util {
82 90
83 // Cleanup for resources used to generate the cert. 91 void ParsePrincipal(CERTName* name, CertPrincipal* principal) {
84 CERT_DestroyName(subject_name); 92 // Starting in NSS 3.15, CERTGetNameFunc takes a const CERTName* argument.
85 CERT_DestroyValidity(validity); 93 #if NSS_VMINOR >= 15
86 CERT_DestroyCertificateRequest(cert_request); 94 typedef char* (*CERTGetNameFunc)(const CERTName* name);
87 95 #else
88 return cert; 96 typedef char* (*CERTGetNameFunc)(CERTName * name);
89 } 97 #endif
90 98
91 SECOidTag ToSECOid(x509_util::DigestAlgorithm alg) { 99 // TODO(jcampan): add business_category and serial_number.
92 switch (alg) { 100 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
93 case x509_util::DIGEST_SHA1: 101 // CERT_GetDomainComponentName functions, but they return only the most
94 return SEC_OID_SHA1; 102 // general (the first) RDN. NSS doesn't have a function for the street
95 case x509_util::DIGEST_SHA256: 103 // address.
96 return SEC_OID_SHA256; 104 static const SECOidTag kOIDs[] = {
97 } 105 SEC_OID_AVA_STREET_ADDRESS, SEC_OID_AVA_ORGANIZATION_NAME,
98 return SEC_OID_UNKNOWN; 106 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME, SEC_OID_AVA_DC};
99 } 107
100 108 std::vector<std::string>* values[] = {
101 // Signs a certificate object, with |key| generating a new X509Certificate 109 &principal->street_addresses, &principal->organization_names,
102 // and destroying the passed certificate object (even when NULL is returned). 110 &principal->organization_unit_names, &principal->domain_components};
103 // The logic of this method references SignCert() in NSS utility certutil: 111 DCHECK_EQ(arraysize(kOIDs), arraysize(values));
104 // http://mxr.mozilla.org/security/ident?i=SignCert. 112
105 // Returns true on success or false if an error is encountered in the 113 CERTRDN** rdns = name->rdns;
106 // certificate signing process. 114 for (size_t rdn = 0; rdns[rdn]; ++rdn) {
107 bool SignCertificate( 115 CERTAVA** avas = rdns[rdn]->avas;
108 CERTCertificate* cert, 116 for (size_t pair = 0; avas[pair] != 0; ++pair) {
109 SECKEYPrivateKey* key, 117 SECOidTag tag = CERT_GetAVATag(avas[pair]);
110 SECOidTag hash_algorithm) { 118 for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
111 // |arena| is used to encode the cert. 119 if (kOIDs[oid] == tag) {
112 PLArenaPool* arena = cert->arena; 120 SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
113 SECOidTag algo_id = SEC_GetSignatureAlgorithmOidTag(key->keyType, 121 if (!decode_item)
114 hash_algorithm); 122 break;
115 if (algo_id == SEC_OID_UNKNOWN) 123 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
116 return false; 124 std::string value(reinterpret_cast<char*>(decode_item->data),
117 125 decode_item->len);
118 SECStatus rv = SECOID_SetAlgorithmID(arena, &cert->signature, algo_id, 0); 126 values[oid]->push_back(value);
127 SECITEM_FreeItem(decode_item, PR_TRUE);
128 break;
129 }
130 }
131 }
132 }
133
134 // Get CN, L, S, and C.
135 CERTGetNameFunc get_name_funcs[4] = {CERT_GetCommonName, CERT_GetLocalityName,
136 CERT_GetStateName, CERT_GetCountryName};
137 std::string* single_values[4] = {
138 &principal->common_name, &principal->locality_name,
139 &principal->state_or_province_name, &principal->country_name};
140 for (size_t i = 0; i < arraysize(get_name_funcs); ++i) {
141 char* value = get_name_funcs[i](name);
142 if (value) {
143 single_values[i]->assign(value);
144 PORT_Free(value);
145 }
146 }
147 }
148
149 void ParseDate(const SECItem* der_date, base::Time* result) {
150 PRTime prtime;
151 SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
152 DCHECK_EQ(SECSuccess, rv);
153 *result = crypto::PRTimeToBaseTime(prtime);
154 }
155
156 std::string ParseSerialNumber(const CERTCertificate* certificate) {
157 return std::string(reinterpret_cast<char*>(certificate->serialNumber.data),
158 certificate->serialNumber.len);
159 }
160
161 void GetSubjectAltName(CERTCertificate* cert_handle,
162 std::vector<std::string>* dns_names,
163 std::vector<std::string>* ip_addrs) {
164 if (dns_names)
165 dns_names->clear();
166 if (ip_addrs)
167 ip_addrs->clear();
168
169 SECItem alt_name;
170 SECStatus rv = CERT_FindCertExtension(
171 cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, &alt_name);
119 if (rv != SECSuccess) 172 if (rv != SECSuccess)
120 return false; 173 return;
121 174
122 // Generate a cert of version 3. 175 PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
123 *(cert->version.data) = 2; 176 DCHECK(arena != NULL);
124 cert->version.len = 1; 177
125 178 CERTGeneralName* alt_name_list;
126 SECItem der = { siBuffer, NULL, 0 }; 179 alt_name_list = CERT_DecodeAltNameExtension(arena, &alt_name);
127 180 SECITEM_FreeItem(&alt_name, PR_FALSE);
128 // Use ASN1 DER to encode the cert. 181
129 void* encode_result = SEC_ASN1EncodeItem( 182 CERTGeneralName* name = alt_name_list;
130 NULL, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate)); 183 while (name) {
131 if (!encode_result) 184 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
132 return false; 185 // respectively, both of which can be byte copied from
133 186 // SECItemType::data into the appropriate output vector.
134 // Allocate space to contain the signed cert. 187 if (dns_names && name->type == certDNSName) {
135 SECItem result = { siBuffer, NULL, 0 }; 188 dns_names->push_back(
136 189 std::string(reinterpret_cast<char*>(name->name.other.data),
137 // Sign the ASN1 encoded cert and save it to |result|. 190 name->name.other.len));
138 rv = DerSignData(arena, &result, &der, key, algo_id); 191 } else if (ip_addrs && name->type == certIPAddress) {
139 PORT_Free(der.data); 192 ip_addrs->push_back(
140 if (rv != SECSuccess) { 193 std::string(reinterpret_cast<char*>(name->name.other.data),
141 DLOG(ERROR) << "DerSignData: " << PORT_GetError(); 194 name->name.other.len));
142 return false; 195 }
143 } 196 name = CERT_GetNextGeneralName(name);
144 197 if (name == alt_name_list)
145 // Save the signed result to the cert. 198 break;
146 cert->derCert = result; 199 }
147 200 PORT_FreeArena(arena, PR_FALSE);
148 return true; 201 }
149 } 202
150 203 void GetRFC822SubjectAltNames(CERTCertificate* cert_handle,
151 } // namespace 204 std::vector<std::string>* names) {
152 205 crypto::ScopedSECItem alt_name(SECITEM_AllocItem(NULL, NULL, 0));
153 namespace x509_util { 206 DCHECK(alt_name.get());
154 207
155 bool CreateSelfSignedCert(crypto::RSAPrivateKey* key, 208 names->clear();
156 DigestAlgorithm alg, 209 SECStatus rv = CERT_FindCertExtension(
157 const std::string& subject, 210 cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
158 uint32_t serial_number, 211 if (rv != SECSuccess)
159 base::Time not_valid_before, 212 return;
160 base::Time not_valid_after, 213
161 std::string* der_cert) { 214 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
162 DCHECK(key); 215 DCHECK(arena.get());
163 DCHECK(!strncmp(subject.c_str(), "CN=", 3U)); 216
164 CERTCertificate* cert = CreateCertificate(key->public_key(), 217 CERTGeneralName* alt_name_list;
165 subject, 218 alt_name_list = CERT_DecodeAltNameExtension(arena.get(), alt_name.get());
166 serial_number, 219
167 not_valid_before, 220 CERTGeneralName* name = alt_name_list;
168 not_valid_after); 221 while (name) {
169 if (!cert) 222 if (name->type == certRFC822Name) {
170 return false; 223 names->push_back(
171 224 std::string(reinterpret_cast<char*>(name->name.other.data),
172 if (!SignCertificate(cert, key->key(), ToSECOid(alg))) { 225 name->name.other.len));
173 CERT_DestroyCertificate(cert); 226 }
174 return false; 227 name = CERT_GetNextGeneralName(name);
175 } 228 if (name == alt_name_list)
176 229 break;
177 der_cert->assign(reinterpret_cast<char*>(cert->derCert.data), 230 }
178 cert->derCert.len); 231 }
179 CERT_DestroyCertificate(cert); 232
180 return true; 233 void GetUPNSubjectAltNames(CERTCertificate* cert_handle,
181 } 234 std::vector<std::string>* names) {
182 235 crypto::ScopedSECItem alt_name(SECITEM_AllocItem(NULL, NULL, 0));
183 bool GetTLSServerEndPointChannelBinding(const X509Certificate& certificate, 236 DCHECK(alt_name.get());
184 std::string* token) { 237
185 NOTIMPLEMENTED(); 238 names->clear();
239 SECStatus rv = CERT_FindCertExtension(
240 cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
241 if (rv != SECSuccess)
242 return;
243
244 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
245 DCHECK(arena.get());
246
247 CERTGeneralName* alt_name_list;
248 alt_name_list = CERT_DecodeAltNameExtension(arena.get(), alt_name.get());
249
250 CERTGeneralName* name = alt_name_list;
251 while (name) {
252 if (name->type == certOtherName) {
253 OtherName* on = &name->name.OthName;
254 if (on->oid.len == sizeof(kUpnOid) &&
255 memcmp(on->oid.data, kUpnOid, sizeof(kUpnOid)) == 0) {
256 SECItem decoded;
257 if (SEC_QuickDERDecodeItem(arena.get(), &decoded,
258 SEC_ASN1_GET(SEC_UTF8StringTemplate),
259 &name->name.OthName.name) == SECSuccess) {
260 names->push_back(
261 std::string(reinterpret_cast<char*>(decoded.data), decoded.len));
262 }
263 }
264 }
265 name = CERT_GetNextGeneralName(name);
266 if (name == alt_name_list)
267 break;
268 }
269 }
270
271 X509Certificate::OSCertHandles CreateOSCertHandlesFromBytes(
272 const char* data,
273 size_t length,
274 X509Certificate::Format format) {
275 X509Certificate::OSCertHandles results;
276
277 crypto::EnsureNSSInit();
278
279 if (!NSS_IsInitialized())
280 return results;
281
282 switch (format) {
283 case X509Certificate::FORMAT_SINGLE_CERTIFICATE: {
284 X509Certificate::OSCertHandle handle =
285 X509Certificate::CreateOSCertHandleFromBytes(data, length);
286 if (handle)
287 results.push_back(handle);
288 break;
289 }
290 case X509Certificate::FORMAT_PKCS7: {
291 // Make a copy since CERT_DecodeCertPackage may modify it
292 std::vector<char> data_copy(data, data + length);
293
294 SECStatus result = CERT_DecodeCertPackage(
295 data_copy.data(), base::checked_cast<int>(data_copy.size()),
296 CollectCertsCallback, &results);
297 if (result != SECSuccess)
298 results.clear();
299 break;
300 }
301 default:
302 NOTREACHED() << "Certificate format " << format << " unimplemented";
303 break;
304 }
305
306 return results;
307 }
308
309 X509Certificate::OSCertHandle ReadOSCertHandleFromPickle(
310 base::PickleIterator* pickle_iter) {
311 const char* data;
312 int length;
313 if (!pickle_iter->ReadData(&data, &length))
314 return NULL;
315
316 return X509Certificate::CreateOSCertHandleFromBytes(data, length);
317 }
318
319 void GetPublicKeyInfo(CERTCertificate* handle,
320 size_t* size_bits,
321 X509Certificate::PublicKeyType* type) {
322 // Since we might fail, set the output parameters to default values first.
323 *type = X509Certificate::kPublicKeyTypeUnknown;
324 *size_bits = 0;
325
326 crypto::ScopedSECKEYPublicKey key(CERT_ExtractPublicKey(handle));
327 if (!key.get())
328 return;
329
330 *size_bits = SECKEY_PublicKeyStrengthInBits(key.get());
331
332 switch (key->keyType) {
333 case rsaKey:
334 *type = X509Certificate::kPublicKeyTypeRSA;
335 break;
336 case dsaKey:
337 *type = X509Certificate::kPublicKeyTypeDSA;
338 break;
339 case dhKey:
340 *type = X509Certificate::kPublicKeyTypeDH;
341 break;
342 case ecKey:
343 *type = X509Certificate::kPublicKeyTypeECDSA;
344 break;
345 default:
346 *type = X509Certificate::kPublicKeyTypeUnknown;
347 *size_bits = 0;
348 break;
349 }
350 }
351
352 bool GetIssuersFromEncodedList(const std::vector<std::string>& encoded_issuers,
353 PLArenaPool* arena,
354 std::vector<CERTName*>* out) {
355 std::vector<CERTName*> result;
356 for (size_t n = 0; n < encoded_issuers.size(); ++n) {
357 CERTName* name = CreateCertNameFromEncoded(arena, encoded_issuers[n]);
358 if (name != NULL)
359 result.push_back(name);
360 }
361
362 if (result.size() == encoded_issuers.size()) {
363 out->swap(result);
364 return true;
365 }
366
367 for (size_t n = 0; n < result.size(); ++n)
368 CERT_DestroyName(result[n]);
186 return false; 369 return false;
187 } 370 }
188 371
189 } // namespace x509_util 372 bool IsCertificateIssuedBy(const std::vector<CERTCertificate*>& cert_chain,
190 373 const std::vector<CERTName*>& valid_issuers) {
191 } // namespace net 374 for (size_t n = 0; n < cert_chain.size(); ++n) {
375 CERTName* cert_issuer = &cert_chain[n]->issuer;
376 for (size_t i = 0; i < valid_issuers.size(); ++i) {
377 if (CERT_CompareName(valid_issuers[i], cert_issuer) == SECEqual)
378 return true;
379 }
380 }
381 return false;
382 }
383
384 std::string GetUniqueNicknameForSlot(const std::string& nickname,
385 const SECItem* subject,
386 PK11SlotInfo* slot) {
387 int index = 2;
388 std::string new_name = nickname;
389 std::string temp_nickname = new_name;
390 std::string token_name;
391
392 if (!slot)
393 return new_name;
394
395 if (!PK11_IsInternalKeySlot(slot)) {
396 token_name.assign(PK11_GetTokenName(slot));
397 token_name.append(":");
398
399 temp_nickname = token_name + new_name;
400 }
401
402 while (SEC_CertNicknameConflict(temp_nickname.c_str(),
403 const_cast<SECItem*>(subject),
404 CERT_GetDefaultCertDB())) {
405 base::SStringPrintf(&new_name, "%s #%d", nickname.c_str(), index++);
406 temp_nickname = token_name + new_name;
407 }
408
409 return new_name;
410 }
411
412 } // namespace x509_util
413
414 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698