Allow overlapping sync and async startup requests
[chromium-blink-merge.git] / chromeos / cert_loader.cc
blob060d4641129dede3f433eeaef353a20beb0e9944
1 // 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.
5 #include "chromeos/cert_loader.h"
7 #include <algorithm>
9 #include "base/chromeos/chromeos_version.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/observer_list.h"
12 #include "base/sequenced_task_runner.h"
13 #include "base/strings/string_number_conversions.h"
14 #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"
24 namespace chromeos {
26 namespace {
28 const int64 kInitialRequestDelayMs = 100;
29 const int64 kMaxRequestDelayMs = 300000; // 5 minutes
31 // Calculates the delay before running next attempt to initiatialize the TPM
32 // token, if |last_delay| was the last or initial delay.
33 base::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;
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;
46 void LoadNSSCertificates(net::CertificateList* cert_list) {
47 net::NSSCertDatabase::GetInstance()->ListCerts(cert_list);
50 void CallOpenPersistentNSSDB() {
51 // Called from crypto_task_runner_.
52 VLOG(1) << "CallOpenPersistentNSSDB";
54 // Ensure we've opened the user's key/certificate database.
55 if (base::chromeos::IsRunningOnChromeOS())
56 crypto::OpenPersistentNSSDB();
57 crypto::EnableTPMTokenForNSS();
60 } // namespace
62 static CertLoader* g_cert_loader = NULL;
64 // static
65 void CertLoader::Initialize() {
66 CHECK(!g_cert_loader);
67 g_cert_loader = new CertLoader();
70 // static
71 void CertLoader::Shutdown() {
72 CHECK(g_cert_loader);
73 delete g_cert_loader;
74 g_cert_loader = NULL;
77 // static
78 CertLoader* CertLoader::Get() {
79 CHECK(g_cert_loader) << "CertLoader::Get() called before Initialize()";
80 return g_cert_loader;
83 // static
84 bool CertLoader::IsInitialized() {
85 return g_cert_loader;
88 CertLoader::CertLoader()
89 : initialize_tpm_for_test_(false),
90 certificates_requested_(false),
91 certificates_loaded_(false),
92 certificates_update_required_(false),
93 certificates_update_running_(false),
94 tpm_token_state_(TPM_STATE_UNKNOWN),
95 tpm_request_delay_(
96 base::TimeDelta::FromMilliseconds(kInitialRequestDelayMs)),
97 initialize_token_factory_(this),
98 update_certificates_factory_(this) {
99 if (LoginState::IsInitialized())
100 LoginState::Get()->AddObserver(this);
103 void CertLoader::InitializeTPMForTest() {
104 initialize_tpm_for_test_ = true;
107 void CertLoader::SetCryptoTaskRunner(
108 const scoped_refptr<base::SequencedTaskRunner>& crypto_task_runner) {
109 crypto_task_runner_ = crypto_task_runner;
110 MaybeRequestCertificates();
113 void CertLoader::SetSlowTaskRunnerForTest(
114 const scoped_refptr<base::TaskRunner>& task_runner) {
115 slow_task_runner_for_test_ = task_runner;
118 CertLoader::~CertLoader() {
119 net::CertDatabase::GetInstance()->RemoveObserver(this);
120 if (LoginState::IsInitialized())
121 LoginState::Get()->RemoveObserver(this);
124 void CertLoader::AddObserver(CertLoader::Observer* observer) {
125 observers_.AddObserver(observer);
128 void CertLoader::RemoveObserver(CertLoader::Observer* observer) {
129 observers_.RemoveObserver(observer);
132 bool CertLoader::CertificatesLoading() const {
133 return certificates_requested_ && !certificates_loaded_;
136 bool CertLoader::IsHardwareBacked() const {
137 return !tpm_token_name_.empty();
140 void CertLoader::MaybeRequestCertificates() {
141 CHECK(thread_checker_.CalledOnValidThread());
143 // This is the entry point to the TPM token initialization process,
144 // which we should do at most once.
145 if (certificates_requested_ || !crypto_task_runner_.get())
146 return;
148 const bool logged_in = LoginState::IsInitialized() ?
149 LoginState::Get()->IsUserLoggedIn() : false;
150 VLOG(1) << "RequestCertificates: " << logged_in;
151 if (!logged_in)
152 return;
154 certificates_requested_ = true;
156 // Ensure we only initialize the TPM token once.
157 DCHECK_EQ(tpm_token_state_, TPM_STATE_UNKNOWN);
158 if (!initialize_tpm_for_test_ && !base::chromeos::IsRunningOnChromeOS())
159 tpm_token_state_ = TPM_DISABLED;
161 // Treat TPM as disabled for guest users since they do not store certs.
162 if (LoginState::IsInitialized() && LoginState::Get()->IsGuestUser())
163 tpm_token_state_ = TPM_DISABLED;
165 InitializeTokenAndLoadCertificates();
168 void CertLoader::InitializeTokenAndLoadCertificates() {
169 CHECK(thread_checker_.CalledOnValidThread());
170 VLOG(1) << "InitializeTokenAndLoadCertificates: " << tpm_token_state_;
172 switch (tpm_token_state_) {
173 case TPM_STATE_UNKNOWN: {
174 crypto_task_runner_->PostTaskAndReply(
175 FROM_HERE,
176 base::Bind(&CallOpenPersistentNSSDB),
177 base::Bind(&CertLoader::OnPersistentNSSDBOpened,
178 initialize_token_factory_.GetWeakPtr()));
179 return;
181 case TPM_DB_OPENED: {
182 DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
183 base::Bind(&CertLoader::OnTpmIsEnabled,
184 initialize_token_factory_.GetWeakPtr()));
185 return;
187 case TPM_DISABLED: {
188 // TPM is disabled, so proceed with empty tpm token name.
189 StartLoadCertificates();
190 return;
192 case TPM_ENABLED: {
193 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
194 base::Bind(&CertLoader::OnPkcs11IsTpmTokenReady,
195 initialize_token_factory_.GetWeakPtr()));
196 return;
198 case TPM_TOKEN_READY: {
199 // Retrieve token_name_ and user_pin_ here since they will never change
200 // and CryptohomeClient calls are not thread safe.
201 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11GetTpmTokenInfo(
202 base::Bind(&CertLoader::OnPkcs11GetTpmTokenInfo,
203 initialize_token_factory_.GetWeakPtr()));
204 return;
206 case TPM_TOKEN_INFO_RECEIVED: {
207 base::PostTaskAndReplyWithResult(
208 crypto_task_runner_.get(),
209 FROM_HERE,
210 base::Bind(
211 &crypto::InitializeTPMToken, tpm_token_name_, tpm_user_pin_),
212 base::Bind(&CertLoader::OnTPMTokenInitialized,
213 initialize_token_factory_.GetWeakPtr()));
214 return;
216 case TPM_TOKEN_INITIALIZED: {
217 StartLoadCertificates();
218 return;
223 void CertLoader::RetryTokenInitializationLater() {
224 CHECK(thread_checker_.CalledOnValidThread());
225 LOG(WARNING) << "Retry token initialization later.";
226 base::MessageLoop::current()->PostDelayedTask(
227 FROM_HERE,
228 base::Bind(&CertLoader::InitializeTokenAndLoadCertificates,
229 initialize_token_factory_.GetWeakPtr()),
230 tpm_request_delay_);
231 tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
234 void CertLoader::OnPersistentNSSDBOpened() {
235 VLOG(1) << "PersistentNSSDBOpened";
236 tpm_token_state_ = TPM_DB_OPENED;
237 InitializeTokenAndLoadCertificates();
240 // This is copied from chrome/common/net/x509_certificate_model_nss.cc.
241 // For background see this discussion on dev-tech-crypto.lists.mozilla.org:
242 // http://web.archiveorange.com/archive/v/6JJW7E40sypfZGtbkzxX
244 // NOTE: This function relies on the convention that the same PKCS#11 ID
245 // is shared between a certificate and its associated private and public
246 // keys. I tried to implement this with PK11_GetLowLevelKeyIDForCert(),
247 // but that always returns NULL on Chrome OS for me.
249 // static
250 std::string CertLoader::GetPkcs11IdForCert(const net::X509Certificate& cert) {
251 CERTCertificateStr* cert_handle = cert.os_cert_handle();
252 SECKEYPrivateKey *priv_key =
253 PK11_FindKeyByAnyCert(cert_handle, NULL /* wincx */);
254 if (!priv_key)
255 return std::string();
257 // Get the CKA_ID attribute for a key.
258 SECItem* sec_item = PK11_GetLowLevelKeyIDForPrivateKey(priv_key);
259 std::string pkcs11_id;
260 if (sec_item) {
261 pkcs11_id = base::HexEncode(sec_item->data, sec_item->len);
262 SECITEM_FreeItem(sec_item, PR_TRUE);
264 SECKEY_DestroyPrivateKey(priv_key);
266 return pkcs11_id;
269 void CertLoader::OnTpmIsEnabled(DBusMethodCallStatus call_status,
270 bool tpm_is_enabled) {
271 VLOG(1) << "OnTpmIsEnabled: " << tpm_is_enabled;
273 if (call_status == DBUS_METHOD_CALL_SUCCESS && tpm_is_enabled)
274 tpm_token_state_ = TPM_ENABLED;
275 else
276 tpm_token_state_ = TPM_DISABLED;
278 InitializeTokenAndLoadCertificates();
281 void CertLoader::OnPkcs11IsTpmTokenReady(DBusMethodCallStatus call_status,
282 bool is_tpm_token_ready) {
283 VLOG(1) << "OnPkcs11IsTpmTokenReady: " << is_tpm_token_ready;
285 if (call_status == DBUS_METHOD_CALL_FAILURE || !is_tpm_token_ready) {
286 RetryTokenInitializationLater();
287 return;
290 tpm_token_state_ = TPM_TOKEN_READY;
291 InitializeTokenAndLoadCertificates();
294 void CertLoader::OnPkcs11GetTpmTokenInfo(DBusMethodCallStatus call_status,
295 const std::string& token_name,
296 const std::string& user_pin) {
297 VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name;
299 if (call_status == DBUS_METHOD_CALL_FAILURE) {
300 RetryTokenInitializationLater();
301 return;
304 tpm_token_name_ = token_name;
305 // TODO(stevenjb): The network code expects a slot ID, not a label. See
306 // crbug.com/201101. For now, use a hard coded, well known slot instead.
307 const char kHardcodedTpmSlot[] = "0";
308 tpm_token_slot_ = kHardcodedTpmSlot;
309 tpm_user_pin_ = user_pin;
310 tpm_token_state_ = TPM_TOKEN_INFO_RECEIVED;
312 InitializeTokenAndLoadCertificates();
315 void CertLoader::OnTPMTokenInitialized(bool success) {
316 VLOG(1) << "OnTPMTokenInitialized: " << success;
317 if (!success) {
318 RetryTokenInitializationLater();
319 return;
321 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
322 InitializeTokenAndLoadCertificates();
325 void CertLoader::StartLoadCertificates() {
326 DCHECK(!certificates_loaded_ && !certificates_update_running_);
327 net::CertDatabase::GetInstance()->AddObserver(this);
328 LoadCertificates();
331 void CertLoader::LoadCertificates() {
332 CHECK(thread_checker_.CalledOnValidThread());
333 VLOG(1) << "LoadCertificates: " << certificates_update_running_;
335 if (certificates_update_running_) {
336 certificates_update_required_ = true;
337 return;
340 net::CertificateList* cert_list = new net::CertificateList;
341 certificates_update_running_ = true;
342 certificates_update_required_ = false;
344 base::TaskRunner* task_runner = slow_task_runner_for_test_.get();
345 if (!task_runner)
346 task_runner = base::WorkerPool::GetTaskRunner(true /* task is slow */);
347 task_runner->PostTaskAndReply(
348 FROM_HERE,
349 base::Bind(LoadNSSCertificates, cert_list),
350 base::Bind(&CertLoader::UpdateCertificates,
351 update_certificates_factory_.GetWeakPtr(),
352 base::Owned(cert_list)));
355 void CertLoader::UpdateCertificates(net::CertificateList* cert_list) {
356 CHECK(thread_checker_.CalledOnValidThread());
357 DCHECK(certificates_update_running_);
358 VLOG(1) << "UpdateCertificates: " << cert_list->size();
360 // Ignore any existing certificates.
361 cert_list_.swap(*cert_list);
363 bool initial_load = !certificates_loaded_;
364 certificates_loaded_ = true;
365 NotifyCertificatesLoaded(initial_load);
367 certificates_update_running_ = false;
368 if (certificates_update_required_)
369 LoadCertificates();
372 void CertLoader::NotifyCertificatesLoaded(bool initial_load) {
373 FOR_EACH_OBSERVER(Observer, observers_,
374 OnCertificatesLoaded(cert_list_, initial_load));
377 void CertLoader::OnCertTrustChanged(const net::X509Certificate* cert) {
380 void CertLoader::OnCertAdded(const net::X509Certificate* cert) {
381 VLOG(1) << "OnCertAdded";
382 LoadCertificates();
385 void CertLoader::OnCertRemoved(const net::X509Certificate* cert) {
386 VLOG(1) << "OnCertRemoved";
387 LoadCertificates();
390 void CertLoader::LoggedInStateChanged(LoginState::LoggedInState state) {
391 VLOG(1) << "LoggedInStateChanged: " << state;
392 MaybeRequestCertificates();
395 } // namespace chromeos