Makes the is_blocking method public.
[chromium-blink-merge.git] / chromeos / cert_loader.cc
blobff57d36c1c2ec8a0a4e161d39bbbba38afd69091
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 if (base::chromeos::IsRunningOnChromeOS())
48 net::NSSCertDatabase::GetInstance()->ListCerts(cert_list);
51 void CallOpenPersistentNSSDB() {
52 // Called from crypto_task_runner_.
53 VLOG(1) << "CallOpenPersistentNSSDB";
55 // Ensure we've opened the user's key/certificate database.
56 crypto::OpenPersistentNSSDB();
57 if (base::chromeos::IsRunningOnChromeOS())
58 crypto::EnableTPMTokenForNSS();
61 } // namespace
63 static CertLoader* g_cert_loader = NULL;
64 // static
65 void CertLoader::Initialize() {
66 CHECK(!g_cert_loader);
67 g_cert_loader = new CertLoader();
68 g_cert_loader->Init();
71 // static
72 void CertLoader::Shutdown() {
73 CHECK(g_cert_loader);
74 delete g_cert_loader;
75 g_cert_loader = NULL;
78 // static
79 CertLoader* CertLoader::Get() {
80 CHECK(g_cert_loader)
81 << "CertLoader::Get() called before Initialize()";
82 return g_cert_loader;
85 // static
86 bool CertLoader::IsInitialized() {
87 return g_cert_loader;
90 CertLoader::CertLoader()
91 : certificates_requested_(false),
92 certificates_loaded_(false),
93 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) {
102 void CertLoader::Init() {
103 net::CertDatabase::GetInstance()->AddObserver(this);
104 if (LoginState::IsInitialized())
105 LoginState::Get()->AddObserver(this);
108 void CertLoader::SetCryptoTaskRunner(
109 const scoped_refptr<base::SequencedTaskRunner>& crypto_task_runner) {
110 crypto_task_runner_ = crypto_task_runner;
111 MaybeRequestCertificates();
114 CertLoader::~CertLoader() {
115 net::CertDatabase::GetInstance()->RemoveObserver(this);
116 if (LoginState::IsInitialized())
117 LoginState::Get()->RemoveObserver(this);
120 void CertLoader::AddObserver(CertLoader::Observer* observer) {
121 observers_.AddObserver(observer);
124 void CertLoader::RemoveObserver(CertLoader::Observer* observer) {
125 observers_.RemoveObserver(observer);
128 bool CertLoader::CertificatesLoading() const {
129 return certificates_requested_ && !certificates_loaded_;
132 bool CertLoader::IsHardwareBacked() const {
133 return !tpm_token_name_.empty();
136 void CertLoader::MaybeRequestCertificates() {
137 CHECK(thread_checker_.CalledOnValidThread());
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;
144 const bool logged_in = LoginState::IsInitialized() ?
145 LoginState::Get()->IsUserLoggedIn() : false;
146 VLOG(1) << "RequestCertificates: " << logged_in;
147 if (!logged_in)
148 return;
150 certificates_requested_ = true;
152 // Ensure we only initialize the TPM token once.
153 DCHECK_EQ(tpm_token_state_, TPM_STATE_UNKNOWN);
154 InitializeTokenAndLoadCertificates();
157 void CertLoader::InitializeTokenAndLoadCertificates() {
158 CHECK(thread_checker_.CalledOnValidThread());
159 VLOG(1) << "InitializeTokenAndLoadCertificates: " << tpm_token_state_;
161 switch (tpm_token_state_) {
162 case TPM_STATE_UNKNOWN: {
163 crypto_task_runner_->PostTaskAndReply(
164 FROM_HERE,
165 base::Bind(&CallOpenPersistentNSSDB),
166 base::Bind(&CertLoader::OnPersistentNSSDBOpened,
167 initialize_token_factory_.GetWeakPtr()));
168 return;
170 case TPM_DB_OPENED: {
171 DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
172 base::Bind(&CertLoader::OnTpmIsEnabled,
173 initialize_token_factory_.GetWeakPtr()));
174 return;
176 case TPM_DISABLED: {
177 // TPM is disabled, so proceed with empty tpm token name.
178 StartLoadCertificates();
179 return;
181 case TPM_ENABLED: {
182 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
183 base::Bind(&CertLoader::OnPkcs11IsTpmTokenReady,
184 initialize_token_factory_.GetWeakPtr()));
185 return;
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;
195 case TPM_TOKEN_INFO_RECEIVED: {
196 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;
206 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
207 // FALL_THROUGH_INTENDED
209 case TPM_TOKEN_INITIALIZED: {
210 StartLoadCertificates();
211 return;
216 void CertLoader::RetryTokenInitializationLater() {
217 CHECK(thread_checker_.CalledOnValidThread());
218 LOG(WARNING) << "Re-Requesting Certificates later.";
219 base::MessageLoop::current()->PostDelayedTask(
220 FROM_HERE,
221 base::Bind(&CertLoader::InitializeTokenAndLoadCertificates,
222 initialize_token_factory_.GetWeakPtr()),
223 tpm_request_delay_);
224 tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
227 void CertLoader::OnPersistentNSSDBOpened() {
228 VLOG(1) << "PersistentNSSDBOpened";
229 tpm_token_state_ = TPM_DB_OPENED;
230 InitializeTokenAndLoadCertificates();
233 // For background see this discussion on dev-tech-crypto.lists.mozilla.org:
234 // http://web.archiveorange.com/archive/v/6JJW7E40sypfZGtbkzxX
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.
240 std::string CertLoader::GetPkcs11IdForCert(
241 const net::X509Certificate& cert) const {
242 if (!IsHardwareBacked())
243 return std::string();
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();
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);
258 SECKEY_DestroyPrivateKey(priv_key);
260 return pkcs11_id;
263 void CertLoader::OnTpmIsEnabled(DBusMethodCallStatus call_status,
264 bool tpm_is_enabled) {
265 VLOG(1) << "OnTpmIsEnabled: " << tpm_is_enabled;
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;
272 InitializeTokenAndLoadCertificates();
275 void CertLoader::OnPkcs11IsTpmTokenReady(DBusMethodCallStatus call_status,
276 bool is_tpm_token_ready) {
277 VLOG(1) << "OnPkcs11IsTpmTokenReady: " << is_tpm_token_ready;
279 if (call_status == DBUS_METHOD_CALL_FAILURE || !is_tpm_token_ready) {
280 RetryTokenInitializationLater();
281 return;
284 tpm_token_state_ = TPM_TOKEN_READY;
285 InitializeTokenAndLoadCertificates();
288 void CertLoader::OnPkcs11GetTpmTokenInfo(DBusMethodCallStatus call_status,
289 const std::string& token_name,
290 const std::string& user_pin) {
291 VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name;
293 if (call_status == DBUS_METHOD_CALL_FAILURE) {
294 RetryTokenInitializationLater();
295 return;
298 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;
304 tpm_token_state_ = TPM_TOKEN_INFO_RECEIVED;
306 InitializeTokenAndLoadCertificates();
309 void CertLoader::OnTPMTokenInitialized(bool success) {
310 VLOG(1) << "OnTPMTokenInitialized: " << success;
311 if (!success) {
312 RetryTokenInitializationLater();
313 return;
315 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
316 InitializeTokenAndLoadCertificates();
319 void CertLoader::StartLoadCertificates() {
320 CHECK(thread_checker_.CalledOnValidThread());
321 VLOG(1) << "StartLoadCertificates: " << certificates_update_running_;
323 if (certificates_update_running_) {
324 certificates_update_required_ = true;
325 return;
328 net::CertificateList* cert_list = new net::CertificateList;
329 certificates_update_running_ = true;
330 certificates_update_required_ = false;
331 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)));
340 void CertLoader::UpdateCertificates(net::CertificateList* cert_list) {
341 CHECK(thread_checker_.CalledOnValidThread());
342 DCHECK(certificates_update_running_);
343 VLOG(1) << "UpdateCertificates: " << cert_list->size();
345 // Ignore any existing certificates.
346 cert_list_.swap(*cert_list);
348 NotifyCertificatesLoaded(!certificates_loaded_);
349 certificates_loaded_ = true;
351 certificates_update_running_ = false;
352 if (certificates_update_required_)
353 StartLoadCertificates();
356 void CertLoader::NotifyCertificatesLoaded(bool initial_load) {
357 FOR_EACH_OBSERVER(Observer, observers_,
358 OnCertificatesLoaded(cert_list_, initial_load));
361 void CertLoader::OnCertTrustChanged(const net::X509Certificate* cert) {
364 void CertLoader::OnCertAdded(const net::X509Certificate* cert) {
365 VLOG(1) << "OnCertAdded";
366 StartLoadCertificates();
369 void CertLoader::OnCertRemoved(const net::X509Certificate* cert) {
370 VLOG(1) << "OnCertRemoved";
371 StartLoadCertificates();
374 void CertLoader::LoggedInStateChanged(LoginState::LoggedInState state) {
375 VLOG(1) << "LoggedInStateChanged: " << state;
376 MaybeRequestCertificates();
379 } // namespace chromeos