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

Side by Side Diff: net/cert/x509_util_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 | « net/cert/x509_util_nss.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2015 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_nss.h"
6
5 #include <cert.h> // Must be included before certdb.h 7 #include <cert.h> // Must be included before certdb.h
6 #include <certdb.h> 8 #include <certdb.h>
7 #include <cryptohi.h> 9 #include <cryptohi.h>
8 #include <nss.h> 10 #include <nss.h>
9 #include <pk11pub.h> 11 #include <pk11pub.h>
10 #include <prerror.h> 12 #include <prerror.h>
11 #include <secder.h> 13 #include <secder.h>
12 #include <secmod.h> 14 #include <secmod.h>
13 #include <secport.h> 15 #include <secport.h>
14 16
15 #include <memory>
16
17 #include "base/debug/leak_annotations.h"
18 #include "base/logging.h" 17 #include "base/logging.h"
19 #include "base/memory/singleton.h"
20 #include "base/numerics/safe_conversions.h"
21 #include "base/pickle.h"
22 #include "base/strings/stringprintf.h" 18 #include "base/strings/stringprintf.h"
23 #include "crypto/ec_private_key.h"
24 #include "crypto/nss_util.h"
25 #include "crypto/nss_util_internal.h"
26 #include "crypto/rsa_private_key.h"
27 #include "crypto/scoped_nss_types.h" 19 #include "crypto/scoped_nss_types.h"
28 #include "net/cert/x509_certificate.h"
29 #include "net/cert/x509_util.h"
30 #include "net/cert/x509_util_nss.h"
31 20
32 namespace net { 21 namespace net {
33 22
34 namespace { 23 namespace {
35 24
36 // Microsoft User Principal Name: 1.3.6.1.4.1.311.20.2.3 25 // Microsoft User Principal Name: 1.3.6.1.4.1.311.20.2.3
37 const uint8_t kUpnOid[] = {0x2b, 0x6, 0x1, 0x4, 0x1, 26 const uint8_t kUpnOid[] = {0x2b, 0x6, 0x1, 0x4, 0x1,
38 0x82, 0x37, 0x14, 0x2, 0x3}; 27 0x82, 0x37, 0x14, 0x2, 0x3};
39 28
40 // Callback for CERT_DecodeCertPackage(), used in
41 // CreateOSCertHandlesFromBytes().
42 SECStatus PR_CALLBACK CollectCertsCallback(void* arg,
43 SECItem** certs,
44 int num_certs) {
45 X509Certificate::OSCertHandles* results =
46 reinterpret_cast<X509Certificate::OSCertHandles*>(arg);
47
48 for (int i = 0; i < num_certs; ++i) {
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 std::unique_ptr<CERTName,
60 crypto::NSSDestroyer<CERTName, CERT_DestroyName>>
61 ScopedCERTName;
62
63 // Create a new CERTName object from its encoded representation.
64 // |arena| is the allocation pool to use.
65 // |data| points to a DER-encoded X.509 DistinguishedName.
66 // Return a new CERTName pointer on success, or NULL.
67 CERTName* CreateCertNameFromEncoded(PLArenaPool* arena,
68 const base::StringPiece& data) {
69 if (!arena)
70 return NULL;
71
72 ScopedCERTName name(PORT_ArenaZNew(arena, CERTName));
73 if (!name.get())
74 return NULL;
75
76 SECItem item;
77 item.len = static_cast<unsigned int>(data.length());
78 item.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data.data()));
79
80 SECStatus rv = SEC_ASN1DecodeItem(arena, name.get(),
81 SEC_ASN1_GET(CERT_NameTemplate), &item);
82 if (rv != SECSuccess)
83 return NULL;
84
85 return name.release();
86 }
87
88 } // namespace 29 } // namespace
89 30
90 namespace x509_util { 31 namespace x509_util {
91 32
92 bool ParsePrincipal(CERTName* name, CertPrincipal* principal) {
93 // Starting in NSS 3.15, CERTGetNameFunc takes a const CERTName* argument.
94 #if NSS_VMINOR >= 15
95 typedef char* (*CERTGetNameFunc)(const CERTName* name);
96 #else
97 typedef char* (*CERTGetNameFunc)(CERTName * name);
98 #endif
99
100 // TODO(jcampan): add business_category and serial_number.
101 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
102 // CERT_GetDomainComponentName functions, but they return only the most
103 // general (the first) RDN. NSS doesn't have a function for the street
104 // address.
105 static const SECOidTag kOIDs[] = {
106 SEC_OID_AVA_STREET_ADDRESS, SEC_OID_AVA_ORGANIZATION_NAME,
107 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME, SEC_OID_AVA_DC};
108
109 std::vector<std::string>* values[] = {
110 &principal->street_addresses, &principal->organization_names,
111 &principal->organization_unit_names, &principal->domain_components};
112 DCHECK_EQ(arraysize(kOIDs), arraysize(values));
113
114 CERTRDN** rdns = name->rdns;
115 for (size_t rdn = 0; rdns[rdn]; ++rdn) {
116 CERTAVA** avas = rdns[rdn]->avas;
117 for (size_t pair = 0; avas[pair] != 0; ++pair) {
118 SECOidTag tag = CERT_GetAVATag(avas[pair]);
119 for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
120 if (kOIDs[oid] == tag) {
121 SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
122 if (!decode_item)
123 return false;
124 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
125 std::string value(reinterpret_cast<char*>(decode_item->data),
126 decode_item->len);
127 values[oid]->push_back(value);
128 SECITEM_FreeItem(decode_item, PR_TRUE);
129 break;
130 }
131 }
132 }
133 }
134
135 // Get CN, L, S, and C.
136 CERTGetNameFunc get_name_funcs[4] = {CERT_GetCommonName, CERT_GetLocalityName,
137 CERT_GetStateName, CERT_GetCountryName};
138 std::string* single_values[4] = {
139 &principal->common_name, &principal->locality_name,
140 &principal->state_or_province_name, &principal->country_name};
141 for (size_t i = 0; i < arraysize(get_name_funcs); ++i) {
142 char* value = get_name_funcs[i](name);
143 if (value) {
144 single_values[i]->assign(value);
145 PORT_Free(value);
146 }
147 }
148
149 return true;
150 }
151
152 bool ParseDate(const SECItem* der_date, base::Time* result) {
153 PRTime prtime;
154 SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
155 if (rv != SECSuccess)
156 return false;
157 *result = crypto::PRTimeToBaseTime(prtime);
158 return true;
159 }
160
161 std::string ParseSerialNumber(const CERTCertificate* certificate) {
162 return std::string(reinterpret_cast<char*>(certificate->serialNumber.data),
163 certificate->serialNumber.len);
164 }
165
166 bool GetSubjectAltName(CERTCertificate* cert_handle,
167 std::vector<std::string>* dns_names,
168 std::vector<std::string>* ip_addrs) {
169 if (dns_names)
170 dns_names->clear();
171 if (ip_addrs)
172 ip_addrs->clear();
173
174 SECItem alt_name;
175 SECStatus rv = CERT_FindCertExtension(
176 cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, &alt_name);
177 if (rv != SECSuccess)
178 return false;
179
180 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
181
182 CERTGeneralName* alt_name_list;
183 alt_name_list = CERT_DecodeAltNameExtension(arena.get(), &alt_name);
184 SECITEM_FreeItem(&alt_name, PR_FALSE);
185
186 bool has_san = false;
187 CERTGeneralName* name = alt_name_list;
188 while (name) {
189 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
190 // respectively, both of which can be byte copied from
191 // SECItemType::data into the appropriate output vector.
192 if (name->type == certDNSName) {
193 has_san = true;
194 if (dns_names) {
195 dns_names->push_back(
196 std::string(reinterpret_cast<char*>(name->name.other.data),
197 name->name.other.len));
198 }
199 } else if (name->type == certIPAddress) {
200 has_san = true;
201 if (ip_addrs) {
202 ip_addrs->push_back(
203 std::string(reinterpret_cast<char*>(name->name.other.data),
204 name->name.other.len));
205 }
206 }
207 // Fast path: Found at least one subjectAltName and the caller doesn't
208 // need the actual values.
209 if (has_san && !ip_addrs && !dns_names)
210 return true;
211
212 name = CERT_GetNextGeneralName(name);
213 if (name == alt_name_list)
214 break;
215 }
216 return has_san;
217 }
218 33
219 void GetRFC822SubjectAltNames(CERTCertificate* cert_handle, 34 void GetRFC822SubjectAltNames(CERTCertificate* cert_handle,
220 std::vector<std::string>* names) { 35 std::vector<std::string>* names) {
221 crypto::ScopedSECItem alt_name(SECITEM_AllocItem(NULL, NULL, 0)); 36 crypto::ScopedSECItem alt_name(SECITEM_AllocItem(NULL, NULL, 0));
222 DCHECK(alt_name.get()); 37 DCHECK(alt_name.get());
223 38
224 names->clear(); 39 names->clear();
225 SECStatus rv = CERT_FindCertExtension( 40 SECStatus rv = CERT_FindCertExtension(
226 cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get()); 41 cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
227 if (rv != SECSuccess) 42 if (rv != SECSuccess)
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
277 std::string(reinterpret_cast<char*>(decoded.data), decoded.len)); 92 std::string(reinterpret_cast<char*>(decoded.data), decoded.len));
278 } 93 }
279 } 94 }
280 } 95 }
281 name = CERT_GetNextGeneralName(name); 96 name = CERT_GetNextGeneralName(name);
282 if (name == alt_name_list) 97 if (name == alt_name_list)
283 break; 98 break;
284 } 99 }
285 } 100 }
286 101
287 X509Certificate::OSCertHandles CreateOSCertHandlesFromBytes(
288 const char* data,
289 size_t length,
290 X509Certificate::Format format) {
291 X509Certificate::OSCertHandles results;
292
293 crypto::EnsureNSSInit();
294
295 if (!NSS_IsInitialized())
296 return results;
297
298 switch (format) {
299 case X509Certificate::FORMAT_SINGLE_CERTIFICATE: {
300 X509Certificate::OSCertHandle handle =
301 X509Certificate::CreateOSCertHandleFromBytes(data, length);
302 if (handle)
303 results.push_back(handle);
304 break;
305 }
306 case X509Certificate::FORMAT_PKCS7: {
307 // Make a copy since CERT_DecodeCertPackage may modify it
308 std::vector<char> data_copy(data, data + length);
309
310 SECStatus result = CERT_DecodeCertPackage(
311 data_copy.data(), base::checked_cast<int>(data_copy.size()),
312 CollectCertsCallback, &results);
313 if (result != SECSuccess)
314 results.clear();
315 break;
316 }
317 default:
318 NOTREACHED() << "Certificate format " << format << " unimplemented";
319 break;
320 }
321
322 return results;
323 }
324
325 X509Certificate::OSCertHandle ReadOSCertHandleFromPickle(
326 base::PickleIterator* pickle_iter) {
327 const char* data;
328 int length;
329 if (!pickle_iter->ReadData(&data, &length))
330 return NULL;
331
332 return X509Certificate::CreateOSCertHandleFromBytes(data, length);
333 }
334
335 void GetPublicKeyInfo(CERTCertificate* handle,
336 size_t* size_bits,
337 X509Certificate::PublicKeyType* type) {
338 // Since we might fail, set the output parameters to default values first.
339 *type = X509Certificate::kPublicKeyTypeUnknown;
340 *size_bits = 0;
341
342 crypto::ScopedSECKEYPublicKey key(CERT_ExtractPublicKey(handle));
343 if (!key.get())
344 return;
345
346 *size_bits = SECKEY_PublicKeyStrengthInBits(key.get());
347
348 switch (key->keyType) {
349 case rsaKey:
350 *type = X509Certificate::kPublicKeyTypeRSA;
351 break;
352 case dsaKey:
353 *type = X509Certificate::kPublicKeyTypeDSA;
354 break;
355 case dhKey:
356 *type = X509Certificate::kPublicKeyTypeDH;
357 break;
358 case ecKey:
359 *type = X509Certificate::kPublicKeyTypeECDSA;
360 break;
361 default:
362 *type = X509Certificate::kPublicKeyTypeUnknown;
363 *size_bits = 0;
364 break;
365 }
366 }
367
368 bool GetIssuersFromEncodedList(const std::vector<std::string>& encoded_issuers,
369 PLArenaPool* arena,
370 std::vector<CERTName*>* out) {
371 std::vector<CERTName*> result;
372 for (size_t n = 0; n < encoded_issuers.size(); ++n) {
373 CERTName* name = CreateCertNameFromEncoded(arena, encoded_issuers[n]);
374 if (name != NULL)
375 result.push_back(name);
376 }
377
378 if (result.size() == encoded_issuers.size()) {
379 out->swap(result);
380 return true;
381 }
382
383 for (size_t n = 0; n < result.size(); ++n)
384 CERT_DestroyName(result[n]);
385 return false;
386 }
387
388 bool IsCertificateIssuedBy(const std::vector<CERTCertificate*>& cert_chain,
389 const std::vector<CERTName*>& valid_issuers) {
390 for (size_t n = 0; n < cert_chain.size(); ++n) {
391 CERTName* cert_issuer = &cert_chain[n]->issuer;
392 for (size_t i = 0; i < valid_issuers.size(); ++i) {
393 if (CERT_CompareName(valid_issuers[i], cert_issuer) == SECEqual)
394 return true;
395 }
396 }
397 return false;
398 }
399
400 std::string GetUniqueNicknameForSlot(const std::string& nickname, 102 std::string GetUniqueNicknameForSlot(const std::string& nickname,
401 const SECItem* subject, 103 const SECItem* subject,
402 PK11SlotInfo* slot) { 104 PK11SlotInfo* slot) {
403 int index = 2; 105 int index = 2;
404 std::string new_name = nickname; 106 std::string new_name = nickname;
405 std::string temp_nickname = new_name; 107 std::string temp_nickname = new_name;
406 std::string token_name; 108 std::string token_name;
407 109
408 if (!slot) 110 if (!slot)
409 return new_name; 111 return new_name;
(...skipping 11 matching lines...) Expand all
421 base::SStringPrintf(&new_name, "%s #%d", nickname.c_str(), index++); 123 base::SStringPrintf(&new_name, "%s #%d", nickname.c_str(), index++);
422 temp_nickname = token_name + new_name; 124 temp_nickname = token_name + new_name;
423 } 125 }
424 126
425 return new_name; 127 return new_name;
426 } 128 }
427 129
428 } // namespace x509_util 130 } // namespace x509_util
429 131
430 } // namespace net 132 } // namespace net
OLDNEW
« no previous file with comments | « net/cert/x509_util_nss.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698