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"
9 #include "base/message_loop/message_loop_proxy.h"
10 #include "base/observer_list.h"
11 #include "base/sequenced_task_runner.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/sys_info.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"
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
;
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::SysInfo::IsRunningOnChromeOS())
56 crypto::OpenPersistentNSSDB();
57 crypto::EnableTPMTokenForNSS();
62 static CertLoader
* g_cert_loader
= NULL
;
65 void CertLoader::Initialize() {
66 CHECK(!g_cert_loader
);
67 g_cert_loader
= new CertLoader();
71 void CertLoader::Shutdown() {
78 CertLoader
* CertLoader::Get() {
79 CHECK(g_cert_loader
) << "CertLoader::Get() called before Initialize()";
84 bool CertLoader::IsInitialized() {
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
),
96 base::TimeDelta::FromMilliseconds(kInitialRequestDelayMs
)),
97 tpm_token_slot_id_(-1),
98 initialize_token_factory_(this),
99 update_certificates_factory_(this) {
100 if (LoginState::IsInitialized())
101 LoginState::Get()->AddObserver(this);
104 void CertLoader::InitializeTPMForTest() {
105 initialize_tpm_for_test_
= true;
108 void CertLoader::SetCryptoTaskRunner(
109 const scoped_refptr
<base::SequencedTaskRunner
>& crypto_task_runner
) {
110 crypto_task_runner_
= crypto_task_runner
;
111 MaybeRequestCertificates();
114 void CertLoader::SetSlowTaskRunnerForTest(
115 const scoped_refptr
<base::TaskRunner
>& task_runner
) {
116 slow_task_runner_for_test_
= task_runner
;
119 CertLoader::~CertLoader() {
120 net::CertDatabase::GetInstance()->RemoveObserver(this);
121 if (LoginState::IsInitialized())
122 LoginState::Get()->RemoveObserver(this);
125 void CertLoader::AddObserver(CertLoader::Observer
* observer
) {
126 observers_
.AddObserver(observer
);
129 void CertLoader::RemoveObserver(CertLoader::Observer
* observer
) {
130 observers_
.RemoveObserver(observer
);
133 bool CertLoader::CertificatesLoading() const {
134 return certificates_requested_
&& !certificates_loaded_
;
137 bool CertLoader::IsHardwareBacked() const {
138 return !tpm_token_name_
.empty();
141 void CertLoader::MaybeRequestCertificates() {
142 CHECK(thread_checker_
.CalledOnValidThread());
144 // This is the entry point to the TPM token initialization process,
145 // which we should do at most once.
146 if (certificates_requested_
|| !crypto_task_runner_
.get())
149 if (!LoginState::IsInitialized())
152 bool request_certificates
= LoginState::Get()->IsUserLoggedIn() ||
153 LoginState::Get()->IsInSafeMode();
155 VLOG(1) << "RequestCertificates: " << request_certificates
;
156 if (!request_certificates
)
159 certificates_requested_
= true;
161 // Ensure we only initialize the TPM token once.
162 DCHECK_EQ(tpm_token_state_
, TPM_STATE_UNKNOWN
);
163 if (!initialize_tpm_for_test_
&& !base::SysInfo::IsRunningOnChromeOS())
164 tpm_token_state_
= TPM_DISABLED
;
166 // Treat TPM as disabled for guest users since they do not store certs.
167 if (LoginState::Get()->IsGuestUser())
168 tpm_token_state_
= TPM_DISABLED
;
170 InitializeTokenAndLoadCertificates();
173 void CertLoader::InitializeTokenAndLoadCertificates() {
174 CHECK(thread_checker_
.CalledOnValidThread());
175 VLOG(1) << "InitializeTokenAndLoadCertificates: " << tpm_token_state_
;
177 switch (tpm_token_state_
) {
178 case TPM_STATE_UNKNOWN
: {
179 crypto_task_runner_
->PostTaskAndReply(
181 base::Bind(&CallOpenPersistentNSSDB
),
182 base::Bind(&CertLoader::OnPersistentNSSDBOpened
,
183 initialize_token_factory_
.GetWeakPtr()));
186 case TPM_DB_OPENED
: {
187 DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
188 base::Bind(&CertLoader::OnTpmIsEnabled
,
189 initialize_token_factory_
.GetWeakPtr()));
193 // TPM is disabled, so proceed with empty tpm token name.
194 StartLoadCertificates();
198 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
199 base::Bind(&CertLoader::OnPkcs11IsTpmTokenReady
,
200 initialize_token_factory_
.GetWeakPtr()));
203 case TPM_TOKEN_READY
: {
204 // Retrieve token_name_ and user_pin_ here since they will never change
205 // and CryptohomeClient calls are not thread safe.
206 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11GetTpmTokenInfo(
207 base::Bind(&CertLoader::OnPkcs11GetTpmTokenInfo
,
208 initialize_token_factory_
.GetWeakPtr()));
211 case TPM_TOKEN_INFO_RECEIVED
: {
212 base::PostTaskAndReplyWithResult(
213 crypto_task_runner_
.get(),
215 base::Bind(&crypto::InitializeTPMToken
, tpm_token_slot_id_
),
216 base::Bind(&CertLoader::OnTPMTokenInitialized
,
217 initialize_token_factory_
.GetWeakPtr()));
220 case TPM_TOKEN_INITIALIZED
: {
221 StartLoadCertificates();
227 void CertLoader::RetryTokenInitializationLater() {
228 CHECK(thread_checker_
.CalledOnValidThread());
229 LOG(WARNING
) << "Retry token initialization later.";
230 base::MessageLoop::current()->PostDelayedTask(
232 base::Bind(&CertLoader::InitializeTokenAndLoadCertificates
,
233 initialize_token_factory_
.GetWeakPtr()),
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.
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 */);
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
;
265 pkcs11_id
= base::HexEncode(sec_item
->data
, sec_item
->len
);
266 SECITEM_FreeItem(sec_item
, PR_TRUE
);
268 SECKEY_DestroyPrivateKey(priv_key
);
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
;
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();
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
,
302 VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name
;
304 if (call_status
== DBUS_METHOD_CALL_FAILURE
) {
305 RetryTokenInitializationLater();
309 tpm_token_name_
= token_name
;
310 tpm_token_slot_id_
= token_slot_id
;
311 tpm_user_pin_
= user_pin
;
312 tpm_token_state_
= TPM_TOKEN_INFO_RECEIVED
;
314 InitializeTokenAndLoadCertificates();
317 void CertLoader::OnTPMTokenInitialized(bool success
) {
318 VLOG(1) << "OnTPMTokenInitialized: " << success
;
320 RetryTokenInitializationLater();
323 tpm_token_state_
= TPM_TOKEN_INITIALIZED
;
324 InitializeTokenAndLoadCertificates();
327 void CertLoader::StartLoadCertificates() {
328 DCHECK(!certificates_loaded_
&& !certificates_update_running_
);
329 net::CertDatabase::GetInstance()->AddObserver(this);
333 void CertLoader::LoadCertificates() {
334 CHECK(thread_checker_
.CalledOnValidThread());
335 VLOG(1) << "LoadCertificates: " << certificates_update_running_
;
337 if (certificates_update_running_
) {
338 certificates_update_required_
= true;
342 net::CertificateList
* cert_list
= new net::CertificateList
;
343 certificates_update_running_
= true;
344 certificates_update_required_
= false;
346 base::TaskRunner
* task_runner
= slow_task_runner_for_test_
.get();
348 task_runner
= base::WorkerPool::GetTaskRunner(true /* task is slow */);
349 task_runner
->PostTaskAndReply(
351 base::Bind(LoadNSSCertificates
, cert_list
),
352 base::Bind(&CertLoader::UpdateCertificates
,
353 update_certificates_factory_
.GetWeakPtr(),
354 base::Owned(cert_list
)));
357 void CertLoader::UpdateCertificates(net::CertificateList
* cert_list
) {
358 CHECK(thread_checker_
.CalledOnValidThread());
359 DCHECK(certificates_update_running_
);
360 VLOG(1) << "UpdateCertificates: " << cert_list
->size();
362 // Ignore any existing certificates.
363 cert_list_
.swap(*cert_list
);
365 bool initial_load
= !certificates_loaded_
;
366 certificates_loaded_
= true;
367 NotifyCertificatesLoaded(initial_load
);
369 certificates_update_running_
= false;
370 if (certificates_update_required_
)
374 void CertLoader::NotifyCertificatesLoaded(bool initial_load
) {
375 FOR_EACH_OBSERVER(Observer
, observers_
,
376 OnCertificatesLoaded(cert_list_
, initial_load
));
379 void CertLoader::OnCACertChanged(const net::X509Certificate
* cert
) {
380 // This is triggered when a CA certificate is modified.
381 VLOG(1) << "OnCACertChanged";
385 void CertLoader::OnCertAdded(const net::X509Certificate
* cert
) {
386 // This is triggered when a client certificate is added.
387 VLOG(1) << "OnCertAdded";
391 void CertLoader::OnCertRemoved(const net::X509Certificate
* cert
) {
392 VLOG(1) << "OnCertRemoved";
396 void CertLoader::LoggedInStateChanged() {
397 VLOG(1) << "LoggedInStateChanged";
398 MaybeRequestCertificates();
401 } // namespace chromeos