blob: ff57d36c1c2ec8a0a4e161d39bbbba38afd69091 [file] [log] [blame]
[email protected]75d93a82013-05-06 19:51:561// Copyright (c) 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
[email protected]60833392013-07-26 17:48:495#include "chromeos/cert_loader.h"
[email protected]75d93a82013-05-06 19:51:566
7#include <algorithm>
8
9#include "base/chromeos/chromeos_version.h"
[email protected]60833392013-07-26 17:48:4910#include "base/message_loop/message_loop_proxy.h"
[email protected]75d93a82013-05-06 19:51:5611#include "base/observer_list.h"
[email protected]60833392013-07-26 17:48:4912#include "base/sequenced_task_runner.h"
[email protected]53419052013-05-14 04:37:5613#include "base/strings/string_number_conversions.h"
[email protected]75d93a82013-05-06 19:51:5614#include "base/task_runner_util.h"
15#include "base/threading/worker_pool.h"
16#include "chromeos/dbus/cryptohome_client.h"
17#include "chromeos/dbus/dbus_thread_manager.h"
18#include "crypto/encryptor.h"
19#include "crypto/nss_util.h"
20#include "crypto/sha2.h"
21#include "crypto/symmetric_key.h"
22#include "net/cert/nss_cert_database.h"
23
24namespace chromeos {
25
26namespace {
27
[email protected]7d3d0c02013-05-22 12:32:1328const int64 kInitialRequestDelayMs = 100;
29const int64 kMaxRequestDelayMs = 300000; // 5 minutes
[email protected]75d93a82013-05-06 19:51:5630
[email protected]7d3d0c02013-05-22 12:32:1331// Calculates the delay before running next attempt to initiatialize the TPM
32// token, if |last_delay| was the last or initial delay.
33base::TimeDelta GetNextRequestDelayMs(base::TimeDelta last_delay) {
34 // This implements an exponential backoff, as we don't know in which order of
35 // magnitude the TPM token changes it's state.
36 base::TimeDelta next_delay = last_delay * 2;
37
38 // Cap the delay to prevent an overflow. This threshold is arbitrarily chosen.
39 const base::TimeDelta max_delay =
40 base::TimeDelta::FromMilliseconds(kMaxRequestDelayMs);
41 if (next_delay > max_delay)
42 next_delay = max_delay;
43 return next_delay;
44}
45
46void LoadNSSCertificates(net::CertificateList* cert_list) {
[email protected]53419052013-05-14 04:37:5647 if (base::chromeos::IsRunningOnChromeOS())
48 net::NSSCertDatabase::GetInstance()->ListCerts(cert_list);
[email protected]75d93a82013-05-06 19:51:5649}
50
[email protected]60833392013-07-26 17:48:4951void CallOpenPersistentNSSDB() {
52 // Called from crypto_task_runner_.
53 VLOG(1) << "CallOpenPersistentNSSDB";
54
55 // Ensure we've opened the user's key/certificate database.
56 crypto::OpenPersistentNSSDB();
57 if (base::chromeos::IsRunningOnChromeOS())
58 crypto::EnableTPMTokenForNSS();
59}
60
[email protected]75d93a82013-05-06 19:51:5661} // namespace
62
[email protected]60833392013-07-26 17:48:4963static CertLoader* g_cert_loader = NULL;
64// static
65void CertLoader::Initialize() {
66 CHECK(!g_cert_loader);
67 g_cert_loader = new CertLoader();
68 g_cert_loader->Init();
69}
70
71// static
72void CertLoader::Shutdown() {
73 CHECK(g_cert_loader);
74 delete g_cert_loader;
75 g_cert_loader = NULL;
76}
77
78// static
79CertLoader* CertLoader::Get() {
80 CHECK(g_cert_loader)
81 << "CertLoader::Get() called before Initialize()";
82 return g_cert_loader;
83}
84
85// static
86bool CertLoader::IsInitialized() {
87 return g_cert_loader;
88}
89
[email protected]75d93a82013-05-06 19:51:5690CertLoader::CertLoader()
[email protected]7d3d0c02013-05-22 12:32:1391 : certificates_requested_(false),
[email protected]75d93a82013-05-06 19:51:5692 certificates_loaded_(false),
[email protected]7d3d0c02013-05-22 12:32:1393 certificates_update_required_(false),
94 certificates_update_running_(false),
95 tpm_token_state_(TPM_STATE_UNKNOWN),
96 tpm_request_delay_(
97 base::TimeDelta::FromMilliseconds(kInitialRequestDelayMs)),
98 initialize_token_factory_(this),
99 update_certificates_factory_(this) {
[email protected]60833392013-07-26 17:48:49100}
101
102void CertLoader::Init() {
[email protected]75d93a82013-05-06 19:51:56103 net::CertDatabase::GetInstance()->AddObserver(this);
[email protected]437a9f8f2013-05-28 18:33:30104 if (LoginState::IsInitialized())
105 LoginState::Get()->AddObserver(this);
[email protected]60833392013-07-26 17:48:49106}
107
108void CertLoader::SetCryptoTaskRunner(
109 const scoped_refptr<base::SequencedTaskRunner>& crypto_task_runner) {
110 crypto_task_runner_ = crypto_task_runner;
111 MaybeRequestCertificates();
[email protected]75d93a82013-05-06 19:51:56112}
113
114CertLoader::~CertLoader() {
[email protected]75d93a82013-05-06 19:51:56115 net::CertDatabase::GetInstance()->RemoveObserver(this);
[email protected]437a9f8f2013-05-28 18:33:30116 if (LoginState::IsInitialized())
117 LoginState::Get()->RemoveObserver(this);
[email protected]75d93a82013-05-06 19:51:56118}
119
120void CertLoader::AddObserver(CertLoader::Observer* observer) {
121 observers_.AddObserver(observer);
122}
123
124void CertLoader::RemoveObserver(CertLoader::Observer* observer) {
125 observers_.RemoveObserver(observer);
126}
127
128bool CertLoader::CertificatesLoading() const {
129 return certificates_requested_ && !certificates_loaded_;
130}
131
132bool CertLoader::IsHardwareBacked() const {
133 return !tpm_token_name_.empty();
134}
135
[email protected]60833392013-07-26 17:48:49136void CertLoader::MaybeRequestCertificates() {
[email protected]75d93a82013-05-06 19:51:56137 CHECK(thread_checker_.CalledOnValidThread());
[email protected]60833392013-07-26 17:48:49138
139 // This is the entry point to the TPM token initialization process,
140 // which we should do at most once.
141 if (certificates_requested_ || !crypto_task_runner_.get())
142 return;
143
[email protected]437a9f8f2013-05-28 18:33:30144 const bool logged_in = LoginState::IsInitialized() ?
145 LoginState::Get()->IsUserLoggedIn() : false;
146 VLOG(1) << "RequestCertificates: " << logged_in;
[email protected]60833392013-07-26 17:48:49147 if (!logged_in)
[email protected]7d3d0c02013-05-22 12:32:13148 return;
[email protected]75d93a82013-05-06 19:51:56149
150 certificates_requested_ = true;
151
[email protected]60833392013-07-26 17:48:49152 // Ensure we only initialize the TPM token once.
153 DCHECK_EQ(tpm_token_state_, TPM_STATE_UNKNOWN);
[email protected]7d3d0c02013-05-22 12:32:13154 InitializeTokenAndLoadCertificates();
155}
156
157void CertLoader::InitializeTokenAndLoadCertificates() {
158 CHECK(thread_checker_.CalledOnValidThread());
[email protected]60833392013-07-26 17:48:49159 VLOG(1) << "InitializeTokenAndLoadCertificates: " << tpm_token_state_;
[email protected]7d3d0c02013-05-22 12:32:13160
[email protected]437a9f8f2013-05-28 18:33:30161 switch (tpm_token_state_) {
[email protected]7d3d0c02013-05-22 12:32:13162 case TPM_STATE_UNKNOWN: {
[email protected]60833392013-07-26 17:48:49163 crypto_task_runner_->PostTaskAndReply(
164 FROM_HERE,
165 base::Bind(&CallOpenPersistentNSSDB),
166 base::Bind(&CertLoader::OnPersistentNSSDBOpened,
167 initialize_token_factory_.GetWeakPtr()));
168 return;
169 }
170 case TPM_DB_OPENED: {
[email protected]7d3d0c02013-05-22 12:32:13171 DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
[email protected]60833392013-07-26 17:48:49172 base::Bind(&CertLoader::OnTpmIsEnabled,
173 initialize_token_factory_.GetWeakPtr()));
[email protected]7d3d0c02013-05-22 12:32:13174 return;
175 }
176 case TPM_DISABLED: {
177 // TPM is disabled, so proceed with empty tpm token name.
178 StartLoadCertificates();
179 return;
180 }
181 case TPM_ENABLED: {
182 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
183 base::Bind(&CertLoader::OnPkcs11IsTpmTokenReady,
184 initialize_token_factory_.GetWeakPtr()));
185 return;
186 }
187 case TPM_TOKEN_READY: {
188 // Retrieve token_name_ and user_pin_ here since they will never change
189 // and CryptohomeClient calls are not thread safe.
190 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11GetTpmTokenInfo(
191 base::Bind(&CertLoader::OnPkcs11GetTpmTokenInfo,
192 initialize_token_factory_.GetWeakPtr()));
193 return;
194 }
195 case TPM_TOKEN_INFO_RECEIVED: {
[email protected]60833392013-07-26 17:48:49196 if (base::chromeos::IsRunningOnChromeOS()) {
197 base::PostTaskAndReplyWithResult(
198 crypto_task_runner_.get(),
199 FROM_HERE,
200 base::Bind(&crypto::InitializeTPMToken,
201 tpm_token_name_, tpm_user_pin_),
202 base::Bind(&CertLoader::OnTPMTokenInitialized,
203 initialize_token_factory_.GetWeakPtr()));
204 return;
205 }
206 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
207 // FALL_THROUGH_INTENDED
[email protected]7d3d0c02013-05-22 12:32:13208 }
[email protected]60833392013-07-26 17:48:49209 case TPM_TOKEN_INITIALIZED: {
[email protected]7d3d0c02013-05-22 12:32:13210 StartLoadCertificates();
211 return;
212 }
213 }
214}
215
216void CertLoader::RetryTokenInitializationLater() {
[email protected]60833392013-07-26 17:48:49217 CHECK(thread_checker_.CalledOnValidThread());
[email protected]7d3d0c02013-05-22 12:32:13218 LOG(WARNING) << "Re-Requesting Certificates later.";
[email protected]df905632013-05-29 23:04:36219 base::MessageLoop::current()->PostDelayedTask(
[email protected]7d3d0c02013-05-22 12:32:13220 FROM_HERE,
221 base::Bind(&CertLoader::InitializeTokenAndLoadCertificates,
222 initialize_token_factory_.GetWeakPtr()),
223 tpm_request_delay_);
224 tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
[email protected]75d93a82013-05-06 19:51:56225}
226
[email protected]60833392013-07-26 17:48:49227void CertLoader::OnPersistentNSSDBOpened() {
228 VLOG(1) << "PersistentNSSDBOpened";
229 tpm_token_state_ = TPM_DB_OPENED;
230 InitializeTokenAndLoadCertificates();
231}
232
[email protected]53419052013-05-14 04:37:56233// For background see this discussion on dev-tech-crypto.lists.mozilla.org:
234// http://web.archiveorange.com/archive/v/6JJW7E40sypfZGtbkzxX
235//
236// NOTE: This function relies on the convention that the same PKCS#11 ID
237// is shared between a certificate and its associated private and public
238// keys. I tried to implement this with PK11_GetLowLevelKeyIDForCert(),
239// but that always returns NULL on Chrome OS for me.
240std::string CertLoader::GetPkcs11IdForCert(
241 const net::X509Certificate& cert) const {
242 if (!IsHardwareBacked())
243 return std::string();
244
245 CERTCertificateStr* cert_handle = cert.os_cert_handle();
246 SECKEYPrivateKey *priv_key =
247 PK11_FindKeyByAnyCert(cert_handle, NULL /* wincx */);
248 if (!priv_key)
249 return std::string();
250
251 // Get the CKA_ID attribute for a key.
252 SECItem* sec_item = PK11_GetLowLevelKeyIDForPrivateKey(priv_key);
253 std::string pkcs11_id;
254 if (sec_item) {
255 pkcs11_id = base::HexEncode(sec_item->data, sec_item->len);
256 SECITEM_FreeItem(sec_item, PR_TRUE);
257 }
258 SECKEY_DestroyPrivateKey(priv_key);
259
260 return pkcs11_id;
261}
262
[email protected]75d93a82013-05-06 19:51:56263void CertLoader::OnTpmIsEnabled(DBusMethodCallStatus call_status,
264 bool tpm_is_enabled) {
265 VLOG(1) << "OnTpmIsEnabled: " << tpm_is_enabled;
[email protected]7d3d0c02013-05-22 12:32:13266
267 if (call_status == DBUS_METHOD_CALL_SUCCESS && tpm_is_enabled)
268 tpm_token_state_ = TPM_ENABLED;
269 else
270 tpm_token_state_ = TPM_DISABLED;
271
272 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56273}
274
275void CertLoader::OnPkcs11IsTpmTokenReady(DBusMethodCallStatus call_status,
276 bool is_tpm_token_ready) {
277 VLOG(1) << "OnPkcs11IsTpmTokenReady: " << is_tpm_token_ready;
[email protected]7d3d0c02013-05-22 12:32:13278
279 if (call_status == DBUS_METHOD_CALL_FAILURE || !is_tpm_token_ready) {
280 RetryTokenInitializationLater();
[email protected]75d93a82013-05-06 19:51:56281 return;
282 }
283
[email protected]7d3d0c02013-05-22 12:32:13284 tpm_token_state_ = TPM_TOKEN_READY;
285 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56286}
287
288void CertLoader::OnPkcs11GetTpmTokenInfo(DBusMethodCallStatus call_status,
289 const std::string& token_name,
290 const std::string& user_pin) {
291 VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name;
[email protected]7d3d0c02013-05-22 12:32:13292
293 if (call_status == DBUS_METHOD_CALL_FAILURE) {
294 RetryTokenInitializationLater();
[email protected]75d93a82013-05-06 19:51:56295 return;
296 }
[email protected]7d3d0c02013-05-22 12:32:13297
[email protected]75d93a82013-05-06 19:51:56298 tpm_token_name_ = token_name;
299 // TODO(stevenjb): The network code expects a slot ID, not a label. See
300 // crbug.com/201101. For now, use a hard coded, well known slot instead.
301 const char kHardcodedTpmSlot[] = "0";
302 tpm_token_slot_ = kHardcodedTpmSlot;
303 tpm_user_pin_ = user_pin;
[email protected]7d3d0c02013-05-22 12:32:13304 tpm_token_state_ = TPM_TOKEN_INFO_RECEIVED;
[email protected]75d93a82013-05-06 19:51:56305
[email protected]7d3d0c02013-05-22 12:32:13306 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56307}
308
[email protected]60833392013-07-26 17:48:49309void CertLoader::OnTPMTokenInitialized(bool success) {
310 VLOG(1) << "OnTPMTokenInitialized: " << success;
311 if (!success) {
[email protected]7d3d0c02013-05-22 12:32:13312 RetryTokenInitializationLater();
[email protected]75d93a82013-05-06 19:51:56313 return;
314 }
[email protected]60833392013-07-26 17:48:49315 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
[email protected]7d3d0c02013-05-22 12:32:13316 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56317}
318
319void CertLoader::StartLoadCertificates() {
[email protected]60833392013-07-26 17:48:49320 CHECK(thread_checker_.CalledOnValidThread());
321 VLOG(1) << "StartLoadCertificates: " << certificates_update_running_;
[email protected]7d3d0c02013-05-22 12:32:13322
323 if (certificates_update_running_) {
324 certificates_update_required_ = true;
325 return;
326 }
327
328 net::CertificateList* cert_list = new net::CertificateList;
329 certificates_update_running_ = true;
[email protected]8e80c2882013-05-23 10:43:40330 certificates_update_required_ = false;
[email protected]7d3d0c02013-05-22 12:32:13331 base::WorkerPool::GetTaskRunner(true /* task_is_slow */)->
332 PostTaskAndReply(
333 FROM_HERE,
334 base::Bind(LoadNSSCertificates, cert_list),
335 base::Bind(&CertLoader::UpdateCertificates,
336 update_certificates_factory_.GetWeakPtr(),
337 base::Owned(cert_list)));
[email protected]75d93a82013-05-06 19:51:56338}
339
340void CertLoader::UpdateCertificates(net::CertificateList* cert_list) {
341 CHECK(thread_checker_.CalledOnValidThread());
[email protected]7d3d0c02013-05-22 12:32:13342 DCHECK(certificates_update_running_);
343 VLOG(1) << "UpdateCertificates: " << cert_list->size();
[email protected]75d93a82013-05-06 19:51:56344
[email protected]7d3d0c02013-05-22 12:32:13345 // Ignore any existing certificates.
[email protected]75d93a82013-05-06 19:51:56346 cert_list_.swap(*cert_list);
347
[email protected]7d3d0c02013-05-22 12:32:13348 NotifyCertificatesLoaded(!certificates_loaded_);
349 certificates_loaded_ = true;
[email protected]75d93a82013-05-06 19:51:56350
[email protected]7d3d0c02013-05-22 12:32:13351 certificates_update_running_ = false;
352 if (certificates_update_required_)
353 StartLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56354}
355
356void CertLoader::NotifyCertificatesLoaded(bool initial_load) {
357 FOR_EACH_OBSERVER(Observer, observers_,
358 OnCertificatesLoaded(cert_list_, initial_load));
359}
360
361void CertLoader::OnCertTrustChanged(const net::X509Certificate* cert) {
362}
363
364void CertLoader::OnCertAdded(const net::X509Certificate* cert) {
[email protected]7d3d0c02013-05-22 12:32:13365 VLOG(1) << "OnCertAdded";
[email protected]75d93a82013-05-06 19:51:56366 StartLoadCertificates();
367}
368
369void CertLoader::OnCertRemoved(const net::X509Certificate* cert) {
[email protected]7d3d0c02013-05-22 12:32:13370 VLOG(1) << "OnCertRemoved";
[email protected]75d93a82013-05-06 19:51:56371 StartLoadCertificates();
372}
373
374void CertLoader::LoggedInStateChanged(LoginState::LoggedInState state) {
375 VLOG(1) << "LoggedInStateChanged: " << state;
[email protected]60833392013-07-26 17:48:49376 MaybeRequestCertificates();
[email protected]75d93a82013-05-06 19:51:56377}
378
379} // namespace chromeos