OLD | NEW |
| (Empty) |
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 "chrome/browser/chromeos/ownership/owner_settings_service.h" | |
6 | |
7 #include <string> | |
8 | |
9 #include "base/bind.h" | |
10 #include "base/bind_helpers.h" | |
11 #include "base/command_line.h" | |
12 #include "base/prefs/pref_service.h" | |
13 #include "chrome/browser/chrome_notification_types.h" | |
14 #include "chrome/browser/chromeos/profiles/profile_helper.h" | |
15 #include "chrome/browser/chromeos/settings/cros_settings.h" | |
16 #include "chrome/browser/chromeos/settings/session_manager_operation.h" | |
17 #include "chrome/browser/profiles/profile.h" | |
18 #include "chromeos/dbus/dbus_thread_manager.h" | |
19 #include "components/policy/core/common/cloud/cloud_policy_constants.h" | |
20 #include "content/public/browser/browser_thread.h" | |
21 #include "content/public/browser/notification_details.h" | |
22 #include "content/public/browser/notification_service.h" | |
23 #include "content/public/browser/notification_source.h" | |
24 #include "content/public/common/content_switches.h" | |
25 #include "crypto/nss_util.h" | |
26 #include "crypto/nss_util_internal.h" | |
27 #include "crypto/rsa_private_key.h" | |
28 #include "crypto/scoped_nss_types.h" | |
29 #include "crypto/signature_creator.h" | |
30 | |
31 namespace em = enterprise_management; | |
32 | |
33 using content::BrowserThread; | |
34 using ownership::OwnerKeyUtil; | |
35 using ownership::PrivateKey; | |
36 using ownership::PublicKey; | |
37 | |
38 namespace chromeos { | |
39 | |
40 namespace { | |
41 | |
42 DeviceSettingsService* g_device_settings_service_for_testing = NULL; | |
43 | |
44 bool IsOwnerInTests(const std::string& user_id) { | |
45 if (user_id.empty() || | |
46 !CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestType) || | |
47 !CrosSettings::IsInitialized()) { | |
48 return false; | |
49 } | |
50 const base::Value* value = CrosSettings::Get()->GetPref(kDeviceOwner); | |
51 if (!value || value->GetType() != base::Value::TYPE_STRING) | |
52 return false; | |
53 return static_cast<const base::StringValue*>(value)->GetString() == user_id; | |
54 } | |
55 | |
56 // Assembles PolicyData based on |settings|, |policy_data| and | |
57 // |user_id|. | |
58 scoped_ptr<em::PolicyData> AssemblePolicy( | |
59 const std::string& user_id, | |
60 const em::PolicyData* policy_data, | |
61 const em::ChromeDeviceSettingsProto* settings) { | |
62 scoped_ptr<em::PolicyData> policy(new em::PolicyData()); | |
63 if (policy_data) { | |
64 // Preserve management settings. | |
65 if (policy_data->has_management_mode()) | |
66 policy->set_management_mode(policy_data->management_mode()); | |
67 if (policy_data->has_request_token()) | |
68 policy->set_request_token(policy_data->request_token()); | |
69 if (policy_data->has_device_id()) | |
70 policy->set_device_id(policy_data->device_id()); | |
71 } else { | |
72 // If there's no previous policy data, this is the first time the device | |
73 // setting is set. We set the management mode to NOT_MANAGED initially. | |
74 policy->set_management_mode(em::PolicyData::NOT_MANAGED); | |
75 } | |
76 policy->set_policy_type(policy::dm_protocol::kChromeDevicePolicyType); | |
77 policy->set_timestamp( | |
78 (base::Time::Now() - base::Time::UnixEpoch()).InMilliseconds()); | |
79 policy->set_username(user_id); | |
80 if (!settings->SerializeToString(policy->mutable_policy_value())) | |
81 return scoped_ptr<em::PolicyData>(); | |
82 | |
83 return policy.Pass(); | |
84 } | |
85 | |
86 std::string AssembleAndSignPolicy(scoped_ptr<em::PolicyData> policy, | |
87 crypto::RSAPrivateKey* private_key) { | |
88 // Assemble the policy. | |
89 em::PolicyFetchResponse policy_response; | |
90 if (!policy->SerializeToString(policy_response.mutable_policy_data())) { | |
91 LOG(ERROR) << "Failed to encode policy payload."; | |
92 return std::string(); | |
93 } | |
94 | |
95 // Generate the signature. | |
96 scoped_ptr<crypto::SignatureCreator> signature_creator( | |
97 crypto::SignatureCreator::Create(private_key)); | |
98 signature_creator->Update( | |
99 reinterpret_cast<const uint8*>(policy_response.policy_data().c_str()), | |
100 policy_response.policy_data().size()); | |
101 std::vector<uint8> signature_bytes; | |
102 std::string policy_blob; | |
103 if (!signature_creator->Final(&signature_bytes)) { | |
104 LOG(ERROR) << "Failed to create policy signature."; | |
105 return std::string(); | |
106 } | |
107 | |
108 policy_response.mutable_policy_data_signature()->assign( | |
109 reinterpret_cast<const char*>(vector_as_array(&signature_bytes)), | |
110 signature_bytes.size()); | |
111 return policy_response.SerializeAsString(); | |
112 } | |
113 | |
114 void LoadPrivateKeyByPublicKey( | |
115 const scoped_refptr<OwnerKeyUtil>& owner_key_util, | |
116 scoped_refptr<PublicKey> public_key, | |
117 const std::string& username_hash, | |
118 const base::Callback<void(scoped_refptr<PublicKey> public_key, | |
119 scoped_refptr<PrivateKey> private_key)>& | |
120 callback) { | |
121 crypto::EnsureNSSInit(); | |
122 crypto::ScopedPK11Slot slot = | |
123 crypto::GetPublicSlotForChromeOSUser(username_hash); | |
124 scoped_refptr<PrivateKey> private_key(new PrivateKey( | |
125 owner_key_util->FindPrivateKeyInSlot(public_key->data(), slot.get()))); | |
126 BrowserThread::PostTask(BrowserThread::UI, | |
127 FROM_HERE, | |
128 base::Bind(callback, public_key, private_key)); | |
129 } | |
130 | |
131 void LoadPrivateKey(const scoped_refptr<OwnerKeyUtil>& owner_key_util, | |
132 const std::string username_hash, | |
133 const base::Callback<void( | |
134 scoped_refptr<PublicKey> public_key, | |
135 scoped_refptr<PrivateKey> private_key)>& callback) { | |
136 std::vector<uint8> public_key_data; | |
137 scoped_refptr<PublicKey> public_key; | |
138 if (!owner_key_util->ImportPublicKey(&public_key_data)) { | |
139 scoped_refptr<PrivateKey> private_key; | |
140 BrowserThread::PostTask(BrowserThread::UI, | |
141 FROM_HERE, | |
142 base::Bind(callback, public_key, private_key)); | |
143 return; | |
144 } | |
145 public_key = new PublicKey(); | |
146 public_key->data().swap(public_key_data); | |
147 bool rv = BrowserThread::PostTask(BrowserThread::IO, | |
148 FROM_HERE, | |
149 base::Bind(&LoadPrivateKeyByPublicKey, | |
150 owner_key_util, | |
151 public_key, | |
152 username_hash, | |
153 callback)); | |
154 if (!rv) { | |
155 // IO thread doesn't exists in unit tests, but it's safe to use NSS from | |
156 // BlockingPool in unit tests. | |
157 LoadPrivateKeyByPublicKey( | |
158 owner_key_util, public_key, username_hash, callback); | |
159 } | |
160 } | |
161 | |
162 bool DoesPrivateKeyExistAsyncHelper( | |
163 const scoped_refptr<OwnerKeyUtil>& owner_key_util) { | |
164 std::vector<uint8> public_key; | |
165 if (!owner_key_util->ImportPublicKey(&public_key)) | |
166 return false; | |
167 scoped_ptr<crypto::RSAPrivateKey> key( | |
168 crypto::RSAPrivateKey::FindFromPublicKeyInfo(public_key)); | |
169 bool is_owner = key.get() != NULL; | |
170 return is_owner; | |
171 } | |
172 | |
173 // Checks whether NSS slots with private key are mounted or | |
174 // not. Responds via |callback|. | |
175 void DoesPrivateKeyExistAsync( | |
176 const scoped_refptr<OwnerKeyUtil>& owner_key_util, | |
177 const OwnerSettingsService::IsOwnerCallback& callback) { | |
178 if (!owner_key_util) { | |
179 callback.Run(false); | |
180 return; | |
181 } | |
182 scoped_refptr<base::TaskRunner> task_runner = | |
183 content::BrowserThread::GetBlockingPool() | |
184 ->GetTaskRunnerWithShutdownBehavior( | |
185 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN); | |
186 base::PostTaskAndReplyWithResult( | |
187 task_runner.get(), | |
188 FROM_HERE, | |
189 base::Bind(&DoesPrivateKeyExistAsyncHelper, owner_key_util), | |
190 callback); | |
191 } | |
192 | |
193 // Returns the current management mode. | |
194 em::PolicyData::ManagementMode GetManagementMode( | |
195 DeviceSettingsService* service) { | |
196 if (!service) { | |
197 LOG(ERROR) << "DeviceSettingsService is not initialized"; | |
198 return em::PolicyData::NOT_MANAGED; | |
199 } | |
200 | |
201 const em::PolicyData* policy_data = service->policy_data(); | |
202 if (policy_data && policy_data->has_management_mode()) | |
203 return policy_data->management_mode(); | |
204 return em::PolicyData::NOT_MANAGED; | |
205 } | |
206 | |
207 // Returns true if it is okay to transfer from the current mode to the new | |
208 // mode. This function should be called in SetManagementMode(). | |
209 bool CheckManagementModeTransition(em::PolicyData::ManagementMode current_mode, | |
210 em::PolicyData::ManagementMode new_mode) { | |
211 // Mode is not changed. | |
212 if (current_mode == new_mode) | |
213 return true; | |
214 | |
215 switch (current_mode) { | |
216 case em::PolicyData::NOT_MANAGED: | |
217 // For consumer management enrollment. | |
218 return new_mode == em::PolicyData::CONSUMER_MANAGED; | |
219 | |
220 case em::PolicyData::ENTERPRISE_MANAGED: | |
221 // Management mode cannot be set when it is currently ENTERPRISE_MANAGED. | |
222 return false; | |
223 | |
224 case em::PolicyData::CONSUMER_MANAGED: | |
225 // For consumer management unenrollment. | |
226 return new_mode == em::PolicyData::NOT_MANAGED; | |
227 } | |
228 | |
229 NOTREACHED(); | |
230 return false; | |
231 } | |
232 | |
233 } // namespace | |
234 | |
235 OwnerSettingsService::OwnerSettingsService( | |
236 Profile* profile, | |
237 const scoped_refptr<OwnerKeyUtil>& owner_key_util) | |
238 : profile_(profile), | |
239 owner_key_util_(owner_key_util), | |
240 waiting_for_profile_creation_(true), | |
241 waiting_for_tpm_token_(true), | |
242 weak_factory_(this) { | |
243 if (TPMTokenLoader::IsInitialized()) { | |
244 waiting_for_tpm_token_ = !TPMTokenLoader::Get()->IsTPMTokenReady(); | |
245 TPMTokenLoader::Get()->AddObserver(this); | |
246 } | |
247 | |
248 if (DBusThreadManager::IsInitialized() && | |
249 DBusThreadManager::Get()->GetSessionManagerClient()) { | |
250 DBusThreadManager::Get()->GetSessionManagerClient()->AddObserver(this); | |
251 } | |
252 | |
253 registrar_.Add(this, | |
254 chrome::NOTIFICATION_PROFILE_CREATED, | |
255 content::Source<Profile>(profile_)); | |
256 } | |
257 | |
258 OwnerSettingsService::~OwnerSettingsService() { | |
259 DCHECK(thread_checker_.CalledOnValidThread()); | |
260 if (TPMTokenLoader::IsInitialized()) | |
261 TPMTokenLoader::Get()->RemoveObserver(this); | |
262 | |
263 if (DBusThreadManager::IsInitialized() && | |
264 DBusThreadManager::Get()->GetSessionManagerClient()) { | |
265 DBusThreadManager::Get()->GetSessionManagerClient()->RemoveObserver(this); | |
266 } | |
267 } | |
268 | |
269 bool OwnerSettingsService::IsOwner() { | |
270 DCHECK(thread_checker_.CalledOnValidThread()); | |
271 return private_key_ && private_key_->key(); | |
272 } | |
273 | |
274 void OwnerSettingsService::IsOwnerAsync(const IsOwnerCallback& callback) { | |
275 DCHECK(thread_checker_.CalledOnValidThread()); | |
276 if (private_key_) { | |
277 base::MessageLoop::current()->PostTask(FROM_HERE, | |
278 base::Bind(callback, IsOwner())); | |
279 } else { | |
280 pending_is_owner_callbacks_.push_back(callback); | |
281 } | |
282 } | |
283 | |
284 bool OwnerSettingsService::AssembleAndSignPolicyAsync( | |
285 scoped_ptr<em::PolicyData> policy, | |
286 const AssembleAndSignPolicyCallback& callback) { | |
287 DCHECK(thread_checker_.CalledOnValidThread()); | |
288 if (!IsOwner()) | |
289 return false; | |
290 base::PostTaskAndReplyWithResult( | |
291 BrowserThread::GetBlockingPool(), | |
292 FROM_HERE, | |
293 base::Bind( | |
294 &AssembleAndSignPolicy, base::Passed(&policy), private_key_->key()), | |
295 callback); | |
296 return true; | |
297 } | |
298 | |
299 void OwnerSettingsService::SignAndStoreAsync( | |
300 scoped_ptr<em::ChromeDeviceSettingsProto> settings, | |
301 const base::Closure& callback) { | |
302 DCHECK(thread_checker_.CalledOnValidThread()); | |
303 scoped_ptr<em::PolicyData> policy = AssemblePolicy( | |
304 user_id_, GetDeviceSettingsService()->policy_data(), settings.get()); | |
305 if (!policy) { | |
306 HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback); | |
307 return; | |
308 } | |
309 | |
310 EnqueueSignAndStore(policy.Pass(), callback); | |
311 } | |
312 | |
313 void OwnerSettingsService::SetManagementSettingsAsync( | |
314 em::PolicyData::ManagementMode management_mode, | |
315 const std::string& request_token, | |
316 const std::string& device_id, | |
317 const base::Closure& callback) { | |
318 em::PolicyData::ManagementMode current_mode = | |
319 GetManagementMode(GetDeviceSettingsService()); | |
320 if (!CheckManagementModeTransition(current_mode, management_mode)) { | |
321 LOG(ERROR) << "Invalid management mode transition: current mode = " | |
322 << current_mode << ", new mode = " << management_mode; | |
323 HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback); | |
324 return; | |
325 } | |
326 | |
327 DeviceSettingsService* service = GetDeviceSettingsService(); | |
328 scoped_ptr<em::PolicyData> policy = AssemblePolicy( | |
329 user_id_, service->policy_data(), service->device_settings()); | |
330 if (!policy) { | |
331 HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback); | |
332 return; | |
333 } | |
334 | |
335 policy->set_management_mode(management_mode); | |
336 policy->set_request_token(request_token); | |
337 policy->set_device_id(device_id); | |
338 | |
339 EnqueueSignAndStore(policy.Pass(), callback); | |
340 } | |
341 | |
342 void OwnerSettingsService::Observe( | |
343 int type, | |
344 const content::NotificationSource& source, | |
345 const content::NotificationDetails& details) { | |
346 DCHECK(thread_checker_.CalledOnValidThread()); | |
347 if (type != chrome::NOTIFICATION_PROFILE_CREATED) { | |
348 NOTREACHED(); | |
349 return; | |
350 } | |
351 | |
352 Profile* profile = content::Source<Profile>(source).ptr(); | |
353 if (profile != profile_) { | |
354 NOTREACHED(); | |
355 return; | |
356 } | |
357 | |
358 waiting_for_profile_creation_ = false; | |
359 ReloadPrivateKey(); | |
360 } | |
361 | |
362 void OwnerSettingsService::OnTPMTokenReady() { | |
363 DCHECK(thread_checker_.CalledOnValidThread()); | |
364 waiting_for_tpm_token_ = false; | |
365 | |
366 // TPMTokenLoader initializes the TPM and NSS database which is necessary to | |
367 // determine ownership. Force a reload once we know these are initialized. | |
368 ReloadPrivateKey(); | |
369 } | |
370 | |
371 void OwnerSettingsService::OwnerKeySet(bool success) { | |
372 DCHECK(thread_checker_.CalledOnValidThread()); | |
373 if (success) | |
374 ReloadPrivateKey(); | |
375 } | |
376 | |
377 // static | |
378 void OwnerSettingsService::IsOwnerForSafeModeAsync( | |
379 const std::string& user_id, | |
380 const std::string& user_hash, | |
381 const scoped_refptr<OwnerKeyUtil>& owner_key_util, | |
382 const IsOwnerCallback& callback) { | |
383 CHECK(chromeos::LoginState::Get()->IsInSafeMode()); | |
384 | |
385 // Make sure NSS is initialized and NSS DB is loaded for the user before | |
386 // searching for the owner key. | |
387 BrowserThread::PostTaskAndReply( | |
388 BrowserThread::IO, | |
389 FROM_HERE, | |
390 base::Bind(base::IgnoreResult(&crypto::InitializeNSSForChromeOSUser), | |
391 user_id, | |
392 user_hash, | |
393 ProfileHelper::GetProfilePathByUserIdHash(user_hash)), | |
394 base::Bind(&DoesPrivateKeyExistAsync, owner_key_util, callback)); | |
395 } | |
396 | |
397 // static | |
398 void OwnerSettingsService::SetDeviceSettingsServiceForTesting( | |
399 DeviceSettingsService* device_settings_service) { | |
400 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
401 g_device_settings_service_for_testing = device_settings_service; | |
402 } | |
403 | |
404 void OwnerSettingsService::ReloadPrivateKey() { | |
405 DCHECK(thread_checker_.CalledOnValidThread()); | |
406 if (waiting_for_profile_creation_ || waiting_for_tpm_token_) | |
407 return; | |
408 scoped_refptr<base::TaskRunner> task_runner = | |
409 content::BrowserThread::GetBlockingPool() | |
410 ->GetTaskRunnerWithShutdownBehavior( | |
411 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN); | |
412 task_runner->PostTask( | |
413 FROM_HERE, | |
414 base::Bind(&LoadPrivateKey, | |
415 GetOwnerKeyUtil(), | |
416 ProfileHelper::GetUserIdHashFromProfile(profile_), | |
417 base::Bind(&OwnerSettingsService::OnPrivateKeyLoaded, | |
418 weak_factory_.GetWeakPtr()))); | |
419 } | |
420 | |
421 void OwnerSettingsService::OnPrivateKeyLoaded( | |
422 scoped_refptr<PublicKey> public_key, | |
423 scoped_refptr<PrivateKey> private_key) { | |
424 DCHECK(thread_checker_.CalledOnValidThread()); | |
425 public_key_ = public_key; | |
426 private_key_ = private_key; | |
427 | |
428 user_id_ = profile_->GetProfileName(); | |
429 const bool is_owner = IsOwner() || IsOwnerInTests(user_id_); | |
430 if (is_owner && GetDeviceSettingsService()) | |
431 GetDeviceSettingsService()->InitOwner(user_id_, weak_factory_.GetWeakPtr()); | |
432 | |
433 std::vector<IsOwnerCallback> is_owner_callbacks; | |
434 is_owner_callbacks.swap(pending_is_owner_callbacks_); | |
435 for (std::vector<IsOwnerCallback>::iterator it(is_owner_callbacks.begin()); | |
436 it != is_owner_callbacks.end(); | |
437 ++it) { | |
438 it->Run(is_owner); | |
439 } | |
440 } | |
441 | |
442 void OwnerSettingsService::EnqueueSignAndStore( | |
443 scoped_ptr<em::PolicyData> policy, | |
444 const base::Closure& callback) { | |
445 SignAndStoreSettingsOperation* operation = new SignAndStoreSettingsOperation( | |
446 base::Bind(&OwnerSettingsService::HandleCompletedOperation, | |
447 weak_factory_.GetWeakPtr(), | |
448 callback), | |
449 policy.Pass()); | |
450 operation->set_delegate(weak_factory_.GetWeakPtr()); | |
451 pending_operations_.push_back(operation); | |
452 if (pending_operations_.front() == operation) | |
453 StartNextOperation(); | |
454 } | |
455 | |
456 void OwnerSettingsService::StartNextOperation() { | |
457 DeviceSettingsService* service = GetDeviceSettingsService(); | |
458 if (!pending_operations_.empty() && service && | |
459 service->session_manager_client()) { | |
460 pending_operations_.front()->Start( | |
461 service->session_manager_client(), GetOwnerKeyUtil(), public_key_); | |
462 } | |
463 } | |
464 | |
465 void OwnerSettingsService::HandleCompletedOperation( | |
466 const base::Closure& callback, | |
467 SessionManagerOperation* operation, | |
468 DeviceSettingsService::Status status) { | |
469 DCHECK_EQ(operation, pending_operations_.front()); | |
470 | |
471 DeviceSettingsService* service = GetDeviceSettingsService(); | |
472 if (status == DeviceSettingsService::STORE_SUCCESS) { | |
473 service->set_policy_data(operation->policy_data().Pass()); | |
474 service->set_device_settings(operation->device_settings().Pass()); | |
475 } | |
476 | |
477 if ((operation->public_key() && !public_key_) || | |
478 (operation->public_key() && public_key_ && | |
479 operation->public_key()->data() != public_key_->data())) { | |
480 // Public part changed so we need to reload private part too. | |
481 ReloadPrivateKey(); | |
482 content::NotificationService::current()->Notify( | |
483 chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED, | |
484 content::Source<OwnerSettingsService>(this), | |
485 content::NotificationService::NoDetails()); | |
486 } | |
487 service->OnSignAndStoreOperationCompleted(status); | |
488 if (!callback.is_null()) | |
489 callback.Run(); | |
490 | |
491 pending_operations_.pop_front(); | |
492 delete operation; | |
493 StartNextOperation(); | |
494 } | |
495 | |
496 void OwnerSettingsService::HandleError(DeviceSettingsService::Status status, | |
497 const base::Closure& callback) { | |
498 LOG(ERROR) << "Session manager operation failed: " << status; | |
499 GetDeviceSettingsService()->OnSignAndStoreOperationCompleted(status); | |
500 if (!callback.is_null()) | |
501 callback.Run(); | |
502 } | |
503 | |
504 scoped_refptr<OwnerKeyUtil> OwnerSettingsService::GetOwnerKeyUtil() { | |
505 DCHECK(thread_checker_.CalledOnValidThread()); | |
506 return owner_key_util_; | |
507 } | |
508 | |
509 DeviceSettingsService* OwnerSettingsService::GetDeviceSettingsService() { | |
510 DCHECK(thread_checker_.CalledOnValidThread()); | |
511 if (g_device_settings_service_for_testing) | |
512 return g_device_settings_service_for_testing; | |
513 if (DeviceSettingsService::IsInitialized()) | |
514 return DeviceSettingsService::Get(); | |
515 return NULL; | |
516 } | |
517 | |
518 } // namespace chromeos | |
OLD | NEW |