blob: 060d4641129dede3f433eeaef353a20beb0e9944 [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]166741182013-08-06 11:31:2747 net::NSSCertDatabase::GetInstance()->ListCerts(cert_list);
[email protected]75d93a82013-05-06 19:51:5648}
49
[email protected]60833392013-07-26 17:48:4950void CallOpenPersistentNSSDB() {
51 // Called from crypto_task_runner_.
52 VLOG(1) << "CallOpenPersistentNSSDB";
53
54 // Ensure we've opened the user's key/certificate database.
[email protected]72b3a7e2013-08-13 15:30:0455 if (base::chromeos::IsRunningOnChromeOS())
56 crypto::OpenPersistentNSSDB();
[email protected]166741182013-08-06 11:31:2757 crypto::EnableTPMTokenForNSS();
[email protected]60833392013-07-26 17:48:4958}
59
[email protected]75d93a82013-05-06 19:51:5660} // namespace
61
[email protected]60833392013-07-26 17:48:4962static CertLoader* g_cert_loader = NULL;
[email protected]18e8d54f2013-08-06 17:15:4863
[email protected]60833392013-07-26 17:48:4964// static
65void CertLoader::Initialize() {
66 CHECK(!g_cert_loader);
67 g_cert_loader = new CertLoader();
[email protected]60833392013-07-26 17:48:4968}
69
70// static
71void CertLoader::Shutdown() {
72 CHECK(g_cert_loader);
73 delete g_cert_loader;
74 g_cert_loader = NULL;
75}
76
77// static
78CertLoader* CertLoader::Get() {
[email protected]166741182013-08-06 11:31:2779 CHECK(g_cert_loader) << "CertLoader::Get() called before Initialize()";
[email protected]60833392013-07-26 17:48:4980 return g_cert_loader;
81}
82
83// static
84bool CertLoader::IsInitialized() {
85 return g_cert_loader;
86}
87
[email protected]75d93a82013-05-06 19:51:5688CertLoader::CertLoader()
[email protected]72b3a7e2013-08-13 15:30:0489 : initialize_tpm_for_test_(false),
90 certificates_requested_(false),
[email protected]75d93a82013-05-06 19:51:5691 certificates_loaded_(false),
[email protected]7d3d0c02013-05-22 12:32:1392 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) {
[email protected]437a9f8f2013-05-28 18:33:3099 if (LoginState::IsInitialized())
100 LoginState::Get()->AddObserver(this);
[email protected]60833392013-07-26 17:48:49101}
102
[email protected]72b3a7e2013-08-13 15:30:04103void CertLoader::InitializeTPMForTest() {
104 initialize_tpm_for_test_ = true;
105}
106
[email protected]60833392013-07-26 17:48:49107void CertLoader::SetCryptoTaskRunner(
108 const scoped_refptr<base::SequencedTaskRunner>& crypto_task_runner) {
109 crypto_task_runner_ = crypto_task_runner;
110 MaybeRequestCertificates();
[email protected]75d93a82013-05-06 19:51:56111}
112
[email protected]18e8d54f2013-08-06 17:15:48113void CertLoader::SetSlowTaskRunnerForTest(
[email protected]b1f3f5272013-08-12 15:22:49114 const scoped_refptr<base::TaskRunner>& task_runner) {
[email protected]18e8d54f2013-08-06 17:15:48115 slow_task_runner_for_test_ = task_runner;
116}
117
[email protected]75d93a82013-05-06 19:51:56118CertLoader::~CertLoader() {
[email protected]75d93a82013-05-06 19:51:56119 net::CertDatabase::GetInstance()->RemoveObserver(this);
[email protected]437a9f8f2013-05-28 18:33:30120 if (LoginState::IsInitialized())
121 LoginState::Get()->RemoveObserver(this);
[email protected]75d93a82013-05-06 19:51:56122}
123
124void CertLoader::AddObserver(CertLoader::Observer* observer) {
125 observers_.AddObserver(observer);
126}
127
128void CertLoader::RemoveObserver(CertLoader::Observer* observer) {
129 observers_.RemoveObserver(observer);
130}
131
132bool CertLoader::CertificatesLoading() const {
133 return certificates_requested_ && !certificates_loaded_;
134}
135
136bool CertLoader::IsHardwareBacked() const {
137 return !tpm_token_name_.empty();
138}
139
[email protected]60833392013-07-26 17:48:49140void CertLoader::MaybeRequestCertificates() {
[email protected]75d93a82013-05-06 19:51:56141 CHECK(thread_checker_.CalledOnValidThread());
[email protected]60833392013-07-26 17:48:49142
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;
147
[email protected]437a9f8f2013-05-28 18:33:30148 const bool logged_in = LoginState::IsInitialized() ?
149 LoginState::Get()->IsUserLoggedIn() : false;
150 VLOG(1) << "RequestCertificates: " << logged_in;
[email protected]60833392013-07-26 17:48:49151 if (!logged_in)
[email protected]7d3d0c02013-05-22 12:32:13152 return;
[email protected]75d93a82013-05-06 19:51:56153
154 certificates_requested_ = true;
155
[email protected]60833392013-07-26 17:48:49156 // Ensure we only initialize the TPM token once.
157 DCHECK_EQ(tpm_token_state_, TPM_STATE_UNKNOWN);
[email protected]72b3a7e2013-08-13 15:30:04158 if (!initialize_tpm_for_test_ && !base::chromeos::IsRunningOnChromeOS())
159 tpm_token_state_ = TPM_DISABLED;
160
161 // Treat TPM as disabled for guest users since they do not store certs.
162 if (LoginState::IsInitialized() && LoginState::Get()->IsGuestUser())
[email protected]166741182013-08-06 11:31:27163 tpm_token_state_ = TPM_DISABLED;
164
[email protected]7d3d0c02013-05-22 12:32:13165 InitializeTokenAndLoadCertificates();
166}
167
168void CertLoader::InitializeTokenAndLoadCertificates() {
169 CHECK(thread_checker_.CalledOnValidThread());
[email protected]60833392013-07-26 17:48:49170 VLOG(1) << "InitializeTokenAndLoadCertificates: " << tpm_token_state_;
[email protected]7d3d0c02013-05-22 12:32:13171
[email protected]437a9f8f2013-05-28 18:33:30172 switch (tpm_token_state_) {
[email protected]7d3d0c02013-05-22 12:32:13173 case TPM_STATE_UNKNOWN: {
[email protected]60833392013-07-26 17:48:49174 crypto_task_runner_->PostTaskAndReply(
175 FROM_HERE,
176 base::Bind(&CallOpenPersistentNSSDB),
177 base::Bind(&CertLoader::OnPersistentNSSDBOpened,
178 initialize_token_factory_.GetWeakPtr()));
179 return;
180 }
181 case TPM_DB_OPENED: {
[email protected]7d3d0c02013-05-22 12:32:13182 DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
[email protected]60833392013-07-26 17:48:49183 base::Bind(&CertLoader::OnTpmIsEnabled,
184 initialize_token_factory_.GetWeakPtr()));
[email protected]7d3d0c02013-05-22 12:32:13185 return;
186 }
187 case TPM_DISABLED: {
188 // TPM is disabled, so proceed with empty tpm token name.
189 StartLoadCertificates();
190 return;
191 }
192 case TPM_ENABLED: {
193 DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
194 base::Bind(&CertLoader::OnPkcs11IsTpmTokenReady,
195 initialize_token_factory_.GetWeakPtr()));
196 return;
197 }
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;
205 }
206 case TPM_TOKEN_INFO_RECEIVED: {
[email protected]166741182013-08-06 11:31:27207 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;
[email protected]7d3d0c02013-05-22 12:32:13215 }
[email protected]60833392013-07-26 17:48:49216 case TPM_TOKEN_INITIALIZED: {
[email protected]7d3d0c02013-05-22 12:32:13217 StartLoadCertificates();
218 return;
219 }
220 }
221}
222
223void CertLoader::RetryTokenInitializationLater() {
[email protected]60833392013-07-26 17:48:49224 CHECK(thread_checker_.CalledOnValidThread());
[email protected]72b3a7e2013-08-13 15:30:04225 LOG(WARNING) << "Retry token initialization later.";
[email protected]df905632013-05-29 23:04:36226 base::MessageLoop::current()->PostDelayedTask(
[email protected]7d3d0c02013-05-22 12:32:13227 FROM_HERE,
228 base::Bind(&CertLoader::InitializeTokenAndLoadCertificates,
229 initialize_token_factory_.GetWeakPtr()),
230 tpm_request_delay_);
231 tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
[email protected]75d93a82013-05-06 19:51:56232}
233
[email protected]60833392013-07-26 17:48:49234void CertLoader::OnPersistentNSSDBOpened() {
235 VLOG(1) << "PersistentNSSDBOpened";
236 tpm_token_state_ = TPM_DB_OPENED;
237 InitializeTokenAndLoadCertificates();
238}
239
[email protected]b1f3f5272013-08-12 15:22:49240// This is copied from chrome/common/net/x509_certificate_model_nss.cc.
[email protected]53419052013-05-14 04:37:56241// For background see this discussion on dev-tech-crypto.lists.mozilla.org:
242// http://web.archiveorange.com/archive/v/6JJW7E40sypfZGtbkzxX
243//
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.
[email protected]53419052013-05-14 04:37:56248
[email protected]b1f3f5272013-08-12 15:22:49249// static
250std::string CertLoader::GetPkcs11IdForCert(const net::X509Certificate& cert) {
[email protected]53419052013-05-14 04:37:56251 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();
256
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);
263 }
264 SECKEY_DestroyPrivateKey(priv_key);
265
266 return pkcs11_id;
267}
268
[email protected]75d93a82013-05-06 19:51:56269void CertLoader::OnTpmIsEnabled(DBusMethodCallStatus call_status,
270 bool tpm_is_enabled) {
271 VLOG(1) << "OnTpmIsEnabled: " << tpm_is_enabled;
[email protected]7d3d0c02013-05-22 12:32:13272
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;
277
278 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56279}
280
281void CertLoader::OnPkcs11IsTpmTokenReady(DBusMethodCallStatus call_status,
282 bool is_tpm_token_ready) {
283 VLOG(1) << "OnPkcs11IsTpmTokenReady: " << is_tpm_token_ready;
[email protected]7d3d0c02013-05-22 12:32:13284
285 if (call_status == DBUS_METHOD_CALL_FAILURE || !is_tpm_token_ready) {
286 RetryTokenInitializationLater();
[email protected]75d93a82013-05-06 19:51:56287 return;
288 }
289
[email protected]7d3d0c02013-05-22 12:32:13290 tpm_token_state_ = TPM_TOKEN_READY;
291 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56292}
293
294void CertLoader::OnPkcs11GetTpmTokenInfo(DBusMethodCallStatus call_status,
295 const std::string& token_name,
296 const std::string& user_pin) {
297 VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name;
[email protected]7d3d0c02013-05-22 12:32:13298
299 if (call_status == DBUS_METHOD_CALL_FAILURE) {
300 RetryTokenInitializationLater();
[email protected]75d93a82013-05-06 19:51:56301 return;
302 }
[email protected]7d3d0c02013-05-22 12:32:13303
[email protected]75d93a82013-05-06 19:51:56304 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;
[email protected]7d3d0c02013-05-22 12:32:13310 tpm_token_state_ = TPM_TOKEN_INFO_RECEIVED;
[email protected]75d93a82013-05-06 19:51:56311
[email protected]7d3d0c02013-05-22 12:32:13312 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56313}
314
[email protected]60833392013-07-26 17:48:49315void CertLoader::OnTPMTokenInitialized(bool success) {
316 VLOG(1) << "OnTPMTokenInitialized: " << success;
317 if (!success) {
[email protected]7d3d0c02013-05-22 12:32:13318 RetryTokenInitializationLater();
[email protected]75d93a82013-05-06 19:51:56319 return;
320 }
[email protected]60833392013-07-26 17:48:49321 tpm_token_state_ = TPM_TOKEN_INITIALIZED;
[email protected]7d3d0c02013-05-22 12:32:13322 InitializeTokenAndLoadCertificates();
[email protected]75d93a82013-05-06 19:51:56323}
324
325void CertLoader::StartLoadCertificates() {
[email protected]72b3a7e2013-08-13 15:30:04326 DCHECK(!certificates_loaded_ && !certificates_update_running_);
327 net::CertDatabase::GetInstance()->AddObserver(this);
328 LoadCertificates();
329}
330
331void CertLoader::LoadCertificates() {
[email protected]60833392013-07-26 17:48:49332 CHECK(thread_checker_.CalledOnValidThread());
[email protected]72b3a7e2013-08-13 15:30:04333 VLOG(1) << "LoadCertificates: " << certificates_update_running_;
[email protected]7d3d0c02013-05-22 12:32:13334
335 if (certificates_update_running_) {
336 certificates_update_required_ = true;
337 return;
338 }
339
340 net::CertificateList* cert_list = new net::CertificateList;
341 certificates_update_running_ = true;
[email protected]8e80c2882013-05-23 10:43:40342 certificates_update_required_ = false;
[email protected]18e8d54f2013-08-06 17:15:48343
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)));
[email protected]75d93a82013-05-06 19:51:56353}
354
355void CertLoader::UpdateCertificates(net::CertificateList* cert_list) {
356 CHECK(thread_checker_.CalledOnValidThread());
[email protected]7d3d0c02013-05-22 12:32:13357 DCHECK(certificates_update_running_);
358 VLOG(1) << "UpdateCertificates: " << cert_list->size();
[email protected]75d93a82013-05-06 19:51:56359
[email protected]7d3d0c02013-05-22 12:32:13360 // Ignore any existing certificates.
[email protected]75d93a82013-05-06 19:51:56361 cert_list_.swap(*cert_list);
362
[email protected]166741182013-08-06 11:31:27363 bool initial_load = !certificates_loaded_;
[email protected]7d3d0c02013-05-22 12:32:13364 certificates_loaded_ = true;
[email protected]166741182013-08-06 11:31:27365 NotifyCertificatesLoaded(initial_load);
[email protected]75d93a82013-05-06 19:51:56366
[email protected]7d3d0c02013-05-22 12:32:13367 certificates_update_running_ = false;
368 if (certificates_update_required_)
[email protected]72b3a7e2013-08-13 15:30:04369 LoadCertificates();
[email protected]75d93a82013-05-06 19:51:56370}
371
372void CertLoader::NotifyCertificatesLoaded(bool initial_load) {
373 FOR_EACH_OBSERVER(Observer, observers_,
374 OnCertificatesLoaded(cert_list_, initial_load));
375}
376
377void CertLoader::OnCertTrustChanged(const net::X509Certificate* cert) {
378}
379
380void CertLoader::OnCertAdded(const net::X509Certificate* cert) {
[email protected]7d3d0c02013-05-22 12:32:13381 VLOG(1) << "OnCertAdded";
[email protected]72b3a7e2013-08-13 15:30:04382 LoadCertificates();
[email protected]75d93a82013-05-06 19:51:56383}
384
385void CertLoader::OnCertRemoved(const net::X509Certificate* cert) {
[email protected]7d3d0c02013-05-22 12:32:13386 VLOG(1) << "OnCertRemoved";
[email protected]72b3a7e2013-08-13 15:30:04387 LoadCertificates();
[email protected]75d93a82013-05-06 19:51:56388}
389
390void CertLoader::LoggedInStateChanged(LoginState::LoggedInState state) {
391 VLOG(1) << "LoggedInStateChanged: " << state;
[email protected]60833392013-07-26 17:48:49392 MaybeRequestCertificates();
[email protected]75d93a82013-05-06 19:51:56393}
394
395} // namespace chromeos