Simple Cache: transactional index in subdirectory
[chromium-blink-merge.git] / chromeos / cert_loader.cc
blob62a4f120429163f863ea89818c087acb374df2e0
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 if (!LoginState::IsInitialized())
149 return;
151 bool request_certificates = LoginState::Get()->IsUserLoggedIn() ||
152 LoginState::Get()->IsInSafeMode();
154 VLOG(1) << "RequestCertificates: " << request_certificates;
155 if (!request_certificates)
156 return;
158 certificates_requested_ = true;
160 // Ensure we only initialize the TPM token once.
161 DCHECK_EQ(tpm_token_state_, TPM_STATE_UNKNOWN);
162 if (!initialize_tpm_for_test_ && !base::chromeos::IsRunningOnChromeOS())
163 tpm_token_state_ = TPM_DISABLED;
165 // Treat TPM as disabled for guest users since they do not store certs.
166 if (LoginState::Get()->IsGuestUser())
167 tpm_token_state_ = TPM_DISABLED;
169 InitializeTokenAndLoadCertificates();
172 void CertLoader::InitializeTokenAndLoadCertificates() {
173 CHECK(thread_checker_.CalledOnValidThread());
174 VLOG(1) << "InitializeTokenAndLoadCertificates: " << tpm_token_state_;
176 switch (tpm_token_state_) {
177 case TPM_STATE_UNKNOWN: {
178 crypto_task_runner_->PostTaskAndReply(
179 FROM_HERE,
180 base::Bind(&CallOpenPersistentNSSDB),
181 base::Bind(&CertLoader::OnPersistentNSSDBOpened,
182 initialize_token_factory_.GetWeakPtr()));
183 return;
185 case TPM_DB_OPENED: {
186 DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
187 base::Bind(&CertLoader::OnTpmIsEnabled,
188 initialize_token_factory_.GetWeakPtr()));
189 return;
191 case TPM_DISABLED: {
192 // TPM is disabled, so proceed with empty tpm token name.
193 StartLoadCertificates();
194 return;
196 case TPM_ENABLED: {
197 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
198 base::Bind(&CertLoader::OnPkcs11IsTpmTokenReady,
199 initialize_token_factory_.GetWeakPtr()));
200 return;
202 case TPM_TOKEN_READY: {
203 // Retrieve token_name_ and user_pin_ here since they will never change
204 // and CryptohomeClient calls are not thread safe.
205 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11GetTpmTokenInfo(
206 base::Bind(&CertLoader::OnPkcs11GetTpmTokenInfo,
207 initialize_token_factory_.GetWeakPtr()));
208 return;
210 case TPM_TOKEN_INFO_RECEIVED: {
211 base::PostTaskAndReplyWithResult(
212 crypto_task_runner_.get(),
213 FROM_HERE,
214 base::Bind(
215 &crypto::InitializeTPMToken, tpm_token_name_, tpm_user_pin_),
216 base::Bind(&CertLoader::OnTPMTokenInitialized,
217 initialize_token_factory_.GetWeakPtr()));
218 return;
220 case TPM_TOKEN_INITIALIZED: {
221 StartLoadCertificates();
222 return;
227 void CertLoader::RetryTokenInitializationLater() {
228 CHECK(thread_checker_.CalledOnValidThread());
229 LOG(WARNING) << "Retry token initialization later.";
230 base::MessageLoop::current()->PostDelayedTask(
231 FROM_HERE,
232 base::Bind(&CertLoader::InitializeTokenAndLoadCertificates,
233 initialize_token_factory_.GetWeakPtr()),
234 tpm_request_delay_);
235 tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
238 void CertLoader::OnPersistentNSSDBOpened() {
239 VLOG(1) << "PersistentNSSDBOpened";
240 tpm_token_state_ = TPM_DB_OPENED;
241 InitializeTokenAndLoadCertificates();
244 // This is copied from chrome/common/net/x509_certificate_model_nss.cc.
245 // For background see this discussion on dev-tech-crypto.lists.mozilla.org:
246 // http://web.archiveorange.com/archive/v/6JJW7E40sypfZGtbkzxX
248 // NOTE: This function relies on the convention that the same PKCS#11 ID
249 // is shared between a certificate and its associated private and public
250 // keys. I tried to implement this with PK11_GetLowLevelKeyIDForCert(),
251 // but that always returns NULL on Chrome OS for me.
253 // static
254 std::string CertLoader::GetPkcs11IdForCert(const net::X509Certificate& cert) {
255 CERTCertificateStr* cert_handle = cert.os_cert_handle();
256 SECKEYPrivateKey *priv_key =
257 PK11_FindKeyByAnyCert(cert_handle, NULL /* wincx */);
258 if (!priv_key)
259 return std::string();
261 // Get the CKA_ID attribute for a key.
262 SECItem* sec_item = PK11_GetLowLevelKeyIDForPrivateKey(priv_key);
263 std::string pkcs11_id;
264 if (sec_item) {
265 pkcs11_id = base::HexEncode(sec_item->data, sec_item->len);
266 SECITEM_FreeItem(sec_item, PR_TRUE);
268 SECKEY_DestroyPrivateKey(priv_key);
270 return pkcs11_id;
273 void CertLoader::OnTpmIsEnabled(DBusMethodCallStatus call_status,
274 bool tpm_is_enabled) {
275 VLOG(1) << "OnTpmIsEnabled: " << tpm_is_enabled;
277 if (call_status == DBUS_METHOD_CALL_SUCCESS && tpm_is_enabled)
278 tpm_token_state_ = TPM_ENABLED;
279 else
280 tpm_token_state_ = TPM_DISABLED;
282 InitializeTokenAndLoadCertificates();
285 void CertLoader::OnPkcs11IsTpmTokenReady(DBusMethodCallStatus call_status,
286 bool is_tpm_token_ready) {
287 VLOG(1) << "OnPkcs11IsTpmTokenReady: " << is_tpm_token_ready;
289 if (call_status == DBUS_METHOD_CALL_FAILURE || !is_tpm_token_ready) {
290 RetryTokenInitializationLater();
291 return;
294 tpm_token_state_ = TPM_TOKEN_READY;
295 InitializeTokenAndLoadCertificates();
298 void CertLoader::OnPkcs11GetTpmTokenInfo(DBusMethodCallStatus call_status,
299 const std::string& token_name,
300 const std::string& user_pin) {
301 VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name;
303 if (call_status == DBUS_METHOD_CALL_FAILURE) {
304 RetryTokenInitializationLater();
305 return;
308 tpm_token_name_ = token_name;
309 // TODO(stevenjb): The network code expects a slot ID, not a label. See
310 // crbug.com/201101. For now, use a hard coded, well known slot instead.
311 const char kHardcodedTpmSlot[] = "0";
312 tpm_token_slot_ = kHardcodedTpmSlot;
313 tpm_user_pin_ = user_pin;
314 tpm_token_state_ = TPM_TOKEN_INFO_RECEIVED;
316 InitializeTokenAndLoadCertificates();
319 void CertLoader::OnTPMTokenInitialized(bool success) {
320 VLOG(1) << "OnTPMTokenInitialized: " << success;
321 if (!success) {
322 RetryTokenInitializationLater();
323 return;
325 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
326 InitializeTokenAndLoadCertificates();
329 void CertLoader::StartLoadCertificates() {
330 DCHECK(!certificates_loaded_ && !certificates_update_running_);
331 net::CertDatabase::GetInstance()->AddObserver(this);
332 LoadCertificates();
335 void CertLoader::LoadCertificates() {
336 CHECK(thread_checker_.CalledOnValidThread());
337 VLOG(1) << "LoadCertificates: " << certificates_update_running_;
339 if (certificates_update_running_) {
340 certificates_update_required_ = true;
341 return;
344 net::CertificateList* cert_list = new net::CertificateList;
345 certificates_update_running_ = true;
346 certificates_update_required_ = false;
348 base::TaskRunner* task_runner = slow_task_runner_for_test_.get();
349 if (!task_runner)
350 task_runner = base::WorkerPool::GetTaskRunner(true /* task is slow */);
351 task_runner->PostTaskAndReply(
352 FROM_HERE,
353 base::Bind(LoadNSSCertificates, cert_list),
354 base::Bind(&CertLoader::UpdateCertificates,
355 update_certificates_factory_.GetWeakPtr(),
356 base::Owned(cert_list)));
359 void CertLoader::UpdateCertificates(net::CertificateList* cert_list) {
360 CHECK(thread_checker_.CalledOnValidThread());
361 DCHECK(certificates_update_running_);
362 VLOG(1) << "UpdateCertificates: " << cert_list->size();
364 // Ignore any existing certificates.
365 cert_list_.swap(*cert_list);
367 bool initial_load = !certificates_loaded_;
368 certificates_loaded_ = true;
369 NotifyCertificatesLoaded(initial_load);
371 certificates_update_running_ = false;
372 if (certificates_update_required_)
373 LoadCertificates();
376 void CertLoader::NotifyCertificatesLoaded(bool initial_load) {
377 FOR_EACH_OBSERVER(Observer, observers_,
378 OnCertificatesLoaded(cert_list_, initial_load));
381 void CertLoader::OnCertTrustChanged(const net::X509Certificate* cert) {
384 void CertLoader::OnCertAdded(const net::X509Certificate* cert) {
385 VLOG(1) << "OnCertAdded";
386 LoadCertificates();
389 void CertLoader::OnCertRemoved(const net::X509Certificate* cert) {
390 VLOG(1) << "OnCertRemoved";
391 LoadCertificates();
394 void CertLoader::LoggedInStateChanged() {
395 VLOG(1) << "LoggedInStateChanged";
396 MaybeRequestCertificates();
399 } // namespace chromeos