3 * Copyright 2012, Google Inc.
4 * Copyright 2012, RTFM, Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
9 * 1. Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
20 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
23 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
25 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
26 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #endif // HAVE_CONFIG_H
39 #include "talk/base/nssidentity.h"
48 #include "talk/base/logging.h"
49 #include "talk/base/helpers.h"
50 #include "talk/base/nssstreamadapter.h"
51 #include "talk/base/safe_conversions.h"
55 // Certificate validity lifetime in seconds.
56 static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
57 // Certificate validity window in seconds.
58 // This is to compensate for slightly incorrect system clocks.
59 static const int CERTIFICATE_WINDOW = -60*60*24;
61 NSSKeyPair::~NSSKeyPair() {
63 SECKEY_DestroyPrivateKey(privkey_);
65 SECKEY_DestroyPublicKey(pubkey_);
68 NSSKeyPair *NSSKeyPair::Generate() {
69 SECKEYPrivateKey *privkey = NULL;
70 SECKEYPublicKey *pubkey = NULL;
71 PK11RSAGenParams rsaparams;
72 rsaparams.keySizeInBits = 1024;
73 rsaparams.pe = 0x010001; // 65537 -- a common RSA public exponent.
75 privkey = PK11_GenerateKeyPair(NSSContext::GetSlot(),
76 CKM_RSA_PKCS_KEY_PAIR_GEN,
77 &rsaparams, &pubkey, PR_FALSE /*permanent*/,
78 PR_FALSE /*sensitive*/, NULL);
80 LOG(LS_ERROR) << "Couldn't generate key pair";
84 return new NSSKeyPair(privkey, pubkey);
88 NSSKeyPair *NSSKeyPair::GetReference() {
89 SECKEYPrivateKey *privkey = SECKEY_CopyPrivateKey(privkey_);
93 SECKEYPublicKey *pubkey = SECKEY_CopyPublicKey(pubkey_);
95 SECKEY_DestroyPrivateKey(privkey);
99 return new NSSKeyPair(privkey, pubkey);
102 NSSCertificate::NSSCertificate(CERTCertificate* cert)
103 : certificate_(CERT_DupCertificate(cert)) {
104 ASSERT(certificate_ != NULL);
107 static void DeleteCert(SSLCertificate* cert) {
111 NSSCertificate::NSSCertificate(CERTCertList* cert_list) {
112 // Copy the first cert into certificate_.
113 CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
114 certificate_ = CERT_DupCertificate(node->cert);
116 // Put any remaining certificates into the chain.
117 node = CERT_LIST_NEXT(node);
118 std::vector<SSLCertificate*> certs;
119 for (; !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) {
120 certs.push_back(new NSSCertificate(node->cert));
124 chain_.reset(new SSLCertChain(certs));
126 // The SSLCertChain constructor copies its input, so now we have to delete
128 std::for_each(certs.begin(), certs.end(), DeleteCert);
131 NSSCertificate::NSSCertificate(CERTCertificate* cert, SSLCertChain* chain)
132 : certificate_(CERT_DupCertificate(cert)) {
133 ASSERT(certificate_ != NULL);
135 chain_.reset(chain->Copy());
139 NSSCertificate *NSSCertificate::FromPEMString(const std::string &pem_string) {
141 if (!SSLIdentity::PemToDer(kPemTypeCertificate, pem_string, &der))
145 der_cert.data = reinterpret_cast<unsigned char *>(const_cast<char *>(
147 der_cert.len = checked_cast<unsigned int>(der.size());
148 CERTCertificate *cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
149 &der_cert, NULL, PR_FALSE, PR_TRUE);
154 NSSCertificate* ret = new NSSCertificate(cert);
155 CERT_DestroyCertificate(cert);
159 NSSCertificate *NSSCertificate::GetReference() const {
160 return new NSSCertificate(certificate_, chain_.get());
163 std::string NSSCertificate::ToPEMString() const {
164 return SSLIdentity::DerToPem(kPemTypeCertificate,
165 certificate_->derCert.data,
166 certificate_->derCert.len);
169 void NSSCertificate::ToDER(Buffer* der_buffer) const {
170 der_buffer->SetData(certificate_->derCert.data, certificate_->derCert.len);
173 static bool Certifies(CERTCertificate* parent, CERTCertificate* child) {
174 // TODO(bemasc): Identify stricter validation checks to use here. In the
175 // context of some future identity standard, it might make sense to check
176 // the certificates' roles, expiration dates, self-signatures (if
177 // self-signed), certificate transparency logging, or many other attributes.
178 // NOTE: Future changes to this validation may reject some previously allowed
179 // certificate chains. Users should be advised not to deploy chained
180 // certificates except in controlled environments until the validity
181 // requirements are finalized.
183 // Check that the parent's name is the same as the child's claimed issuer.
184 SECComparison name_status =
185 CERT_CompareName(&child->issuer, &parent->subject);
186 if (name_status != SECEqual)
189 // Extract the parent's public key, or fail if the key could not be read
190 // (e.g. certificate is corrupted).
191 SECKEYPublicKey* parent_key = CERT_ExtractPublicKey(parent);
195 // Check that the parent's privkey was actually used to generate the child's
197 SECStatus verified = CERT_VerifySignedDataWithPublicKey(
198 &child->signatureWrap, parent_key, NULL);
199 SECKEY_DestroyPublicKey(parent_key);
200 return verified == SECSuccess;
203 bool NSSCertificate::IsValidChain(const CERTCertList* cert_list) {
204 CERTCertListNode* child = CERT_LIST_HEAD(cert_list);
205 for (CERTCertListNode* parent = CERT_LIST_NEXT(child);
206 !CERT_LIST_END(parent, cert_list);
207 child = parent, parent = CERT_LIST_NEXT(parent)) {
208 if (!Certifies(parent->cert, child->cert))
214 bool NSSCertificate::GetDigestLength(const std::string &algorithm,
215 std::size_t *length) {
216 const SECHashObject *ho;
218 if (!GetDigestObject(algorithm, &ho))
221 *length = ho->length;
226 bool NSSCertificate::GetSignatureDigestAlgorithm(std::string* algorithm) const {
227 // The function sec_DecodeSigAlg in NSS provides this mapping functionality.
228 // Unfortunately it is private, so the functionality must be duplicated here.
229 // See https://bugzilla.mozilla.org/show_bug.cgi?id=925165 .
230 SECOidTag sig_alg = SECOID_GetAlgorithmTag(&certificate_->signature);
232 case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION:
233 *algorithm = DIGEST_MD5;
235 case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION:
236 case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE:
237 case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE:
238 case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST:
239 case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST:
240 case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE:
241 case SEC_OID_MISSI_DSS:
242 case SEC_OID_MISSI_KEA_DSS:
243 case SEC_OID_MISSI_KEA_DSS_OLD:
244 case SEC_OID_MISSI_DSS_OLD:
245 *algorithm = DIGEST_SHA_1;
247 case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE:
248 case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION:
249 case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST:
250 *algorithm = DIGEST_SHA_224;
252 case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE:
253 case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION:
254 case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST:
255 *algorithm = DIGEST_SHA_256;
257 case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE:
258 case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION:
259 *algorithm = DIGEST_SHA_384;
261 case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE:
262 case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION:
263 *algorithm = DIGEST_SHA_512;
266 // Unknown algorithm. There are several unhandled options that are less
267 // common and more complex.
274 bool NSSCertificate::ComputeDigest(const std::string &algorithm,
275 unsigned char *digest, std::size_t size,
276 std::size_t *length) const {
277 const SECHashObject *ho;
279 if (!GetDigestObject(algorithm, &ho))
282 if (size < ho->length) // Sanity check for fit
285 SECStatus rv = HASH_HashBuf(ho->type, digest,
286 certificate_->derCert.data,
287 certificate_->derCert.len);
288 if (rv != SECSuccess)
291 *length = ho->length;
296 bool NSSCertificate::GetChain(SSLCertChain** chain) const {
300 *chain = chain_->Copy();
304 bool NSSCertificate::Equals(const NSSCertificate *tocompare) const {
305 if (!certificate_->derCert.len)
307 if (!tocompare->certificate_->derCert.len)
310 if (certificate_->derCert.len != tocompare->certificate_->derCert.len)
313 return memcmp(certificate_->derCert.data,
314 tocompare->certificate_->derCert.data,
315 certificate_->derCert.len) == 0;
319 bool NSSCertificate::GetDigestObject(const std::string &algorithm,
320 const SECHashObject **hop) {
321 const SECHashObject *ho;
322 HASH_HashType hash_type;
324 if (algorithm == DIGEST_SHA_1) {
325 hash_type = HASH_AlgSHA1;
326 // HASH_AlgSHA224 is not supported in the chromium linux build system.
328 } else if (algorithm == DIGEST_SHA_224) {
329 hash_type = HASH_AlgSHA224;
331 } else if (algorithm == DIGEST_SHA_256) {
332 hash_type = HASH_AlgSHA256;
333 } else if (algorithm == DIGEST_SHA_384) {
334 hash_type = HASH_AlgSHA384;
335 } else if (algorithm == DIGEST_SHA_512) {
336 hash_type = HASH_AlgSHA512;
341 ho = HASH_GetHashObject(hash_type);
343 ASSERT(ho->length >= 20); // Can't happen
350 NSSIdentity* NSSIdentity::GenerateInternal(const SSLIdentityParams& params) {
351 std::string subject_name_string = "CN=" + params.common_name;
352 CERTName *subject_name = CERT_AsciiToName(
353 const_cast<char *>(subject_name_string.c_str()));
354 NSSIdentity *identity = NULL;
355 CERTSubjectPublicKeyInfo *spki = NULL;
356 CERTCertificateRequest *certreq = NULL;
357 CERTValidity *validity;
358 CERTCertificate *certificate = NULL;
359 NSSKeyPair *keypair = NSSKeyPair::Generate();
364 PRTime now = PR_Now();
366 now + static_cast<PRTime>(params.not_before) * PR_USEC_PER_SEC;
368 now + static_cast<PRTime>(params.not_after) * PR_USEC_PER_SEC;
371 inner_der.data = NULL;
374 LOG(LS_ERROR) << "Couldn't generate key pair";
379 LOG(LS_ERROR) << "Couldn't convert subject name " << subject_name;
383 spki = SECKEY_CreateSubjectPublicKeyInfo(keypair->pubkey());
385 LOG(LS_ERROR) << "Couldn't create SPKI";
389 certreq = CERT_CreateCertificateRequest(subject_name, spki, NULL);
391 LOG(LS_ERROR) << "Couldn't create certificate signing request";
395 validity = CERT_CreateValidity(not_before, not_after);
397 LOG(LS_ERROR) << "Couldn't create validity";
401 unsigned long serial;
402 // Note: This serial in principle could collide, but it's unlikely
403 rv = PK11_GenerateRandom(reinterpret_cast<unsigned char *>(&serial),
405 if (rv != SECSuccess) {
406 LOG(LS_ERROR) << "Couldn't generate random serial";
410 certificate = CERT_CreateCertificate(serial, subject_name, validity, certreq);
412 LOG(LS_ERROR) << "Couldn't create certificate";
416 arena = certificate->arena;
418 rv = SECOID_SetAlgorithmID(arena, &certificate->signature,
419 SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION, NULL);
420 if (rv != SECSuccess)
423 // Set version to X509v3.
424 *(certificate->version.data) = 2;
425 certificate->version.len = 1;
427 if (!SEC_ASN1EncodeItem(arena, &inner_der, certificate,
428 SEC_ASN1_GET(CERT_CertificateTemplate)))
431 rv = SEC_DerSignData(arena, &signed_cert, inner_der.data, inner_der.len,
433 SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION);
434 if (rv != SECSuccess) {
435 LOG(LS_ERROR) << "Couldn't sign certificate";
438 certificate->derCert = signed_cert;
440 identity = new NSSIdentity(keypair, new NSSCertificate(certificate));
448 if (certificate) CERT_DestroyCertificate(certificate);
449 if (subject_name) CERT_DestroyName(subject_name);
450 if (spki) SECKEY_DestroySubjectPublicKeyInfo(spki);
451 if (certreq) CERT_DestroyCertificateRequest(certreq);
452 if (validity) CERT_DestroyValidity(validity);
456 NSSIdentity* NSSIdentity::Generate(const std::string &common_name) {
457 SSLIdentityParams params;
458 params.common_name = common_name;
459 params.not_before = CERTIFICATE_WINDOW;
460 params.not_after = CERTIFICATE_LIFETIME;
461 return GenerateInternal(params);
464 NSSIdentity* NSSIdentity::GenerateForTest(const SSLIdentityParams& params) {
465 return GenerateInternal(params);
468 SSLIdentity* NSSIdentity::FromPEMStrings(const std::string& private_key,
469 const std::string& certificate) {
470 std::string private_key_der;
471 if (!SSLIdentity::PemToDer(
472 kPemTypeRsaPrivateKey, private_key, &private_key_der))
475 SECItem private_key_item;
476 private_key_item.data = reinterpret_cast<unsigned char *>(
477 const_cast<char *>(private_key_der.c_str()));
478 private_key_item.len = checked_cast<unsigned int>(private_key_der.size());
480 const unsigned int key_usage = KU_KEY_ENCIPHERMENT | KU_DATA_ENCIPHERMENT |
481 KU_DIGITAL_SIGNATURE;
483 SECKEYPrivateKey* privkey = NULL;
485 PK11_ImportDERPrivateKeyInfoAndReturnKey(NSSContext::GetSlot(),
487 NULL, NULL, PR_FALSE, PR_FALSE,
488 key_usage, &privkey, NULL);
489 if (rv != SECSuccess) {
490 LOG(LS_ERROR) << "Couldn't import private key";
494 SECKEYPublicKey *pubkey = SECKEY_ConvertToPublicKey(privkey);
495 if (rv != SECSuccess) {
496 SECKEY_DestroyPrivateKey(privkey);
497 LOG(LS_ERROR) << "Couldn't convert private key to public key";
501 // Assign to a scoped_ptr so we don't leak on error.
502 scoped_ptr<NSSKeyPair> keypair(new NSSKeyPair(privkey, pubkey));
504 scoped_ptr<NSSCertificate> cert(NSSCertificate::FromPEMString(certificate));
506 LOG(LS_ERROR) << "Couldn't parse certificate";
510 // TODO(ekr@rtfm.com): Check the public key against the certificate.
512 return new NSSIdentity(keypair.release(), cert.release());
515 NSSIdentity *NSSIdentity::GetReference() const {
516 NSSKeyPair *keypair = keypair_->GetReference();
520 NSSCertificate *certificate = certificate_->GetReference();
526 return new NSSIdentity(keypair, certificate);
530 NSSCertificate &NSSIdentity::certificate() const {
531 return *certificate_;
535 } // talk_base namespace
537 #endif // HAVE_NSS_SSL_H