move SK_DISABLE_DITHER_32BIT_GRADIENT from SkUserConfig.h to skia.gyp, so we can...
[chromium-blink-merge.git] / net / base / x509_util_nss.cc
blobc86b9c5db8b9e013d0bbd4eb4c2795ab77554d11
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/base/x509_util.h"
6 #include "net/base/x509_util_nss.h"
8 #include <cert.h>
9 #include <cryptohi.h>
10 #include <nss.h>
11 #include <pk11pub.h>
12 #include <prerror.h>
13 #include <secder.h>
14 #include <secmod.h>
15 #include <secport.h>
17 #include "base/debug/leak_annotations.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/singleton.h"
21 #include "base/pickle.h"
22 #include "crypto/ec_private_key.h"
23 #include "crypto/nss_util.h"
24 #include "crypto/nss_util_internal.h"
25 #include "crypto/scoped_nss_types.h"
26 #include "crypto/third_party/nss/chromium-nss.h"
27 #include "net/base/x509_certificate.h"
29 namespace net {
31 namespace {
33 class DomainBoundCertOIDWrapper {
34 public:
35 static DomainBoundCertOIDWrapper* GetInstance() {
36 // Instantiated as a leaky singleton to allow the singleton to be
37 // constructed on a worker thead that is not joined when a process
38 // shuts down.
39 return Singleton<DomainBoundCertOIDWrapper,
40 LeakySingletonTraits<DomainBoundCertOIDWrapper> >::get();
43 SECOidTag domain_bound_cert_oid_tag() const {
44 return domain_bound_cert_oid_tag_;
47 private:
48 friend struct DefaultSingletonTraits<DomainBoundCertOIDWrapper>;
50 DomainBoundCertOIDWrapper();
52 SECOidTag domain_bound_cert_oid_tag_;
54 DISALLOW_COPY_AND_ASSIGN(DomainBoundCertOIDWrapper);
57 DomainBoundCertOIDWrapper::DomainBoundCertOIDWrapper()
58 : domain_bound_cert_oid_tag_(SEC_OID_UNKNOWN) {
59 // 1.3.6.1.4.1.11129.2.1.6
60 // (iso.org.dod.internet.private.enterprises.google.googleSecurity.
61 // certificateExtensions.originBoundCertificate)
62 static const uint8 kObCertOID[] = {
63 0x2b, 0x06, 0x01, 0x04, 0x01, 0xd6, 0x79, 0x02, 0x01, 0x06
65 SECOidData oid_data;
66 memset(&oid_data, 0, sizeof(oid_data));
67 oid_data.oid.data = const_cast<uint8*>(kObCertOID);
68 oid_data.oid.len = sizeof(kObCertOID);
69 oid_data.offset = SEC_OID_UNKNOWN;
70 oid_data.desc = "Origin Bound Certificate";
71 oid_data.mechanism = CKM_INVALID_MECHANISM;
72 oid_data.supportedExtension = SUPPORTED_CERT_EXTENSION;
73 domain_bound_cert_oid_tag_ = SECOID_AddEntry(&oid_data);
74 if (domain_bound_cert_oid_tag_ == SEC_OID_UNKNOWN)
75 LOG(ERROR) << "OB_CERT OID tag creation failed";
78 // Creates a Certificate object that may be passed to the SignCertificate
79 // method to generate an X509 certificate.
80 // Returns NULL if an error is encountered in the certificate creation
81 // process.
82 // Caller responsible for freeing returned certificate object.
83 CERTCertificate* CreateCertificate(
84 SECKEYPublicKey* public_key,
85 const std::string& subject,
86 uint32 serial_number,
87 base::Time not_valid_before,
88 base::Time not_valid_after) {
89 // Create info about public key.
90 CERTSubjectPublicKeyInfo* spki =
91 SECKEY_CreateSubjectPublicKeyInfo(public_key);
92 if (!spki)
93 return NULL;
95 // Create the certificate request.
96 CERTName* subject_name =
97 CERT_AsciiToName(const_cast<char*>(subject.c_str()));
98 CERTCertificateRequest* cert_request =
99 CERT_CreateCertificateRequest(subject_name, spki, NULL);
100 SECKEY_DestroySubjectPublicKeyInfo(spki);
102 if (!cert_request) {
103 PRErrorCode prerr = PR_GetError();
104 LOG(ERROR) << "Failed to create certificate request: " << prerr;
105 CERT_DestroyName(subject_name);
106 return NULL;
109 CERTValidity* validity = CERT_CreateValidity(
110 crypto::BaseTimeToPRTime(not_valid_before),
111 crypto::BaseTimeToPRTime(not_valid_after));
112 if (!validity) {
113 PRErrorCode prerr = PR_GetError();
114 LOG(ERROR) << "Failed to create certificate validity object: " << prerr;
115 CERT_DestroyName(subject_name);
116 CERT_DestroyCertificateRequest(cert_request);
117 return NULL;
119 CERTCertificate* cert = CERT_CreateCertificate(serial_number, subject_name,
120 validity, cert_request);
121 if (!cert) {
122 PRErrorCode prerr = PR_GetError();
123 LOG(ERROR) << "Failed to create certificate: " << prerr;
126 // Cleanup for resources used to generate the cert.
127 CERT_DestroyName(subject_name);
128 CERT_DestroyValidity(validity);
129 CERT_DestroyCertificateRequest(cert_request);
131 return cert;
134 // Signs a certificate object, with |key| generating a new X509Certificate
135 // and destroying the passed certificate object (even when NULL is returned).
136 // The logic of this method references SignCert() in NSS utility certutil:
137 // http://mxr.mozilla.org/security/ident?i=SignCert.
138 // Returns true on success or false if an error is encountered in the
139 // certificate signing process.
140 bool SignCertificate(
141 CERTCertificate* cert,
142 SECKEYPrivateKey* key) {
143 // |arena| is used to encode the cert.
144 PLArenaPool* arena = cert->arena;
145 SECOidTag algo_id = SEC_GetSignatureAlgorithmOidTag(key->keyType,
146 SEC_OID_SHA1);
147 if (algo_id == SEC_OID_UNKNOWN)
148 return false;
150 SECStatus rv = SECOID_SetAlgorithmID(arena, &cert->signature, algo_id, 0);
151 if (rv != SECSuccess)
152 return false;
154 // Generate a cert of version 3.
155 *(cert->version.data) = 2;
156 cert->version.len = 1;
158 SECItem der = { siBuffer, NULL, 0 };
160 // Use ASN1 DER to encode the cert.
161 void* encode_result = SEC_ASN1EncodeItem(
162 NULL, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate));
163 if (!encode_result)
164 return false;
166 // Allocate space to contain the signed cert.
167 SECItem result = { siBuffer, NULL, 0 };
169 // Sign the ASN1 encoded cert and save it to |result|.
170 rv = DerSignData(arena, &result, &der, key, algo_id);
171 PORT_Free(der.data);
172 if (rv != SECSuccess) {
173 DLOG(ERROR) << "DerSignData: " << PORT_GetError();
174 return false;
177 // Save the signed result to the cert.
178 cert->derCert = result;
180 return true;
183 bool CreateDomainBoundCertInternal(
184 SECKEYPublicKey* public_key,
185 SECKEYPrivateKey* private_key,
186 const std::string& domain,
187 uint32 serial_number,
188 base::Time not_valid_before,
189 base::Time not_valid_after,
190 std::string* der_cert) {
191 CERTCertificate* cert = CreateCertificate(public_key,
192 "CN=anonymous.invalid",
193 serial_number,
194 not_valid_before,
195 not_valid_after);
197 if (!cert)
198 return false;
200 // Create opaque handle used to add extensions later.
201 void* cert_handle;
202 if ((cert_handle = CERT_StartCertExtensions(cert)) == NULL) {
203 LOG(ERROR) << "Unable to get opaque handle for adding extensions";
204 CERT_DestroyCertificate(cert);
205 return false;
208 // Create SECItem for IA5String encoding.
209 SECItem domain_string_item = {
210 siAsciiString,
211 (unsigned char*)domain.data(),
212 static_cast<unsigned>(domain.size())
215 // IA5Encode and arena allocate SECItem
216 SECItem* asn1_domain_string = SEC_ASN1EncodeItem(
217 cert->arena, NULL, &domain_string_item,
218 SEC_ASN1_GET(SEC_IA5StringTemplate));
219 if (asn1_domain_string == NULL) {
220 LOG(ERROR) << "Unable to get ASN1 encoding for domain in domain_bound_cert"
221 " extension";
222 CERT_DestroyCertificate(cert);
223 return false;
226 // Add the extension to the opaque handle
227 if (CERT_AddExtension(
228 cert_handle,
229 DomainBoundCertOIDWrapper::GetInstance()->domain_bound_cert_oid_tag(),
230 asn1_domain_string, PR_TRUE, PR_TRUE) != SECSuccess){
231 LOG(ERROR) << "Unable to add domain bound cert extension to opaque handle";
232 CERT_DestroyCertificate(cert);
233 return false;
236 // Copy extension into x509 cert
237 if (CERT_FinishExtensions(cert_handle) != SECSuccess){
238 LOG(ERROR) << "Unable to copy extension to X509 cert";
239 CERT_DestroyCertificate(cert);
240 return false;
243 if (!SignCertificate(cert, private_key)) {
244 CERT_DestroyCertificate(cert);
245 return false;
248 DCHECK(cert->derCert.len);
249 // XXX copied from X509Certificate::GetDEREncoded
250 der_cert->clear();
251 der_cert->append(reinterpret_cast<char*>(cert->derCert.data),
252 cert->derCert.len);
253 CERT_DestroyCertificate(cert);
254 return true;
257 #if defined(USE_NSS) || defined(OS_IOS)
258 // Callback for CERT_DecodeCertPackage(), used in
259 // CreateOSCertHandlesFromBytes().
260 SECStatus PR_CALLBACK CollectCertsCallback(void* arg,
261 SECItem** certs,
262 int num_certs) {
263 X509Certificate::OSCertHandles* results =
264 reinterpret_cast<X509Certificate::OSCertHandles*>(arg);
266 for (int i = 0; i < num_certs; ++i) {
267 X509Certificate::OSCertHandle handle =
268 X509Certificate::CreateOSCertHandleFromBytes(
269 reinterpret_cast<char*>(certs[i]->data), certs[i]->len);
270 if (handle)
271 results->push_back(handle);
274 return SECSuccess;
276 #endif // defined(USE_NSS) || defined(OS_IOS)
278 } // namespace
280 namespace x509_util {
282 CERTCertificate* CreateSelfSignedCert(
283 SECKEYPublicKey* public_key,
284 SECKEYPrivateKey* private_key,
285 const std::string& subject,
286 uint32 serial_number,
287 base::Time not_valid_before,
288 base::Time not_valid_after) {
289 CERTCertificate* cert = CreateCertificate(public_key,
290 subject,
291 serial_number,
292 not_valid_before,
293 not_valid_after);
294 if (!cert)
295 return NULL;
297 if (!SignCertificate(cert, private_key)) {
298 CERT_DestroyCertificate(cert);
299 return NULL;
302 return cert;
305 bool IsSupportedValidityRange(base::Time not_valid_before,
306 base::Time not_valid_after) {
307 CERTValidity* validity = CERT_CreateValidity(
308 crypto::BaseTimeToPRTime(not_valid_before),
309 crypto::BaseTimeToPRTime(not_valid_after));
311 if (!validity)
312 return false;
314 CERT_DestroyValidity(validity);
315 return true;
318 bool CreateDomainBoundCertEC(
319 crypto::ECPrivateKey* key,
320 const std::string& domain,
321 uint32 serial_number,
322 base::Time not_valid_before,
323 base::Time not_valid_after,
324 std::string* der_cert) {
325 DCHECK(key);
326 return CreateDomainBoundCertInternal(key->public_key(),
327 key->key(),
328 domain,
329 serial_number,
330 not_valid_before,
331 not_valid_after,
332 der_cert);
335 #if defined(USE_NSS) || defined(OS_IOS)
336 void ParsePrincipal(CERTName* name, CertPrincipal* principal) {
337 typedef char* (*CERTGetNameFunc)(CERTName* name);
339 // TODO(jcampan): add business_category and serial_number.
340 // TODO(wtc): NSS has the CERT_GetOrgName, CERT_GetOrgUnitName, and
341 // CERT_GetDomainComponentName functions, but they return only the most
342 // general (the first) RDN. NSS doesn't have a function for the street
343 // address.
344 static const SECOidTag kOIDs[] = {
345 SEC_OID_AVA_STREET_ADDRESS,
346 SEC_OID_AVA_ORGANIZATION_NAME,
347 SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
348 SEC_OID_AVA_DC };
350 std::vector<std::string>* values[] = {
351 &principal->street_addresses,
352 &principal->organization_names,
353 &principal->organization_unit_names,
354 &principal->domain_components };
355 DCHECK_EQ(arraysize(kOIDs), arraysize(values));
357 CERTRDN** rdns = name->rdns;
358 for (size_t rdn = 0; rdns[rdn]; ++rdn) {
359 CERTAVA** avas = rdns[rdn]->avas;
360 for (size_t pair = 0; avas[pair] != 0; ++pair) {
361 SECOidTag tag = CERT_GetAVATag(avas[pair]);
362 for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
363 if (kOIDs[oid] == tag) {
364 SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
365 if (!decode_item)
366 break;
367 // TODO(wtc): Pass decode_item to CERT_RFC1485_EscapeAndQuote.
368 std::string value(reinterpret_cast<char*>(decode_item->data),
369 decode_item->len);
370 values[oid]->push_back(value);
371 SECITEM_FreeItem(decode_item, PR_TRUE);
372 break;
378 // Get CN, L, S, and C.
379 CERTGetNameFunc get_name_funcs[4] = {
380 CERT_GetCommonName, CERT_GetLocalityName,
381 CERT_GetStateName, CERT_GetCountryName };
382 std::string* single_values[4] = {
383 &principal->common_name, &principal->locality_name,
384 &principal->state_or_province_name, &principal->country_name };
385 for (size_t i = 0; i < arraysize(get_name_funcs); ++i) {
386 char* value = get_name_funcs[i](name);
387 if (value) {
388 single_values[i]->assign(value);
389 PORT_Free(value);
394 void ParseDate(const SECItem* der_date, base::Time* result) {
395 PRTime prtime;
396 SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
397 DCHECK_EQ(SECSuccess, rv);
398 *result = crypto::PRTimeToBaseTime(prtime);
401 std::string ParseSerialNumber(const CERTCertificate* certificate) {
402 return std::string(reinterpret_cast<char*>(certificate->serialNumber.data),
403 certificate->serialNumber.len);
406 void GetSubjectAltName(CERTCertificate* cert_handle,
407 std::vector<std::string>* dns_names,
408 std::vector<std::string>* ip_addrs) {
409 if (dns_names)
410 dns_names->clear();
411 if (ip_addrs)
412 ip_addrs->clear();
414 SECItem alt_name;
415 SECStatus rv = CERT_FindCertExtension(cert_handle,
416 SEC_OID_X509_SUBJECT_ALT_NAME,
417 &alt_name);
418 if (rv != SECSuccess)
419 return;
421 PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
422 DCHECK(arena != NULL);
424 CERTGeneralName* alt_name_list;
425 alt_name_list = CERT_DecodeAltNameExtension(arena, &alt_name);
426 SECITEM_FreeItem(&alt_name, PR_FALSE);
428 CERTGeneralName* name = alt_name_list;
429 while (name) {
430 // DNSName and IPAddress are encoded as IA5String and OCTET STRINGs
431 // respectively, both of which can be byte copied from
432 // SECItemType::data into the appropriate output vector.
433 if (dns_names && name->type == certDNSName) {
434 dns_names->push_back(std::string(
435 reinterpret_cast<char*>(name->name.other.data),
436 name->name.other.len));
437 } else if (ip_addrs && name->type == certIPAddress) {
438 ip_addrs->push_back(std::string(
439 reinterpret_cast<char*>(name->name.other.data),
440 name->name.other.len));
442 name = CERT_GetNextGeneralName(name);
443 if (name == alt_name_list)
444 break;
446 PORT_FreeArena(arena, PR_FALSE);
449 X509Certificate::OSCertHandles CreateOSCertHandlesFromBytes(
450 const char* data,
451 int length,
452 X509Certificate::Format format) {
453 X509Certificate::OSCertHandles results;
454 if (length < 0)
455 return results;
457 crypto::EnsureNSSInit();
459 if (!NSS_IsInitialized())
460 return results;
462 switch (format) {
463 case X509Certificate::FORMAT_SINGLE_CERTIFICATE: {
464 X509Certificate::OSCertHandle handle =
465 X509Certificate::CreateOSCertHandleFromBytes(data, length);
466 if (handle)
467 results.push_back(handle);
468 break;
470 case X509Certificate::FORMAT_PKCS7: {
471 // Make a copy since CERT_DecodeCertPackage may modify it
472 std::vector<char> data_copy(data, data + length);
474 SECStatus result = CERT_DecodeCertPackage(&data_copy[0],
475 length, CollectCertsCallback, &results);
476 if (result != SECSuccess)
477 results.clear();
478 break;
480 default:
481 NOTREACHED() << "Certificate format " << format << " unimplemented";
482 break;
485 return results;
488 X509Certificate::OSCertHandle ReadOSCertHandleFromPickle(
489 PickleIterator* pickle_iter) {
490 const char* data;
491 int length;
492 if (!pickle_iter->ReadData(&data, &length))
493 return NULL;
495 return X509Certificate::CreateOSCertHandleFromBytes(data, length);
498 void GetPublicKeyInfo(CERTCertificate* handle,
499 size_t* size_bits,
500 X509Certificate::PublicKeyType* type) {
501 // Since we might fail, set the output parameters to default values first.
502 *type = X509Certificate::kPublicKeyTypeUnknown;
503 *size_bits = 0;
505 crypto::ScopedSECKEYPublicKey key(CERT_ExtractPublicKey(handle));
506 if (!key.get())
507 return;
509 *size_bits = SECKEY_PublicKeyStrengthInBits(key.get());
511 switch (key->keyType) {
512 case rsaKey:
513 *type = X509Certificate::kPublicKeyTypeRSA;
514 break;
515 case dsaKey:
516 *type = X509Certificate::kPublicKeyTypeDSA;
517 break;
518 case dhKey:
519 *type = X509Certificate::kPublicKeyTypeDH;
520 break;
521 case ecKey:
522 *type = X509Certificate::kPublicKeyTypeECDSA;
523 break;
524 default:
525 *type = X509Certificate::kPublicKeyTypeUnknown;
526 *size_bits = 0;
527 break;
530 #endif // defined(USE_NSS) || defined(OS_IOS)
532 } // namespace x509_util
534 } // namespace net