diff options
-rw-r--r-- | base/nss_util.cc | 4 | ||||
-rw-r--r-- | chrome/browser/gtk/certificate_manager.cc | 32 | ||||
-rw-r--r-- | chrome/third_party/mozilla_security_manager/nsNSSCertHelper.cpp | 16 | ||||
-rw-r--r-- | chrome/third_party/mozilla_security_manager/nsNSSCertHelper.h | 14 | ||||
-rw-r--r-- | net/base/cert_database.cc | 16 | ||||
-rw-r--r-- | net/base/cert_database.h | 57 | ||||
-rw-r--r-- | net/base/cert_database_nss.cc | 67 | ||||
-rw-r--r-- | net/base/cert_database_nss_unittest.cc | 305 | ||||
-rw-r--r-- | net/base/net_error_list.h | 11 | ||||
-rw-r--r-- | net/net.gyp | 5 | ||||
-rw-r--r-- | net/third_party/mozilla_security_manager/nsNSSCertificateDB.cpp | 203 | ||||
-rw-r--r-- | net/third_party/mozilla_security_manager/nsNSSCertificateDB.h | 66 |
12 files changed, 749 insertions, 47 deletions
diff --git a/base/nss_util.cc b/base/nss_util.cc index bf772aa..b144881 100644 --- a/base/nss_util.cc +++ b/base/nss_util.cc @@ -254,7 +254,9 @@ class NSSInitSingleton { void CloseTestNSSDB() { if (test_db_slot_) { - SECMOD_CloseUserDB(test_db_slot_); + SECStatus status = SECMOD_CloseUserDB(test_db_slot_); + if (status != SECSuccess) + LOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError(); PK11_FreeSlot(test_db_slot_); test_db_slot_ = NULL; } diff --git a/chrome/browser/gtk/certificate_manager.cc b/chrome/browser/gtk/certificate_manager.cc index 2898b2b..7a16b8c 100644 --- a/chrome/browser/gtk/certificate_manager.cc +++ b/chrome/browser/gtk/certificate_manager.cc @@ -49,7 +49,7 @@ std::string Stringize(char* nss_text) { class CertificatePage { public: - explicit CertificatePage(psm::CertType type); + explicit CertificatePage(net::CertType type); virtual ~CertificatePage() {} void PopulateTree(CERTCertList* cert_list); @@ -82,7 +82,7 @@ class CertificatePage { GtkTreeSelection*); CHROMEGTK_CALLBACK_0(CertificatePage, void, OnViewClicked); - psm::CertType type_; + net::CertType type_; // The top-level widget of this page. GtkWidget* vbox_; @@ -98,7 +98,7 @@ class CertificatePage { //////////////////////////////////////////////////////////////////////////////// // CertificatePage implementation. -CertificatePage::CertificatePage(psm::CertType type) : type_(type) { +CertificatePage::CertificatePage(net::CertType type) : type_(type) { vbox_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); gtk_container_set_border_width(GTK_CONTAINER(vbox_), gtk_util::kContentAreaBorder); @@ -111,7 +111,7 @@ CertificatePage::CertificatePage(psm::CertType type) : type_(type) { IDS_CERT_MANAGER_UNKNOWN_TREE_DESCRIPTION, }; DCHECK_EQ(arraysize(kDescriptionIds), - static_cast<size_t>(psm::NUM_CERT_TYPES)); + static_cast<size_t>(net::NUM_CERT_TYPES)); GtkWidget* description_label = gtk_label_new(l10n_util::GetStringUTF8( kDescriptionIds[type]).c_str()); gtk_util::LeftAlignMisc(description_label); @@ -140,8 +140,8 @@ CertificatePage::CertificatePage(psm::CertType type) : type_(type) { gtk_tree_view_column_set_sort_column_id(name_col, CERT_NAME); gtk_tree_view_append_column(GTK_TREE_VIEW(tree_), name_col); - if (type == psm::USER_CERT || type == psm::CA_CERT || - type == psm::UNKNOWN_CERT) { + if (type == net::USER_CERT || type == net::CA_CERT || + type == net::UNKNOWN_CERT) { GtkTreeViewColumn* device_col = gtk_tree_view_column_new_with_attributes( l10n_util::GetStringUTF8( IDS_CERT_MANAGER_DEVICE_COLUMN_LABEL).c_str(), @@ -152,7 +152,7 @@ CertificatePage::CertificatePage(psm::CertType type) : type_(type) { gtk_tree_view_append_column(GTK_TREE_VIEW(tree_), device_col); } - if (type == psm::USER_CERT) { + if (type == net::USER_CERT) { GtkTreeViewColumn* serial_col = gtk_tree_view_column_new_with_attributes( l10n_util::GetStringUTF8( IDS_CERT_MANAGER_SERIAL_NUMBER_COLUMN_LABEL).c_str(), @@ -163,8 +163,8 @@ CertificatePage::CertificatePage(psm::CertType type) : type_(type) { gtk_tree_view_append_column(GTK_TREE_VIEW(tree_), serial_col); } - if (type == psm::USER_CERT || type == psm::EMAIL_CERT || - type == psm::SERVER_CERT) { + if (type == net::USER_CERT || type == net::EMAIL_CERT || + type == net::SERVER_CERT) { GtkTreeViewColumn* expires_col = gtk_tree_view_column_new_with_attributes( l10n_util::GetStringUTF8( IDS_CERT_MANAGER_EXPIRES_COLUMN_LABEL).c_str(), @@ -175,7 +175,7 @@ CertificatePage::CertificatePage(psm::CertType type) : type_(type) { gtk_tree_view_append_column(GTK_TREE_VIEW(tree_), expires_col); } - if (type == psm::EMAIL_CERT) { + if (type == net::EMAIL_CERT) { GtkTreeViewColumn* addr_col = gtk_tree_view_column_new_with_attributes( l10n_util::GetStringUTF8( IDS_CERT_MANAGER_EMAIL_ADDRESS_COLUMN_LABEL).c_str(), @@ -240,7 +240,7 @@ void CertificatePage::PopulateTree(CERTCertList* cert_list) { !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) { CERTCertificate* cert = node->cert; - psm::CertType type = psm::GetCertType(cert); + net::CertType type = psm::GetCertType(cert); if (type == type_) { std::string org = Stringize(CERT_GetOrgName(&cert->subject)); if (org.empty()) @@ -387,11 +387,11 @@ void OnDestroy(GtkDialog* dialog, CertificateManager* cert_manager) { CertificateManager::CertificateManager(gfx::NativeWindow parent, Profile* profile) - : user_page_(psm::USER_CERT), - email_page_(psm::EMAIL_CERT), - server_page_(psm::SERVER_CERT), - ca_page_(psm::CA_CERT), - unknown_page_(psm::UNKNOWN_CERT) { + : user_page_(net::USER_CERT), + email_page_(net::EMAIL_CERT), + server_page_(net::SERVER_CERT), + ca_page_(net::CA_CERT), + unknown_page_(net::UNKNOWN_CERT) { // We don't need to observe changes in this value. last_selected_page_.Init(prefs::kCertificateManagerWindowLastTabIndex, profile->GetPrefs(), NULL); diff --git a/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.cpp b/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.cpp index 881abc2..d9e21c9 100644 --- a/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.cpp +++ b/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.cpp @@ -1089,21 +1089,21 @@ std::string ProcessSubjectPublicKeyInfo(CERTSubjectPublicKeyInfo* spki) { return rv; } -CertType GetCertType(CERTCertificate *cert) { +net::CertType GetCertType(CERTCertificate *cert) { nsNSSCertTrust trust(cert->trust); if (cert->nickname && trust.HasAnyUser()) - return USER_CERT; + return net::USER_CERT; if (trust.HasAnyCA()) - return CA_CERT; + return net::CA_CERT; if (trust.HasPeer(PR_TRUE, PR_FALSE, PR_FALSE)) - return SERVER_CERT; + return net::SERVER_CERT; if (trust.HasPeer(PR_FALSE, PR_TRUE, PR_FALSE) && cert->emailAddr) - return EMAIL_CERT; + return net::EMAIL_CERT; if (CERT_IsCACert(cert, NULL)) - return CA_CERT; + return net::CA_CERT; if (cert->emailAddr) - return EMAIL_CERT; - return UNKNOWN_CERT; + return net::EMAIL_CERT; + return net::UNKNOWN_CERT; } } // namespace mozilla_security_manager diff --git a/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.h b/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.h index 271d88e..1dc933f 100644 --- a/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.h +++ b/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.h @@ -46,6 +46,7 @@ #include <string> #include "base/scoped_ptr.h" +#include "net/base/cert_database.h" class FreePRArenaPool { public: @@ -57,17 +58,6 @@ typedef scoped_ptr_malloc<PRArenaPool, FreePRArenaPool> ScopedPRArenaPool; namespace mozilla_security_manager { -// Constants to classify the type of a certificate. (In Mozilla this is actually -// defined in nsIX509Cert.idl) -enum CertType { - UNKNOWN_CERT, - CA_CERT, - USER_CERT, - EMAIL_CERT, - SERVER_CERT, - NUM_CERT_TYPES -}; - extern SECOidTag ms_cert_ext_certtype; extern SECOidTag ms_certsrv_ca_version; extern SECOidTag ms_nt_principal_name; @@ -110,7 +100,7 @@ std::string ProcessExtKeyUsage(SECItem* extension_data); std::string ProcessExtensionData(SECOidTag oid_tag, SECItem* extension_data); std::string ProcessSubjectPublicKeyInfo(CERTSubjectPublicKeyInfo* spki); -CertType GetCertType(CERTCertificate *cert); +net::CertType GetCertType(CERTCertificate *cert); } // namespace mozilla_security_manager diff --git a/net/base/cert_database.cc b/net/base/cert_database.cc new file mode 100644 index 0000000..3f6f9e9 --- /dev/null +++ b/net/base/cert_database.cc @@ -0,0 +1,16 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/base/cert_database.h" + +#include "net/base/x509_certificate.h" + +namespace net { + +CertDatabase::ImportCertResult::ImportCertResult( + X509Certificate* cert, int err) + : certificate(cert), net_error(err) { +} + +} // namespace net diff --git a/net/base/cert_database.h b/net/base/cert_database.h index a264f19..9570d15 100644 --- a/net/base/cert_database.h +++ b/net/base/cert_database.h @@ -18,6 +18,18 @@ namespace net { class X509Certificate; typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; +// Constants to classify the type of a certificate. +// This is only used in the context of CertDatabase, but is defined outside to +// avoid an awkwardly long type name. +enum CertType { + UNKNOWN_CERT, + CA_CERT, + USER_CERT, + EMAIL_CERT, + SERVER_CERT, + NUM_CERT_TYPES +}; + // This class provides functions to manipulate the local // certificate store. @@ -27,6 +39,24 @@ typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; class CertDatabase { public: + // Constants that define which usages a certificate is trusted for. + enum { + UNTRUSTED = 0, + TRUSTED_SSL = 1 << 0, + TRUSTED_EMAIL = 1 << 1, + TRUSTED_OBJ_SIGN = 1 << 2, + }; + + // Stores per-certificate import results. + struct ImportCertResult { + public: + ImportCertResult(X509Certificate* cert, int err); + + scoped_refptr<X509Certificate> certificate; + int net_error; + }; + typedef std::vector<ImportCertResult> ImportCertResultList; + CertDatabase(); // Check whether this is a valid user cert that we have the private key for. @@ -49,6 +79,33 @@ class CertDatabase { // Returns the number of certificates successfully exported. int ExportToPKCS12(const CertificateList& certs, const string16& password, std::string* output); + + // Uses similar logic to nsNSSCertificateDB::handleCACertDownload to find the + // root. Assumes the list is an ordered hierarchy with the root being either + // the first or last element. + // TODO(mattm): improve this to handle any order. + X509Certificate* FindRootInList(const CertificateList& certificates); + + // Import CA certificates. + // Tries to import all the certificates given. The root will be trusted + // according to |trust_bits|. Any certificates that could not be imported + // will be listed in |not_imported|. + // Returns false if there is an internal error, otherwise true is returned and + // |not_imported| should be checked for any certificates that were not + // imported. + bool ImportCACerts(const CertificateList& certificates, + unsigned int trust_bits, + ImportCertResultList* not_imported); + + // Set trust values for certificate. + // Returns true on success or false on failure. + bool SetCertTrust(const X509Certificate* cert, + CertType type, + unsigned int trust_bits); + + // Delete certificate and associated private key (if one exists). + // Returns true on success or false on failure. + bool DeleteCertAndKey(const X509Certificate* cert); #endif private: diff --git a/net/base/cert_database_nss.cc b/net/base/cert_database_nss.cc index e314afa..b8be38c 100644 --- a/net/base/cert_database_nss.cc +++ b/net/base/cert_database_nss.cc @@ -4,19 +4,18 @@ #include "net/base/cert_database.h" +#include <cert.h> +#include <certdb.h> +#include <keyhi.h> #include <pk11pub.h> #include <secmod.h> -#include <ssl.h> -#include <nssb64.h> // NSSBase64_EncodeItem() -#include <secder.h> // DER_Encode() -#include <cryptohi.h> // SEC_DerSignData() -#include <keyhi.h> // SECKEY_CreateSubjectPublicKeyInfo() #include "base/logging.h" #include "base/nss_util.h" #include "base/scoped_ptr.h" #include "net/base/net_errors.h" #include "net/base/x509_certificate.h" +#include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h" #include "net/third_party/mozilla_security_manager/nsPKCS12Blob.h" // PSM = Mozilla's Personal Security Manager. @@ -102,4 +101,62 @@ int CertDatabase::ExportToPKCS12( return psm::nsPKCS12Blob_Export(output, certs, password); } +X509Certificate* CertDatabase::FindRootInList( + const CertificateList& certificates) { + DCHECK_GT(certificates.size(), 0U); + + if (certificates.size() == 1) + return certificates[0].get(); + + X509Certificate* cert0 = certificates[0]; + X509Certificate* cert1 = certificates[1]; + X509Certificate* certn_2 = certificates[certificates.size() - 2]; + X509Certificate* certn_1 = certificates[certificates.size() - 1]; + + if (CERT_CompareName(&cert1->os_cert_handle()->issuer, + &cert0->os_cert_handle()->subject) == SECEqual) + return cert0; + if (CERT_CompareName(&certn_2->os_cert_handle()->issuer, + &certn_1->os_cert_handle()->subject) == SECEqual) + return certn_1; + + LOG(INFO) << "certificate list is not a hierarchy"; + return cert0; +} + +bool CertDatabase::ImportCACerts(const CertificateList& certificates, + unsigned int trust_bits, + ImportCertResultList* not_imported) { + X509Certificate* root = FindRootInList(certificates); + return psm::ImportCACerts(certificates, root, trust_bits, not_imported); +} + +bool CertDatabase::SetCertTrust(const X509Certificate* cert, + CertType type, + unsigned int trusted) { + return psm::SetCertTrust(cert, type, trusted); +} + +bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) { + // For some reason, PK11_DeleteTokenCertAndKey only calls + // SEC_DeletePermCertificate if the private key is found. So, we check + // whether a private key exists before deciding which function to call to + // delete the cert. + SECKEYPrivateKey *privKey = PK11_FindKeyByAnyCert(cert->os_cert_handle(), + NULL); + if (privKey) { + SECKEY_DestroyPrivateKey(privKey); + if (PK11_DeleteTokenCertAndKey(cert->os_cert_handle(), NULL)) { + LOG(ERROR) << "PK11_DeleteTokenCertAndKey failed: " << PORT_GetError(); + return false; + } + } else { + if (SEC_DeletePermCertificate(cert->os_cert_handle())) { + LOG(ERROR) << "SEC_DeletePermCertificate failed: " << PORT_GetError(); + return false; + } + } + return true; +} + } // namespace net diff --git a/net/base/cert_database_nss_unittest.cc b/net/base/cert_database_nss_unittest.cc index 7ff4346..45ac72c0 100644 --- a/net/base/cert_database_nss_unittest.cc +++ b/net/base/cert_database_nss_unittest.cc @@ -5,6 +5,8 @@ #include <cert.h> #include <pk11pub.h> +#include <algorithm> + #include "base/crypto/scoped_nss_types.h" #include "base/file_path.h" #include "base/file_util.h" @@ -17,8 +19,12 @@ #include "net/base/cert_database.h" #include "net/base/net_errors.h" #include "net/base/x509_certificate.h" +#include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h" +#include "net/third_party/mozilla_security_manager/nsNSSCertTrust.h" #include "testing/gtest/include/gtest/gtest.h" +namespace psm = mozilla_security_manager; + namespace net { namespace { @@ -48,9 +54,23 @@ CertificateList ListCertsInSlot(PK11SlotInfo* slot) { X509Certificate::OSCertHandles())); } CERT_DestroyCertList(cert_list); + + // Sort the result so that test comparisons can be deterministic. + std::sort(result.begin(), result.end(), X509Certificate::LessThan()); return result; } +bool CleanupSlotContents(PK11SlotInfo* slot) { + CertDatabase cert_db; + bool ok = true; + CertificateList certs = ListCertsInSlot(slot); + for (size_t i = 0; i < certs.size(); ++i) { + if (!cert_db.DeleteCertAndKey(certs[i])) + ok = false; + } + return ok; +} + std::string ReadTestFile(const std::string& name) { std::string result; FilePath cert_path = GetTestCertsDirectory().AppendASCII(name); @@ -58,21 +78,51 @@ std::string ReadTestFile(const std::string& name) { return result; } +bool ReadCertIntoList(const std::string& name, CertificateList* certs) { + std::string cert_data = ReadTestFile(name); + if (cert_data.empty()) + return false; + + X509Certificate* cert = X509Certificate::CreateFromBytes( + cert_data.data(), cert_data.size()); + if (!cert) + return false; + + certs->push_back(cert); + return true; +} + } // namespace +// TODO(mattm): when https://bugzilla.mozilla.org/show_bug.cgi?id=588269 is +// fixed, switch back to using a separate userdb for each test. +// (When doing so, remember to add some standalone tests of DeleteCert since it +// won't be tested by TearDown anymore.) class CertDatabaseNSSTest : public testing::Test { public: virtual void SetUp() { - ASSERT_TRUE(temp_db_dir_.CreateUniqueTempDir()); - ASSERT_TRUE( - base::OpenTestNSSDB(temp_db_dir_.path(), "CertDatabaseNSSTest db")); + if (!temp_db_initialized_) { + ScopedTempDir* temp_db_dir = Singleton< + ScopedTempDir, + DefaultSingletonTraits<ScopedTempDir>, + CertDatabaseNSSTest>::get(); + ASSERT_TRUE(temp_db_dir->CreateUniqueTempDir()); + ASSERT_TRUE( + base::OpenTestNSSDB(temp_db_dir->path(), "CertDatabaseNSSTest db")); + temp_db_initialized_ = true; + } slot_.reset(base::GetDefaultNSSKeySlot()); // Test db should be empty at start of test. EXPECT_EQ(0U, ListCertsInSlot(slot_.get()).size()); } virtual void TearDown() { - base::CloseTestNSSDB(); + // Don't try to cleanup if the setup failed. + ASSERT_TRUE(temp_db_initialized_); + ASSERT_TRUE(slot_.get()); + + EXPECT_TRUE(CleanupSlotContents(slot_.get())); + EXPECT_EQ(0U, ListCertsInSlot(slot_.get()).size()); } protected: @@ -80,9 +130,12 @@ class CertDatabaseNSSTest : public testing::Test { CertDatabase cert_db_; private: - ScopedTempDir temp_db_dir_; + static bool temp_db_initialized_; }; +// static +bool CertDatabaseNSSTest::temp_db_initialized_ = false; + TEST_F(CertDatabaseNSSTest, ImportFromPKCS12WrongPassword) { std::string pkcs12_data = ReadTestFile("client.p12"); @@ -113,4 +166,246 @@ TEST_F(CertDatabaseNSSTest, ImportFromPKCS12AndExportAgain) { // TODO(mattm): further verification of exported data? } +TEST_F(CertDatabaseNSSTest, ImportCACert_SSLTrust) { + std::string cert_data = ReadTestFile("root_ca_cert.crt"); + + CertificateList certs = + X509Certificate::CreateCertificateListFromBytes( + cert_data.data(), cert_data.size(), X509Certificate::FORMAT_AUTO); + ASSERT_EQ(1U, certs.size()); + EXPECT_FALSE(certs[0]->os_cert_handle()->isperm); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts(certs, CertDatabase::TRUSTED_SSL, + &failed)); + + EXPECT_EQ(0U, failed.size()); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(1U, cert_list.size()); + scoped_refptr<X509Certificate> cert(cert_list[0]); + EXPECT_EQ("Test CA", cert->subject().common_name); + + psm::nsNSSCertTrust trust(cert->os_cert_handle()->trust); + EXPECT_TRUE(trust.HasTrustedCA(PR_TRUE, PR_FALSE, PR_FALSE)); + EXPECT_FALSE(trust.HasTrustedCA(PR_FALSE, PR_TRUE, PR_FALSE)); + EXPECT_FALSE(trust.HasTrustedCA(PR_FALSE, PR_FALSE, PR_TRUE)); + EXPECT_FALSE(trust.HasTrustedCA(PR_TRUE, PR_TRUE, PR_TRUE)); + EXPECT_TRUE(trust.HasCA(PR_TRUE, PR_TRUE, PR_TRUE)); +} + +TEST_F(CertDatabaseNSSTest, ImportCACert_EmailTrust) { + std::string cert_data = ReadTestFile("root_ca_cert.crt"); + + CertificateList certs = + X509Certificate::CreateCertificateListFromBytes( + cert_data.data(), cert_data.size(), X509Certificate::FORMAT_AUTO); + ASSERT_EQ(1U, certs.size()); + EXPECT_FALSE(certs[0]->os_cert_handle()->isperm); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts(certs, CertDatabase::TRUSTED_EMAIL, + &failed)); + + EXPECT_EQ(0U, failed.size()); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(1U, cert_list.size()); + scoped_refptr<X509Certificate> cert(cert_list[0]); + EXPECT_EQ("Test CA", cert->subject().common_name); + + psm::nsNSSCertTrust trust(cert->os_cert_handle()->trust); + EXPECT_FALSE(trust.HasTrustedCA(PR_TRUE, PR_FALSE, PR_FALSE)); + EXPECT_TRUE(trust.HasTrustedCA(PR_FALSE, PR_TRUE, PR_FALSE)); + EXPECT_FALSE(trust.HasTrustedCA(PR_FALSE, PR_FALSE, PR_TRUE)); + EXPECT_TRUE(trust.HasCA(PR_TRUE, PR_TRUE, PR_TRUE)); +} + +TEST_F(CertDatabaseNSSTest, ImportCACert_ObjSignTrust) { + std::string cert_data = ReadTestFile("root_ca_cert.crt"); + + CertificateList certs = + X509Certificate::CreateCertificateListFromBytes( + cert_data.data(), cert_data.size(), X509Certificate::FORMAT_AUTO); + ASSERT_EQ(1U, certs.size()); + EXPECT_FALSE(certs[0]->os_cert_handle()->isperm); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts(certs, CertDatabase::TRUSTED_OBJ_SIGN, + &failed)); + + EXPECT_EQ(0U, failed.size()); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(1U, cert_list.size()); + scoped_refptr<X509Certificate> cert(cert_list[0]); + EXPECT_EQ("Test CA", cert->subject().common_name); + + psm::nsNSSCertTrust trust(cert->os_cert_handle()->trust); + EXPECT_FALSE(trust.HasTrustedCA(PR_TRUE, PR_FALSE, PR_FALSE)); + EXPECT_FALSE(trust.HasTrustedCA(PR_FALSE, PR_TRUE, PR_FALSE)); + EXPECT_TRUE(trust.HasTrustedCA(PR_FALSE, PR_FALSE, PR_TRUE)); + EXPECT_TRUE(trust.HasCA(PR_TRUE, PR_TRUE, PR_TRUE)); +} + +TEST_F(CertDatabaseNSSTest, ImportCA_NotCACert) { + std::string cert_data = ReadTestFile("google.single.pem"); + + CertificateList certs = + X509Certificate::CreateCertificateListFromBytes( + cert_data.data(), cert_data.size(), X509Certificate::FORMAT_AUTO); + ASSERT_EQ(1U, certs.size()); + EXPECT_FALSE(certs[0]->os_cert_handle()->isperm); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, + cert_db_.ImportCACerts(certs, CertDatabase::TRUSTED_SSL, &failed)); + ASSERT_EQ(1U, failed.size()); + // Note: this compares pointers directly. It's okay in this case because + // ImportCACerts returns the same pointers that were passed in. In the + // general case IsSameOSCert should be used. + EXPECT_EQ(certs[0], failed[0].certificate); + EXPECT_EQ(ERR_IMPORT_CA_CERT_NOT_CA, failed[0].net_error); + + EXPECT_EQ(0U, ListCertsInSlot(slot_.get()).size()); +} + +TEST_F(CertDatabaseNSSTest, ImportCACertHierarchy) { + CertificateList certs; + ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("www_us_army_mil_cert.der", &certs)); + + // Import it. + CertDatabase::ImportCertResultList failed; + // Have to specify email trust for the cert verification of the child cert to + // work (see + // http://mxr.mozilla.org/mozilla/source/security/nss/lib/certhigh/certvfy.c#752 + // "XXX This choice of trustType seems arbitrary.") + EXPECT_EQ(true, cert_db_.ImportCACerts( + certs, CertDatabase::TRUSTED_SSL | CertDatabase::TRUSTED_EMAIL, + &failed)); + + ASSERT_EQ(1U, failed.size()); + EXPECT_EQ("www.us.army.mil", failed[0].certificate->subject().common_name); + EXPECT_EQ(ERR_IMPORT_CA_CERT_NOT_CA, failed[0].net_error); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(2U, cert_list.size()); + EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name); + EXPECT_EQ("DOD CA-17", cert_list[1]->subject().common_name); +} + +TEST_F(CertDatabaseNSSTest, ImportCACertHierarchyDupeRoot) { + CertificateList certs; + ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs)); + + // First import just the root. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts( + certs, CertDatabase::TRUSTED_SSL | CertDatabase::TRUSTED_EMAIL, + &failed)); + + EXPECT_EQ(0U, failed.size()); + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(1U, cert_list.size()); + EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name); + + ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("www_us_army_mil_cert.der", &certs)); + + // Now import with the other certs in the list too. Even though the root is + // already present, we should still import the rest. + failed.clear(); + EXPECT_EQ(true, cert_db_.ImportCACerts( + certs, CertDatabase::TRUSTED_SSL | CertDatabase::TRUSTED_EMAIL, + &failed)); + + ASSERT_EQ(2U, failed.size()); + EXPECT_EQ("DoD Root CA 2", failed[0].certificate->subject().common_name); + EXPECT_EQ(ERR_IMPORT_CERT_ALREADY_EXISTS, failed[0].net_error); + EXPECT_EQ("www.us.army.mil", failed[1].certificate->subject().common_name); + EXPECT_EQ(ERR_IMPORT_CA_CERT_NOT_CA, failed[1].net_error); + + cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(2U, cert_list.size()); + EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name); + EXPECT_EQ("DOD CA-17", cert_list[1]->subject().common_name); +} + +TEST_F(CertDatabaseNSSTest, ImportCACertHierarchyUntrusted) { + CertificateList certs; + ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs)); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts(certs, CertDatabase::UNTRUSTED, + &failed)); + + ASSERT_EQ(1U, failed.size()); + EXPECT_EQ("DOD CA-17", failed[0].certificate->subject().common_name); + // TODO(mattm): should check for net error equivalent of + // SEC_ERROR_UNTRUSTED_ISSUER + EXPECT_EQ(ERR_FAILED, failed[0].net_error); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(1U, cert_list.size()); + EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name); +} + +TEST_F(CertDatabaseNSSTest, ImportCACertHierarchyTree) { + CertificateList certs; + ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("dod_ca_13_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs)); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts( + certs, CertDatabase::TRUSTED_SSL | CertDatabase::TRUSTED_EMAIL, + &failed)); + + EXPECT_EQ(0U, failed.size()); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(3U, cert_list.size()); + EXPECT_EQ("DOD CA-13", cert_list[0]->subject().common_name); + EXPECT_EQ("DoD Root CA 2", cert_list[1]->subject().common_name); + EXPECT_EQ("DOD CA-17", cert_list[2]->subject().common_name); +} + +TEST_F(CertDatabaseNSSTest, ImportCACertNotHierarchy) { + std::string cert_data = ReadTestFile("root_ca_cert.crt"); + CertificateList certs = + X509Certificate::CreateCertificateListFromBytes( + cert_data.data(), cert_data.size(), X509Certificate::FORMAT_AUTO); + ASSERT_EQ(1U, certs.size()); + ASSERT_TRUE(ReadCertIntoList("dod_ca_13_cert.der", &certs)); + ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs)); + + // Import it. + CertDatabase::ImportCertResultList failed; + EXPECT_EQ(true, cert_db_.ImportCACerts( + certs, CertDatabase::TRUSTED_SSL | CertDatabase::TRUSTED_EMAIL | + CertDatabase::TRUSTED_OBJ_SIGN, &failed)); + + ASSERT_EQ(2U, failed.size()); + // TODO(mattm): should check for net error equivalent of + // SEC_ERROR_UNKNOWN_ISSUER + EXPECT_EQ("DOD CA-13", failed[0].certificate->subject().common_name); + EXPECT_EQ(ERR_FAILED, failed[0].net_error); + EXPECT_EQ("DOD CA-17", failed[1].certificate->subject().common_name); + EXPECT_EQ(ERR_FAILED, failed[1].net_error); + + CertificateList cert_list = ListCertsInSlot(slot_.get()); + ASSERT_EQ(1U, cert_list.size()); + EXPECT_EQ("Test CA", cert_list[0]->subject().common_name); +} + + } // namespace net diff --git a/net/base/net_error_list.h b/net/base/net_error_list.h index 785cbed..979bdea 100644 --- a/net/base/net_error_list.h +++ b/net/base/net_error_list.h @@ -442,3 +442,14 @@ NET_ERROR(PKCS12_IMPORT_BAD_PASSWORD, -701) // PKCS #12 import failed due to other error. NET_ERROR(PKCS12_IMPORT_FAILED, -702) + +// CA import failed - not a CA cert. +NET_ERROR(IMPORT_CA_CERT_NOT_CA, -703) + +// Import failed - certificate already exists in database. +// Note it's a little weird this is an error but reimporting a PKCS12 is ok +// (no-op). That's how mozilla does it, though. +NET_ERROR(IMPORT_CERT_ALREADY_EXISTS, -704) + +// CA import failed due to some other error. +NET_ERROR(IMPORT_CA_CERT_FAILED, -705) diff --git a/net/net.gyp b/net/net.gyp index 74a8638..4c5f0aa 100644 --- a/net/net.gyp +++ b/net/net.gyp @@ -31,6 +31,7 @@ 'base/cache_type.h', 'base/capturing_net_log.cc', 'base/capturing_net_log.h', + 'base/cert_database.cc', 'base/cert_database.h', 'base/cert_database_mac.cc', 'base/cert_database_nss.cc', @@ -188,6 +189,8 @@ 'base/x509_cert_types_mac.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', + 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', + 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsNSSCertTrust.cpp', 'third_party/mozilla_security_manager/nsNSSCertTrust.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', @@ -212,6 +215,8 @@ 'base/x509_certificate_nss.cc', 'third_party/mozilla_security_manager/nsKeygenHandler.cpp', 'third_party/mozilla_security_manager/nsKeygenHandler.h', + 'third_party/mozilla_security_manager/nsNSSCertificateDB.cpp', + 'third_party/mozilla_security_manager/nsNSSCertificateDB.h', 'third_party/mozilla_security_manager/nsNSSCertTrust.cpp', 'third_party/mozilla_security_manager/nsNSSCertTrust.h', 'third_party/mozilla_security_manager/nsPKCS12Blob.cpp', diff --git a/net/third_party/mozilla_security_manager/nsNSSCertificateDB.cpp b/net/third_party/mozilla_security_manager/nsNSSCertificateDB.cpp new file mode 100644 index 0000000..798b140 --- /dev/null +++ b/net/third_party/mozilla_security_manager/nsNSSCertificateDB.cpp @@ -0,0 +1,203 @@ + /* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Ian McGreer <mcgreer@netscape.com> + * Javier Delgadillo <javi@netscape.com> + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h" + +#include <cert.h> +#include <pk11pub.h> +#include <secerr.h> + +#include "base/crypto/scoped_nss_types.h" +#include "base/logging.h" +#include "base/nss_util_internal.h" +#include "net/base/net_errors.h" +#include "net/base/x509_certificate.h" +#include "net/third_party/mozilla_security_manager/nsNSSCertTrust.h" + +namespace mozilla_security_manager { + +// Based on nsNSSCertificateDB::handleCACertDownload, minus the UI bits. +bool ImportCACerts(const net::CertificateList& certificates, + net::X509Certificate* root, + unsigned int trustBits, + net::CertDatabase::ImportCertResultList* failed) { + base::ScopedPK11Slot slot(base::GetDefaultNSSKeySlot()); + if (!slot.get()) { + LOG(ERROR) << "Couldn't get internal key slot!"; + return false; + } + + // Mozilla had some code here to check if a perm version of the cert exists + // already and use that, but CERT_NewTempCertificate actually does that + // itself, so we skip it here. + + if (!CERT_IsCACert(root->os_cert_handle(), NULL)) { + failed->push_back(net::CertDatabase::ImportCertResult( + root, net::ERR_IMPORT_CA_CERT_NOT_CA)); + } else if (root->os_cert_handle()->isperm) { + // Mozilla just returns here, but we continue in case there are other certs + // in the list which aren't already imported. + // TODO(mattm): should we set/add trust if it differs from the present + // settings? + failed->push_back(net::CertDatabase::ImportCertResult( + root, net::ERR_IMPORT_CERT_ALREADY_EXISTS)); + } else { + // Mozilla uses CERT_AddTempCertToPerm, however it is privately exported, + // and it doesn't take the slot as an argument either. Instead, we use + // PK11_ImportCert and CERT_ChangeCertTrust. + char* nickname = CERT_MakeCANickname(root->os_cert_handle()); + if (!nickname) + return false; + SECStatus srv = PK11_ImportCert(slot.get(), root->os_cert_handle(), + CK_INVALID_HANDLE, + nickname, + PR_FALSE /* includeTrust (unused) */); + PORT_Free(nickname); + if (srv != SECSuccess) { + LOG(ERROR) << "PK11_ImportCert failed with error " << PORT_GetError(); + return false; + } + if (!SetCertTrust(root, net::CA_CERT, trustBits)) + return false; + } + + PRTime now = PR_Now(); + // Import additional delivered certificates that can be verified. + // This is sort of merged in from Mozilla's ImportValidCACertsInList. Mozilla + // uses CERT_FilterCertListByUsage to filter out non-ca certs, but we want to + // keep using X509Certificates, so that we can use them to build the |failed| + // result. So, we keep using our net::CertificateList and filter it ourself. + for (size_t i = 0; i < certificates.size(); i++) { + const scoped_refptr<net::X509Certificate>& cert = certificates[i]; + if (cert == root) { + // we already processed that one + continue; + } + + // Mozilla uses CERT_FilterCertListByUsage(certList, certUsageAnyCA, + // PR_TRUE). Afaict, checking !CERT_IsCACert on each cert is equivalent. + if (!CERT_IsCACert(cert->os_cert_handle(), NULL)) { + failed->push_back(net::CertDatabase::ImportCertResult( + cert, net::ERR_IMPORT_CA_CERT_NOT_CA)); + LOG(INFO) << "skipping cert (non-ca)"; + continue; + } + + if (cert->os_cert_handle()->isperm) { + failed->push_back(net::CertDatabase::ImportCertResult( + cert, net::ERR_IMPORT_CERT_ALREADY_EXISTS)); + LOG(INFO) << "skipping cert (perm)"; + continue; + } + + if (CERT_VerifyCert(CERT_GetDefaultCertDB(), cert->os_cert_handle(), + PR_TRUE, certUsageVerifyCA, now, NULL, NULL) != SECSuccess) { + // TODO(mattm): use better error code (map PORT_GetError to an appropriate + // error value). (maybe make MapSecurityError or MapCertErrorToCertStatus + // public.) + failed->push_back(net::CertDatabase::ImportCertResult( + cert, net::ERR_FAILED)); + LOG(INFO) << "skipping cert (verify) " << PORT_GetError(); + continue; + } + + // Mozilla uses CERT_ImportCerts, which doesn't take a slot arg. We use + // PK11_ImportCert instead. + char* nickname = CERT_MakeCANickname(cert->os_cert_handle()); + if (!nickname) + return false; + SECStatus srv = PK11_ImportCert(slot.get(), cert->os_cert_handle(), + CK_INVALID_HANDLE, + nickname, + PR_FALSE /* includeTrust (unused) */); + PORT_Free(nickname); + if (srv != SECSuccess) { + LOG(ERROR) << "PK11_ImportCert failed with error " << PORT_GetError(); + // TODO(mattm): Should we bail or continue on error here? Mozilla doesn't + // check error code at all. + failed->push_back(net::CertDatabase::ImportCertResult( + cert, net::ERR_IMPORT_CA_CERT_FAILED)); + } + } + + // Any errors importing individual certs will be in listed in |failed|. + return true; +} + +// Based on nsNSSCertificateDB::SetCertTrust. +bool +SetCertTrust(const net::X509Certificate* cert, + net::CertType type, + unsigned int trusted) +{ + SECStatus srv; + nsNSSCertTrust trust; + CERTCertificate *nsscert = cert->os_cert_handle(); + if (type == net::CA_CERT) { + // always start with untrusted and move up + trust.SetValidCA(); + trust.AddCATrust(trusted & net::CertDatabase::TRUSTED_SSL, + trusted & net::CertDatabase::TRUSTED_EMAIL, + trusted & net::CertDatabase::TRUSTED_OBJ_SIGN); + srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), + nsscert, + trust.GetTrust()); + } else if (type == net::SERVER_CERT) { + // always start with untrusted and move up + trust.SetValidPeer(); + trust.AddPeerTrust(trusted & net::CertDatabase::TRUSTED_SSL, 0, 0); + srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), + nsscert, + trust.GetTrust()); + } else if (type == net::EMAIL_CERT) { + // always start with untrusted and move up + trust.SetValidPeer(); + trust.AddPeerTrust(0, trusted & net::CertDatabase::TRUSTED_EMAIL, 0); + srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), + nsscert, + trust.GetTrust()); + } else { + // ignore user certs + return true; + } + if (srv != SECSuccess) + LOG(ERROR) << "SetCertTrust failed with error " << PORT_GetError(); + return srv == SECSuccess; +} + +} // namespace mozilla_security_manager diff --git a/net/third_party/mozilla_security_manager/nsNSSCertificateDB.h b/net/third_party/mozilla_security_manager/nsNSSCertificateDB.h new file mode 100644 index 0000000..199491f --- /dev/null +++ b/net/third_party/mozilla_security_manager/nsNSSCertificateDB.h @@ -0,0 +1,66 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Ian McGreer <mcgreer@netscape.com> + * Javier Delgadillo <javi@netscape.com> + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef NET_THIRD_PARTY_MOZILLA_SECURITY_MANAGER_NSNSSCERTIFICATEDB_H_ +#define NET_THIRD_PARTY_MOZILLA_SECURITY_MANAGER_NSNSSCERTIFICATEDB_H_ + +#include <vector> + +#include "base/ref_counted.h" +#include "net/base/cert_database.h" + +typedef struct CERTCertificateStr CERTCertificate; +namespace net { +class X509Certificate; +typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; +} // namespace net + +namespace mozilla_security_manager { + +bool ImportCACerts(const net::CertificateList& certificates, + net::X509Certificate* root, + unsigned int trustBits, + net::CertDatabase::ImportCertResultList* failed); + +bool SetCertTrust(const net::X509Certificate* cert, + net::CertType type, + unsigned int trusted); + +} // namespace mozilla_security_manager + +#endif // NET_THIRD_PARTY_MOZILLA_SECURITY_MANAGER_NSNSSCERTIFICATEDB_H_ |