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

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

Issue 2940763002: Move some functions from net/cert/x509_util_nss.cc into x509_certificate_nss.cc (Closed)
Patch Set: . Created 3 years, 6 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
« no previous file with comments | « no previous file | net/cert/x509_util_nss.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 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 <cert.h> 5 #include <cert.h>
6 #include <cryptohi.h> 6 #include <cryptohi.h>
7 #include <keyhi.h> 7 #include <keyhi.h>
8 #include <nss.h> 8 #include <nss.h>
9 #include <pk11pub.h> 9 #include <pk11pub.h>
10 #include <prtime.h> 10 #include <prtime.h>
11 #include <seccomon.h> 11 #include <seccomon.h>
12 #include <secder.h> 12 #include <secder.h>
13 #include <sechash.h> 13 #include <sechash.h>
14 14
15 #include <memory> 15 #include <memory>
16 16
17 #include "base/logging.h" 17 #include "base/logging.h"
18 #include "base/numerics/safe_conversions.h" 18 #include "base/numerics/safe_conversions.h"
19 #include "base/pickle.h" 19 #include "base/pickle.h"
20 #include "base/strings/stringprintf.h" 20 #include "base/strings/stringprintf.h"
21 #include "base/time/time.h" 21 #include "base/time/time.h"
22 #include "crypto/nss_util.h" 22 #include "crypto/nss_util.h"
23 #include "crypto/scoped_nss_types.h" 23 #include "crypto/scoped_nss_types.h"
24 #include "net/cert/x509_certificate.h" 24 #include "net/cert/x509_certificate.h"
25 #include "net/cert/x509_util_nss.h" 25 #include "net/cert/x509_util_nss.h"
26 26
27 namespace net { 27 namespace net {
28 28
29 namespace {
30
31 // Callback for CERT_DecodeCertPackage(), used in
32 // CreateOSCertHandlesFromBytes().
33 SECStatus PR_CALLBACK CollectCertsCallback(void* arg,
34 SECItem** certs,
35 int num_certs) {
36 X509Certificate::OSCertHandles* results =
37 reinterpret_cast<X509Certificate::OSCertHandles*>(arg);
38
39 for (int i = 0; i < num_certs; ++i) {
40 X509Certificate::OSCertHandle handle =
41 X509Certificate::CreateOSCertHandleFromBytes(
42 reinterpret_cast<char*>(certs[i]->data), certs[i]->len);
43 if (handle)
44 results->push_back(handle);
45 }
46
47 return SECSuccess;
48 }
49
50 // Parses the Principal attribute from |name| and outputs the result in
51 // |principal|. Returns true on success.
52 bool ParsePrincipal(CERTName* name, CertPrincipal* principal) {
53 // Starting in NSS 3.15, CERTGetNameFunc takes a const CERTName* argument.
54 #if NSS_VMINOR >= 15
55 typedef char* (*CERTGetNameFunc)(const CERTName* name);
56 #else
57 typedef char* (*CERTGetNameFunc)(CERTName * name);
58 #endif
59
60 // TODO(jcampan): add business_category and serial_number.
61 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
62 // CERT_GetDomainComponentName functions, but they return only the most
63 // general (the first) RDN. NSS doesn't have a function for the street
64 // address.
65 static const SECOidTag kOIDs[] = {
66 SEC_OID_AVA_STREET_ADDRESS, SEC_OID_AVA_ORGANIZATION_NAME,
67 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME, SEC_OID_AVA_DC};
68
69 std::vector<std::string>* values[] = {
70 &principal->street_addresses, &principal->organization_names,
71 &principal->organization_unit_names, &principal->domain_components};
72 DCHECK_EQ(arraysize(kOIDs), arraysize(values));
73
74 CERTRDN** rdns = name->rdns;
75 for (size_t rdn = 0; rdns[rdn]; ++rdn) {
76 CERTAVA** avas = rdns[rdn]->avas;
77 for (size_t pair = 0; avas[pair] != 0; ++pair) {
78 SECOidTag tag = CERT_GetAVATag(avas[pair]);
79 for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
80 if (kOIDs[oid] == tag) {
81 SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
82 if (!decode_item)
83 return false;
84 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
85 std::string value(reinterpret_cast<char*>(decode_item->data),
86 decode_item->len);
87 values[oid]->push_back(value);
88 SECITEM_FreeItem(decode_item, PR_TRUE);
89 break;
90 }
91 }
92 }
93 }
94
95 // Get CN, L, S, and C.
96 CERTGetNameFunc get_name_funcs[4] = {CERT_GetCommonName, CERT_GetLocalityName,
97 CERT_GetStateName, CERT_GetCountryName};
98 std::string* single_values[4] = {
99 &principal->common_name, &principal->locality_name,
100 &principal->state_or_province_name, &principal->country_name};
101 for (size_t i = 0; i < arraysize(get_name_funcs); ++i) {
102 char* value = get_name_funcs[i](name);
103 if (value) {
104 single_values[i]->assign(value);
105 PORT_Free(value);
106 }
107 }
108
109 return true;
110 }
111
112 // Parses the date from |der_date| and outputs the result in |result|.
113 // Returns true on success.
114 bool ParseDate(const SECItem* der_date, base::Time* result) {
115 PRTime prtime;
116 SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
117 if (rv != SECSuccess)
118 return false;
119 *result = crypto::PRTimeToBaseTime(prtime);
120 return true;
121 }
122
123 // Parses the serial number from |certificate|.
124 std::string ParseSerialNumber(const CERTCertificate* certificate) {
125 return std::string(reinterpret_cast<char*>(certificate->serialNumber.data),
126 certificate->serialNumber.len);
127 }
128
129 typedef std::unique_ptr<CERTName,
130 crypto::NSSDestroyer<CERTName, CERT_DestroyName>>
131 ScopedCERTName;
132
133 // Create a new CERTName object from its encoded representation.
134 // |arena| is the allocation pool to use.
135 // |data| points to a DER-encoded X.509 DistinguishedName.
136 // Return a new CERTName pointer on success, or NULL.
137 CERTName* CreateCertNameFromEncoded(PLArenaPool* arena,
138 const base::StringPiece& data) {
139 if (!arena)
140 return NULL;
141
142 ScopedCERTName name(PORT_ArenaZNew(arena, CERTName));
143 if (!name.get())
144 return NULL;
145
146 SECItem item;
147 item.len = static_cast<unsigned int>(data.length());
148 item.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data.data()));
149
150 SECStatus rv = SEC_ASN1DecodeItem(arena, name.get(),
151 SEC_ASN1_GET(CERT_NameTemplate), &item);
152 if (rv != SECSuccess)
153 return NULL;
154
155 return name.release();
156 }
157
158 // Create a list of CERTName objects from a list of DER-encoded X.509
159 // DistinguishedName items. All objects are created in a given arena.
160 // |encoded_issuers| is the list of encoded DNs.
161 // |arena| is the arena used for all allocations.
162 // |out| will receive the result list on success.
163 // Return true on success. On failure, the caller must free the
164 // intermediate CERTName objects pushed to |out|.
165 bool GetIssuersFromEncodedList(const std::vector<std::string>& encoded_issuers,
166 PLArenaPool* arena,
167 std::vector<CERTName*>* out) {
168 std::vector<CERTName*> result;
169 for (size_t n = 0; n < encoded_issuers.size(); ++n) {
170 CERTName* name = CreateCertNameFromEncoded(arena, encoded_issuers[n]);
171 if (name != NULL)
172 result.push_back(name);
173 }
174
175 if (result.size() == encoded_issuers.size()) {
176 out->swap(result);
177 return true;
178 }
179
180 for (size_t n = 0; n < result.size(); ++n)
181 CERT_DestroyName(result[n]);
182 return false;
183 }
184
185 // Returns true iff a certificate is issued by any of the issuers listed
186 // by name in |valid_issuers|.
187 // |cert_chain| is the certificate's chain.
188 // |valid_issuers| is a list of strings, where each string contains
189 // a DER-encoded X.509 Distinguished Name.
190 bool IsCertificateIssuedBy(const std::vector<CERTCertificate*>& cert_chain,
191 const std::vector<CERTName*>& valid_issuers) {
192 for (size_t n = 0; n < cert_chain.size(); ++n) {
193 CERTName* cert_issuer = &cert_chain[n]->issuer;
194 for (size_t i = 0; i < valid_issuers.size(); ++i) {
195 if (CERT_CompareName(valid_issuers[i], cert_issuer) == SECEqual)
196 return true;
197 }
198 }
199 return false;
200 }
201
202 } // namespace
203
29 bool X509Certificate::Initialize() { 204 bool X509Certificate::Initialize() {
30 serial_number_ = x509_util::ParseSerialNumber(cert_handle_); 205 serial_number_ = ParseSerialNumber(cert_handle_);
31 206
32 return ( 207 return (!serial_number_.empty() &&
33 !serial_number_.empty() && 208 ParsePrincipal(&cert_handle_->subject, &subject_) &&
34 x509_util::ParsePrincipal(&cert_handle_->subject, &subject_) && 209 ParsePrincipal(&cert_handle_->issuer, &issuer_) &&
35 x509_util::ParsePrincipal(&cert_handle_->issuer, &issuer_) && 210 ParseDate(&cert_handle_->validity.notBefore, &valid_start_) &&
36 x509_util::ParseDate(&cert_handle_->validity.notBefore, &valid_start_) && 211 ParseDate(&cert_handle_->validity.notAfter, &valid_expiry_));
37 x509_util::ParseDate(&cert_handle_->validity.notAfter, &valid_expiry_));
38 } 212 }
39 213
40 std::string X509Certificate::GetDefaultNickname(CertType type) const { 214 std::string X509Certificate::GetDefaultNickname(CertType type) const {
41 std::string result; 215 std::string result;
42 if (type == USER_CERT && cert_handle_->slot) { 216 if (type == USER_CERT && cert_handle_->slot) {
43 // Find the private key for this certificate and see if it has a 217 // Find the private key for this certificate and see if it has a
44 // nickname. If there is a private key, and it has a nickname, then 218 // nickname. If there is a private key, and it has a nickname, then
45 // return that nickname. 219 // return that nickname.
46 SECKEYPrivateKey* private_key = PK11_FindPrivateKeyFromCert( 220 SECKEYPrivateKey* private_key = PK11_FindPrivateKeyFromCert(
47 cert_handle_->slot, 221 cert_handle_->slot,
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
85 case OTHER_CERT: 259 case OTHER_CERT:
86 default: 260 default:
87 break; 261 break;
88 } 262 }
89 return result; 263 return result;
90 } 264 }
91 265
92 bool X509Certificate::GetSubjectAltName( 266 bool X509Certificate::GetSubjectAltName(
93 std::vector<std::string>* dns_names, 267 std::vector<std::string>* dns_names,
94 std::vector<std::string>* ip_addrs) const { 268 std::vector<std::string>* ip_addrs) const {
95 return x509_util::GetSubjectAltName(cert_handle_, dns_names, ip_addrs); 269 if (dns_names)
270 dns_names->clear();
271 if (ip_addrs)
272 ip_addrs->clear();
273
274 SECItem alt_name;
275 SECStatus rv = CERT_FindCertExtension(
276 cert_handle_, SEC_OID_X509_SUBJECT_ALT_NAME, &alt_name);
277 if (rv != SECSuccess)
278 return false;
279
280 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
281
282 CERTGeneralName* alt_name_list;
283 alt_name_list = CERT_DecodeAltNameExtension(arena.get(), &alt_name);
284 SECITEM_FreeItem(&alt_name, PR_FALSE);
285
286 bool has_san = false;
287 CERTGeneralName* name = alt_name_list;
288 while (name) {
289 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
290 // respectively, both of which can be byte copied from
291 // SECItemType::data into the appropriate output vector.
292 if (name->type == certDNSName) {
293 has_san = true;
294 if (dns_names) {
295 dns_names->push_back(
296 std::string(reinterpret_cast<char*>(name->name.other.data),
297 name->name.other.len));
298 }
299 } else if (name->type == certIPAddress) {
300 has_san = true;
301 if (ip_addrs) {
302 ip_addrs->push_back(
303 std::string(reinterpret_cast<char*>(name->name.other.data),
304 name->name.other.len));
305 }
306 }
307 // Fast path: Found at least one subjectAltName and the caller doesn't
308 // need the actual values.
309 if (has_san && !ip_addrs && !dns_names)
310 return true;
311
312 name = CERT_GetNextGeneralName(name);
313 if (name == alt_name_list)
314 break;
315 }
316 return has_san;
96 } 317 }
97 318
98 bool X509Certificate::IsIssuedByEncoded( 319 bool X509Certificate::IsIssuedByEncoded(
99 const std::vector<std::string>& valid_issuers) { 320 const std::vector<std::string>& valid_issuers) {
100 // Get certificate chain as scoped list of CERTCertificate objects. 321 // Get certificate chain as scoped list of CERTCertificate objects.
101 std::vector<CERTCertificate*> cert_chain; 322 std::vector<CERTCertificate*> cert_chain;
102 cert_chain.push_back(cert_handle_); 323 cert_chain.push_back(cert_handle_);
103 for (size_t n = 0; n < intermediate_ca_certs_.size(); ++n) { 324 for (size_t n = 0; n < intermediate_ca_certs_.size(); ++n) {
104 cert_chain.push_back(intermediate_ca_certs_[n]); 325 cert_chain.push_back(intermediate_ca_certs_[n]);
105 } 326 }
106 // Convert encoded issuers to scoped CERTName* list. 327 // Convert encoded issuers to scoped CERTName* list.
107 std::vector<CERTName*> issuers; 328 std::vector<CERTName*> issuers;
108 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE)); 329 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
109 if (!x509_util::GetIssuersFromEncodedList(valid_issuers, 330 if (!GetIssuersFromEncodedList(valid_issuers, arena.get(), &issuers)) {
110 arena.get(),
111 &issuers)) {
112 return false; 331 return false;
113 } 332 }
114 return x509_util::IsCertificateIssuedBy(cert_chain, issuers); 333 return IsCertificateIssuedBy(cert_chain, issuers);
115 } 334 }
116 335
117 // static 336 // static
118 bool X509Certificate::GetDEREncoded(X509Certificate::OSCertHandle cert_handle, 337 bool X509Certificate::GetDEREncoded(X509Certificate::OSCertHandle cert_handle,
119 std::string* encoded) { 338 std::string* encoded) {
120 if (!cert_handle || !cert_handle->derCert.len) 339 if (!cert_handle || !cert_handle->derCert.len)
121 return false; 340 return false;
122 encoded->assign(reinterpret_cast<char*>(cert_handle->derCert.data), 341 encoded->assign(reinterpret_cast<char*>(cert_handle->derCert.data),
123 cert_handle->derCert.len); 342 cert_handle->derCert.len);
124 return true; 343 return true;
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
160 return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, 379 return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert,
161 const_cast<char*>(nickname), 380 const_cast<char*>(nickname),
162 PR_FALSE, PR_TRUE); 381 PR_FALSE, PR_TRUE);
163 } 382 }
164 383
165 // static 384 // static
166 X509Certificate::OSCertHandles X509Certificate::CreateOSCertHandlesFromBytes( 385 X509Certificate::OSCertHandles X509Certificate::CreateOSCertHandlesFromBytes(
167 const char* data, 386 const char* data,
168 size_t length, 387 size_t length,
169 Format format) { 388 Format format) {
170 return x509_util::CreateOSCertHandlesFromBytes(data, length, format); 389 X509Certificate::OSCertHandles results;
390
391 crypto::EnsureNSSInit();
392
393 if (!NSS_IsInitialized())
394 return results;
395
396 switch (format) {
397 case X509Certificate::FORMAT_SINGLE_CERTIFICATE: {
398 X509Certificate::OSCertHandle handle =
399 X509Certificate::CreateOSCertHandleFromBytes(data, length);
400 if (handle)
401 results.push_back(handle);
402 break;
403 }
404 case X509Certificate::FORMAT_PKCS7: {
405 // Make a copy since CERT_DecodeCertPackage may modify it
406 std::vector<char> data_copy(data, data + length);
407
408 SECStatus result = CERT_DecodeCertPackage(
409 data_copy.data(), base::checked_cast<int>(data_copy.size()),
410 CollectCertsCallback, &results);
411 if (result != SECSuccess)
412 results.clear();
413 break;
414 }
415 default:
416 NOTREACHED() << "Certificate format " << format << " unimplemented";
417 break;
418 }
419
420 return results;
171 } 421 }
172 422
173 // static 423 // static
174 X509Certificate::OSCertHandle X509Certificate::DupOSCertHandle( 424 X509Certificate::OSCertHandle X509Certificate::DupOSCertHandle(
175 OSCertHandle cert_handle) { 425 OSCertHandle cert_handle) {
176 return CERT_DupCertificate(cert_handle); 426 return CERT_DupCertificate(cert_handle);
177 } 427 }
178 428
179 // static 429 // static
180 void X509Certificate::FreeOSCertHandle(OSCertHandle cert_handle) { 430 void X509Certificate::FreeOSCertHandle(OSCertHandle cert_handle) {
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
214 HASH_End(sha256_ctx, sha256.data, &result_len, 464 HASH_End(sha256_ctx, sha256.data, &result_len,
215 HASH_ResultLenContext(sha256_ctx)); 465 HASH_ResultLenContext(sha256_ctx));
216 HASH_Destroy(sha256_ctx); 466 HASH_Destroy(sha256_ctx);
217 467
218 return sha256; 468 return sha256;
219 } 469 }
220 470
221 // static 471 // static
222 X509Certificate::OSCertHandle X509Certificate::ReadOSCertHandleFromPickle( 472 X509Certificate::OSCertHandle X509Certificate::ReadOSCertHandleFromPickle(
223 base::PickleIterator* pickle_iter) { 473 base::PickleIterator* pickle_iter) {
224 return x509_util::ReadOSCertHandleFromPickle(pickle_iter); 474 const char* data;
475 int length;
476 if (!pickle_iter->ReadData(&data, &length))
477 return NULL;
478
479 return CreateOSCertHandleFromBytes(data, length);
225 } 480 }
226 481
227 // static 482 // static
228 bool X509Certificate::WriteOSCertHandleToPickle(OSCertHandle cert_handle, 483 bool X509Certificate::WriteOSCertHandleToPickle(OSCertHandle cert_handle,
229 base::Pickle* pickle) { 484 base::Pickle* pickle) {
230 return pickle->WriteData( 485 return pickle->WriteData(
231 reinterpret_cast<const char*>(cert_handle->derCert.data), 486 reinterpret_cast<const char*>(cert_handle->derCert.data),
232 cert_handle->derCert.len); 487 cert_handle->derCert.len);
233 } 488 }
234 489
235 // static 490 // static
236 void X509Certificate::GetPublicKeyInfo(OSCertHandle cert_handle, 491 void X509Certificate::GetPublicKeyInfo(OSCertHandle cert_handle,
237 size_t* size_bits, 492 size_t* size_bits,
238 PublicKeyType* type) { 493 PublicKeyType* type) {
239 x509_util::GetPublicKeyInfo(cert_handle, size_bits, type); 494 // Since we might fail, set the output parameters to default values first.
495 *type = X509Certificate::kPublicKeyTypeUnknown;
496 *size_bits = 0;
497
498 crypto::ScopedSECKEYPublicKey key(CERT_ExtractPublicKey(cert_handle));
499 if (!key.get())
500 return;
501
502 *size_bits = SECKEY_PublicKeyStrengthInBits(key.get());
503
504 switch (key->keyType) {
505 case rsaKey:
506 *type = X509Certificate::kPublicKeyTypeRSA;
507 break;
508 case dsaKey:
509 *type = X509Certificate::kPublicKeyTypeDSA;
510 break;
511 case dhKey:
512 *type = X509Certificate::kPublicKeyTypeDH;
513 break;
514 case ecKey:
515 *type = X509Certificate::kPublicKeyTypeECDSA;
516 break;
517 default:
518 *type = X509Certificate::kPublicKeyTypeUnknown;
519 *size_bits = 0;
520 break;
521 }
240 } 522 }
241 523
242 // static 524 // static
243 bool X509Certificate::IsSelfSigned(OSCertHandle cert_handle) { 525 bool X509Certificate::IsSelfSigned(OSCertHandle cert_handle) {
244 crypto::ScopedSECKEYPublicKey public_key(CERT_ExtractPublicKey(cert_handle)); 526 crypto::ScopedSECKEYPublicKey public_key(CERT_ExtractPublicKey(cert_handle));
245 if (!public_key.get()) 527 if (!public_key.get())
246 return false; 528 return false;
247 if (SECSuccess != CERT_VerifySignedDataWithPublicKey( 529 if (SECSuccess != CERT_VerifySignedDataWithPublicKey(
248 &cert_handle->signatureWrap, public_key.get(), NULL)) { 530 &cert_handle->signatureWrap, public_key.get(), NULL)) {
249 return false; 531 return false;
250 } 532 }
251 return CERT_CompareName(&cert_handle->subject, &cert_handle->issuer) == 533 return CERT_CompareName(&cert_handle->subject, &cert_handle->issuer) ==
252 SECEqual; 534 SECEqual;
253 } 535 }
254 536
255 } // namespace net 537 } // namespace net
OLDNEW
« no previous file with comments | « no previous file | net/cert/x509_util_nss.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698