network_cert_migrator_unittest.cc revision 116680a4aac90f2aa7413d9095a592090648e557
1// Copyright 2013 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.
4
5#include "chromeos/network/network_cert_migrator.h"
6
7#include <cert.h>
8
9#include "base/file_util.h"
10#include "base/files/file_path.h"
11#include "base/run_loop.h"
12#include "chromeos/cert_loader.h"
13#include "chromeos/dbus/dbus_thread_manager.h"
14#include "chromeos/dbus/shill_service_client.h"
15#include "chromeos/network/network_state_handler.h"
16#include "chromeos/tpm_token_loader.h"
17#include "crypto/nss_util.h"
18#include "crypto/nss_util_internal.h"
19#include "net/base/crypto_module.h"
20#include "net/base/net_errors.h"
21#include "net/base/test_data_directory.h"
22#include "net/cert/nss_cert_database_chromeos.h"
23#include "net/cert/x509_certificate.h"
24#include "net/test/cert_test_util.h"
25#include "testing/gtest/include/gtest/gtest.h"
26#include "third_party/cros_system_api/dbus/service_constants.h"
27
28namespace chromeos {
29
30namespace {
31
32const char* kWifiStub = "wifi_stub";
33const char* kVPNStub = "vpn_stub";
34const char* kNSSNickname = "nss_nickname";
35const char* kFakePEM = "pem";
36
37}  // namespace
38
39class NetworkCertMigratorTest : public testing::Test {
40 public:
41  NetworkCertMigratorTest() : service_test_(NULL),
42                              user_("user_hash") {
43  }
44  virtual ~NetworkCertMigratorTest() {}
45
46  virtual void SetUp() OVERRIDE {
47    // Initialize NSS db for the user.
48    ASSERT_TRUE(user_.constructed_successfully());
49    user_.FinishInit();
50    test_nssdb_.reset(new net::NSSCertDatabaseChromeOS(
51        crypto::GetPublicSlotForChromeOSUser(user_.username_hash()),
52        crypto::GetPrivateSlotForChromeOSUser(
53            user_.username_hash(),
54            base::Callback<void(crypto::ScopedPK11Slot)>())));
55    test_nssdb_->SetSlowTaskRunnerForTest(message_loop_.message_loop_proxy());
56
57    DBusThreadManager::InitializeWithStub();
58    service_test_ =
59        DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface();
60    base::RunLoop().RunUntilIdle();
61    service_test_->ClearServices();
62    base::RunLoop().RunUntilIdle();
63
64    CertLoader::Initialize();
65    CertLoader* cert_loader_ = CertLoader::Get();
66    cert_loader_->StartWithNSSDB(test_nssdb_.get());
67  }
68
69  virtual void TearDown() OVERRIDE {
70    network_cert_migrator_.reset();
71    network_state_handler_.reset();
72    CertLoader::Shutdown();
73    DBusThreadManager::Shutdown();
74    CleanupTestCert();
75  }
76
77 protected:
78  void SetupTestCACert() {
79    scoped_refptr<net::X509Certificate> cert_wo_nickname =
80        net::CreateCertificateListFromFile(net::GetTestCertsDirectory(),
81                                           "eku-test-root.pem",
82                                           net::X509Certificate::FORMAT_AUTO)
83            .back();
84    net::X509Certificate::GetPEMEncoded(cert_wo_nickname->os_cert_handle(),
85                                        &test_ca_cert_pem_);
86    std::string der_encoded;
87    net::X509Certificate::GetDEREncoded(cert_wo_nickname->os_cert_handle(),
88                                        &der_encoded);
89    cert_wo_nickname = NULL;
90
91    test_ca_cert_ = net::X509Certificate::CreateFromBytesWithNickname(
92        der_encoded.data(), der_encoded.size(), kNSSNickname);
93    net::CertificateList cert_list;
94    cert_list.push_back(test_ca_cert_);
95    net::NSSCertDatabase::ImportCertFailureList failures;
96    EXPECT_TRUE(test_nssdb_->ImportCACerts(
97        cert_list, net::NSSCertDatabase::TRUST_DEFAULT, &failures));
98    ASSERT_TRUE(failures.empty()) << net::ErrorToString(failures[0].net_error);
99  }
100
101  void SetupNetworkHandlers() {
102    network_state_handler_.reset(NetworkStateHandler::InitializeForTest());
103    network_cert_migrator_.reset(new NetworkCertMigrator);
104    network_cert_migrator_->Init(network_state_handler_.get());
105  }
106
107  void AddService(const std::string& network_id,
108                  const std::string& type,
109                  const std::string& state) {
110    service_test_->AddService(network_id /* service_path */,
111                              network_id /* guid */,
112                              network_id /* name */,
113                              type,
114                              state,
115                              true /* add_to_visible */);
116  }
117
118  void SetupWifiWithNss() {
119    AddService(kWifiStub, shill::kTypeWifi, shill::kStateOnline);
120    service_test_->SetServiceProperty(kWifiStub,
121                                      shill::kEapCaCertNssProperty,
122                                      base::StringValue(kNSSNickname));
123  }
124
125  void GetEapCACertProperties(std::string* nss_nickname, std::string* ca_pem) {
126    nss_nickname->clear();
127    ca_pem->clear();
128    const base::DictionaryValue* properties =
129        service_test_->GetServiceProperties(kWifiStub);
130    properties->GetStringWithoutPathExpansion(shill::kEapCaCertNssProperty,
131                                              nss_nickname);
132    const base::ListValue* ca_pems = NULL;
133    properties->GetListWithoutPathExpansion(shill::kEapCaCertPemProperty,
134                                            &ca_pems);
135    if (ca_pems && !ca_pems->empty())
136      ca_pems->GetString(0, ca_pem);
137  }
138
139  void SetupVpnWithNss(bool open_vpn) {
140    AddService(kVPNStub, shill::kTypeVPN, shill::kStateIdle);
141    base::DictionaryValue provider;
142    const char* nss_property = open_vpn ? shill::kOpenVPNCaCertNSSProperty
143                                        : shill::kL2tpIpsecCaCertNssProperty;
144    provider.SetStringWithoutPathExpansion(nss_property, kNSSNickname);
145    service_test_->SetServiceProperty(
146        kVPNStub, shill::kProviderProperty, provider);
147  }
148
149  void GetVpnCACertProperties(bool open_vpn,
150                              std::string* nss_nickname,
151                              std::string* ca_pem) {
152    nss_nickname->clear();
153    ca_pem->clear();
154    const base::DictionaryValue* properties =
155        service_test_->GetServiceProperties(kVPNStub);
156    const base::DictionaryValue* provider = NULL;
157    properties->GetDictionaryWithoutPathExpansion(shill::kProviderProperty,
158                                                  &provider);
159    if (!provider)
160      return;
161    const char* nss_property = open_vpn ? shill::kOpenVPNCaCertNSSProperty
162                                        : shill::kL2tpIpsecCaCertNssProperty;
163    provider->GetStringWithoutPathExpansion(nss_property, nss_nickname);
164    const base::ListValue* ca_pems = NULL;
165    const char* pem_property = open_vpn ? shill::kOpenVPNCaCertPemProperty
166                                        : shill::kL2tpIpsecCaCertPemProperty;
167    provider->GetListWithoutPathExpansion(pem_property, &ca_pems);
168    if (ca_pems && !ca_pems->empty())
169      ca_pems->GetString(0, ca_pem);
170  }
171
172  ShillServiceClient::TestInterface* service_test_;
173  scoped_refptr<net::X509Certificate> test_ca_cert_;
174  std::string test_ca_cert_pem_;
175  base::MessageLoop message_loop_;
176
177 private:
178  void CleanupTestCert() {
179    ASSERT_TRUE(test_nssdb_->DeleteCertAndKey(test_ca_cert_.get()));
180  }
181
182  scoped_ptr<NetworkStateHandler> network_state_handler_;
183  scoped_ptr<NetworkCertMigrator> network_cert_migrator_;
184  crypto::ScopedTestNSSChromeOSUser user_;
185  scoped_ptr<net::NSSCertDatabaseChromeOS> test_nssdb_;
186
187  DISALLOW_COPY_AND_ASSIGN(NetworkCertMigratorTest);
188};
189
190TEST_F(NetworkCertMigratorTest, MigrateNssOnInitialization) {
191  // Add a new network for migration before the handlers are initialized.
192  SetupWifiWithNss();
193  SetupTestCACert();
194  SetupNetworkHandlers();
195
196  base::RunLoop().RunUntilIdle();
197  std::string nss_nickname, ca_pem;
198  GetEapCACertProperties(&nss_nickname, &ca_pem);
199  EXPECT_TRUE(nss_nickname.empty());
200  EXPECT_EQ(test_ca_cert_pem_, ca_pem);
201}
202
203TEST_F(NetworkCertMigratorTest, MigrateNssOnNetworkAppearance) {
204  SetupTestCACert();
205  SetupNetworkHandlers();
206  base::RunLoop().RunUntilIdle();
207
208  // Add a new network for migration after the handlers are initialized.
209  SetupWifiWithNss();
210
211  base::RunLoop().RunUntilIdle();
212  std::string nss_nickname, ca_pem;
213  GetEapCACertProperties(&nss_nickname, &ca_pem);
214  EXPECT_TRUE(nss_nickname.empty());
215  EXPECT_EQ(test_ca_cert_pem_, ca_pem);
216}
217
218TEST_F(NetworkCertMigratorTest, DoNotMigrateNssIfPemSet) {
219  // Add a new network with an already set PEM property.
220  SetupWifiWithNss();
221  base::ListValue ca_pems;
222  ca_pems.AppendString(kFakePEM);
223  service_test_->SetServiceProperty(
224      kWifiStub, shill::kEapCaCertPemProperty, ca_pems);
225
226  SetupTestCACert();
227  SetupNetworkHandlers();
228  base::RunLoop().RunUntilIdle();
229
230  std::string nss_nickname, ca_pem;
231  GetEapCACertProperties(&nss_nickname, &ca_pem);
232  EXPECT_TRUE(nss_nickname.empty());
233  EXPECT_EQ(kFakePEM, ca_pem);
234}
235
236TEST_F(NetworkCertMigratorTest, MigrateOpenVpn) {
237  // Add a new network for migration before the handlers are initialized.
238  SetupVpnWithNss(true /* OpenVPN */);
239
240  SetupTestCACert();
241  SetupNetworkHandlers();
242
243  base::RunLoop().RunUntilIdle();
244  std::string nss_nickname, ca_pem;
245  GetVpnCACertProperties(true /* OpenVPN */, &nss_nickname, &ca_pem);
246  EXPECT_TRUE(nss_nickname.empty());
247  EXPECT_EQ(test_ca_cert_pem_, ca_pem);
248}
249
250TEST_F(NetworkCertMigratorTest, MigrateIpsecVpn) {
251  // Add a new network for migration before the handlers are initialized.
252  SetupVpnWithNss(false /* not OpenVPN */);
253
254  SetupTestCACert();
255  SetupNetworkHandlers();
256
257  base::RunLoop().RunUntilIdle();
258  std::string nss_nickname, ca_pem;
259  GetVpnCACertProperties(false /* not OpenVPN */, &nss_nickname, &ca_pem);
260  EXPECT_TRUE(nss_nickname.empty());
261  EXPECT_EQ(test_ca_cert_pem_, ca_pem);
262}
263
264}  // namespace chromeos
265