Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / chromeos / tpm_token_loader.cc
1 // Copyright 2014 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
5 #include "chromeos/tpm_token_loader.h"
6
7 #include <algorithm>
8
9 #include "base/bind.h"
10 #include "base/location.h"
11 #include "base/message_loop/message_loop_proxy.h"
12 #include "base/sequenced_task_runner.h"
13 #include "base/sys_info.h"
14 #include "base/task_runner_util.h"
15 #include "chromeos/dbus/cryptohome_client.h"
16 #include "chromeos/dbus/dbus_thread_manager.h"
17 #include "crypto/nss_util.h"
18
19 namespace chromeos {
20
21 namespace {
22
23 const int64 kInitialRequestDelayMs = 100;
24 const int64 kMaxRequestDelayMs = 300000;  // 5 minutes
25
26 // Calculates the delay before running next attempt to initiatialize the TPM
27 // token, if |last_delay| was the last or initial delay.
28 base::TimeDelta GetNextRequestDelayMs(base::TimeDelta last_delay) {
29   // This implements an exponential backoff, as we don't know in which order of
30   // magnitude the TPM token changes it's state.
31   base::TimeDelta next_delay = last_delay * 2;
32
33   // Cap the delay to prevent an overflow. This threshold is arbitrarily chosen.
34   const base::TimeDelta max_delay =
35       base::TimeDelta::FromMilliseconds(kMaxRequestDelayMs);
36   if (next_delay > max_delay)
37     next_delay = max_delay;
38   return next_delay;
39 }
40
41 void CallOpenPersistentNSSDB() {
42   // Called from crypto_task_runner_.
43   VLOG(1) << "CallOpenPersistentNSSDB";
44
45   // Ensure we've opened the user's key/certificate database.
46   if (base::SysInfo::IsRunningOnChromeOS())
47     crypto::OpenPersistentNSSDB();
48   crypto::EnableTPMTokenForNSS();
49 }
50
51 }  // namespace
52
53 static TPMTokenLoader* g_tpm_token_loader = NULL;
54
55 // static
56 void TPMTokenLoader::Initialize() {
57   CHECK(!g_tpm_token_loader);
58   g_tpm_token_loader = new TPMTokenLoader();
59 }
60
61 // static
62 void TPMTokenLoader::Shutdown() {
63   CHECK(g_tpm_token_loader);
64   delete g_tpm_token_loader;
65   g_tpm_token_loader = NULL;
66 }
67
68 // static
69 TPMTokenLoader* TPMTokenLoader::Get() {
70   CHECK(g_tpm_token_loader)
71       << "TPMTokenLoader::Get() called before Initialize()";
72   return g_tpm_token_loader;
73 }
74
75 // static
76 bool TPMTokenLoader::IsInitialized() {
77   return g_tpm_token_loader;
78 }
79
80 TPMTokenLoader::TPMTokenLoader()
81     : initialize_tpm_for_test_(false),
82       tpm_token_state_(TPM_STATE_UNKNOWN),
83       tpm_request_delay_(
84           base::TimeDelta::FromMilliseconds(kInitialRequestDelayMs)),
85       tpm_token_slot_id_(-1),
86       weak_factory_(this) {
87   if (LoginState::IsInitialized())
88     LoginState::Get()->AddObserver(this);
89 }
90
91 void TPMTokenLoader::InitializeTPMForTest() {
92   initialize_tpm_for_test_ = true;
93 }
94
95 void TPMTokenLoader::SetCryptoTaskRunner(
96     const scoped_refptr<base::SequencedTaskRunner>& crypto_task_runner) {
97   crypto_task_runner_ = crypto_task_runner;
98   MaybeStartTokenInitialization();
99 }
100
101 TPMTokenLoader::~TPMTokenLoader() {
102   if (LoginState::IsInitialized())
103     LoginState::Get()->RemoveObserver(this);
104 }
105
106 void TPMTokenLoader::AddObserver(TPMTokenLoader::Observer* observer) {
107   observers_.AddObserver(observer);
108 }
109
110 void TPMTokenLoader::RemoveObserver(TPMTokenLoader::Observer* observer) {
111   observers_.RemoveObserver(observer);
112 }
113
114 bool TPMTokenLoader::IsTPMTokenReady() const {
115   return tpm_token_state_ == TPM_DISABLED ||
116          tpm_token_state_ == TPM_TOKEN_INITIALIZED;
117 }
118
119 void TPMTokenLoader::MaybeStartTokenInitialization() {
120   CHECK(thread_checker_.CalledOnValidThread());
121
122   // This is the entry point to the TPM token initialization process,
123   // which we should do at most once.
124   if (tpm_token_state_ != TPM_STATE_UNKNOWN || !crypto_task_runner_.get())
125     return;
126
127   if (!LoginState::IsInitialized())
128     return;
129
130   bool request_certificates = LoginState::Get()->IsUserLoggedIn() ||
131       LoginState::Get()->IsInSafeMode();
132
133   VLOG(1) << "RequestCertificates: " << request_certificates;
134   if (!request_certificates)
135     return;
136
137   if (!initialize_tpm_for_test_ && !base::SysInfo::IsRunningOnChromeOS())
138     tpm_token_state_ = TPM_DISABLED;
139
140   // Treat TPM as disabled for guest users since they do not store certs.
141   if (LoginState::Get()->IsGuestUser())
142     tpm_token_state_ = TPM_DISABLED;
143
144   ContinueTokenInitialization();
145
146   DCHECK_NE(tpm_token_state_, TPM_STATE_UNKNOWN);
147 }
148
149 void TPMTokenLoader::ContinueTokenInitialization() {
150   CHECK(thread_checker_.CalledOnValidThread());
151   VLOG(1) << "ContinueTokenInitialization: " << tpm_token_state_;
152
153   switch (tpm_token_state_) {
154     case TPM_STATE_UNKNOWN: {
155       crypto_task_runner_->PostTaskAndReply(
156           FROM_HERE,
157           base::Bind(&CallOpenPersistentNSSDB),
158           base::Bind(&TPMTokenLoader::OnPersistentNSSDBOpened,
159                      weak_factory_.GetWeakPtr()));
160       tpm_token_state_ = TPM_INITIALIZATION_STARTED;
161       return;
162     }
163     case TPM_INITIALIZATION_STARTED: {
164       NOTREACHED();
165       return;
166     }
167     case TPM_DB_OPENED: {
168       DBusThreadManager::Get()->GetCryptohomeClient()->TpmIsEnabled(
169           base::Bind(&TPMTokenLoader::OnTpmIsEnabled,
170                      weak_factory_.GetWeakPtr()));
171       return;
172     }
173     case TPM_DISABLED: {
174       // TPM is disabled, so proceed with empty tpm token name.
175       NotifyTPMTokenReady();
176       return;
177     }
178     case TPM_ENABLED: {
179       DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11IsTpmTokenReady(
180           base::Bind(&TPMTokenLoader::OnPkcs11IsTpmTokenReady,
181                      weak_factory_.GetWeakPtr()));
182       return;
183     }
184     case TPM_TOKEN_READY: {
185       // Retrieve token_name_ and user_pin_ here since they will never change
186       // and CryptohomeClient calls are not thread safe.
187       DBusThreadManager::Get()->GetCryptohomeClient()->Pkcs11GetTpmTokenInfo(
188           base::Bind(&TPMTokenLoader::OnPkcs11GetTpmTokenInfo,
189                      weak_factory_.GetWeakPtr()));
190       return;
191     }
192     case TPM_TOKEN_INFO_RECEIVED: {
193       base::PostTaskAndReplyWithResult(
194           crypto_task_runner_.get(),
195           FROM_HERE,
196           base::Bind(&crypto::InitializeTPMToken, tpm_token_slot_id_),
197           base::Bind(&TPMTokenLoader::OnTPMTokenInitialized,
198                      weak_factory_.GetWeakPtr()));
199       return;
200     }
201     case TPM_TOKEN_INITIALIZED: {
202       NotifyTPMTokenReady();
203       return;
204     }
205   }
206 }
207
208 void TPMTokenLoader::RetryTokenInitializationLater() {
209   CHECK(thread_checker_.CalledOnValidThread());
210   LOG(WARNING) << "Retry token initialization later.";
211   base::MessageLoopProxy::current()->PostDelayedTask(
212       FROM_HERE,
213       base::Bind(&TPMTokenLoader::ContinueTokenInitialization,
214                  weak_factory_.GetWeakPtr()),
215       tpm_request_delay_);
216   tpm_request_delay_ = GetNextRequestDelayMs(tpm_request_delay_);
217 }
218
219 void TPMTokenLoader::OnPersistentNSSDBOpened() {
220   VLOG(1) << "PersistentNSSDBOpened";
221   tpm_token_state_ = TPM_DB_OPENED;
222   ContinueTokenInitialization();
223 }
224
225 void TPMTokenLoader::OnTpmIsEnabled(DBusMethodCallStatus call_status,
226                                     bool tpm_is_enabled) {
227   VLOG(1) << "OnTpmIsEnabled: " << tpm_is_enabled;
228
229   if (call_status == DBUS_METHOD_CALL_SUCCESS && tpm_is_enabled)
230     tpm_token_state_ = TPM_ENABLED;
231   else
232     tpm_token_state_ = TPM_DISABLED;
233
234   ContinueTokenInitialization();
235 }
236
237 void TPMTokenLoader::OnPkcs11IsTpmTokenReady(DBusMethodCallStatus call_status,
238                                          bool is_tpm_token_ready) {
239   VLOG(1) << "OnPkcs11IsTpmTokenReady: " << is_tpm_token_ready;
240
241   if (call_status == DBUS_METHOD_CALL_FAILURE || !is_tpm_token_ready) {
242     RetryTokenInitializationLater();
243     return;
244   }
245
246   tpm_token_state_ = TPM_TOKEN_READY;
247   ContinueTokenInitialization();
248 }
249
250 void TPMTokenLoader::OnPkcs11GetTpmTokenInfo(DBusMethodCallStatus call_status,
251                                              const std::string& token_name,
252                                              const std::string& user_pin,
253                                              int token_slot_id) {
254   VLOG(1) << "OnPkcs11GetTpmTokenInfo: " << token_name;
255
256   if (call_status == DBUS_METHOD_CALL_FAILURE) {
257     RetryTokenInitializationLater();
258     return;
259   }
260
261   tpm_token_name_ = token_name;
262   tpm_token_slot_id_ = token_slot_id;
263   tpm_user_pin_ = user_pin;
264   tpm_token_state_ = TPM_TOKEN_INFO_RECEIVED;
265
266   ContinueTokenInitialization();
267 }
268
269 void TPMTokenLoader::OnTPMTokenInitialized(bool success) {
270   VLOG(1) << "OnTPMTokenInitialized: " << success;
271   if (!success) {
272     RetryTokenInitializationLater();
273     return;
274   }
275   tpm_token_state_ = TPM_TOKEN_INITIALIZED;
276   ContinueTokenInitialization();
277 }
278
279 void TPMTokenLoader::NotifyTPMTokenReady() {
280   FOR_EACH_OBSERVER(Observer, observers_,
281       OnTPMTokenReady(tpm_user_pin_, tpm_token_name_, tpm_token_slot_id_));
282 }
283
284 void TPMTokenLoader::LoggedInStateChanged() {
285   VLOG(1) << "LoggedInStateChanged";
286   MaybeStartTokenInitialization();
287 }
288
289 }  // namespace chromeos