summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/ownership/owner_settings_service.cc
blob: e2b380559e3f5d2e5300bba1f6c2db3a39756ce7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/ownership/owner_settings_service.h"

#include <string>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/ownership/owner_settings_service_factory.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/session_manager_operation.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/chromeos_paths.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/ownership/owner_key_util_impl.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/common/content_switches.h"
#include "crypto/nss_util.h"
#include "crypto/nss_util_internal.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_creator.h"

namespace em = enterprise_management;

using content::BrowserThread;
using ownership::OwnerKeyUtil;
using ownership::PrivateKey;
using ownership::PublicKey;

namespace chromeos {

namespace {

scoped_refptr<OwnerKeyUtil>* g_owner_key_util_for_testing = NULL;
DeviceSettingsService* g_device_settings_service_for_testing = NULL;

bool IsOwnerInTests(const std::string& user_id) {
  if (user_id.empty() ||
      !CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestType) ||
      !CrosSettings::IsInitialized()) {
    return false;
  }
  const base::Value* value = CrosSettings::Get()->GetPref(kDeviceOwner);
  if (!value || value->GetType() != base::Value::TYPE_STRING)
    return false;
  return static_cast<const base::StringValue*>(value)->GetString() == user_id;
}

// Assembles PolicyData based on |settings|, |policy_data| and
// |user_id|.
scoped_ptr<em::PolicyData> AssemblePolicy(
    const std::string& user_id,
    const em::PolicyData* policy_data,
    const em::ChromeDeviceSettingsProto* settings) {
  scoped_ptr<em::PolicyData> policy(new em::PolicyData());
  if (policy_data) {
    // Preserve management settings.
    if (policy_data->has_management_mode())
      policy->set_management_mode(policy_data->management_mode());
    if (policy_data->has_request_token())
      policy->set_request_token(policy_data->request_token());
    if (policy_data->has_device_id())
      policy->set_device_id(policy_data->device_id());
  } else {
    // If there's no previous policy data, this is the first time the device
    // setting is set. We set the management mode to NOT_MANAGED initially.
    policy->set_management_mode(em::PolicyData::NOT_MANAGED);
  }
  policy->set_policy_type(policy::dm_protocol::kChromeDevicePolicyType);
  policy->set_timestamp(
      (base::Time::Now() - base::Time::UnixEpoch()).InMilliseconds());
  policy->set_username(user_id);
  if (!settings->SerializeToString(policy->mutable_policy_value()))
    return scoped_ptr<em::PolicyData>();

  return policy.Pass();
}

std::string AssembleAndSignPolicy(scoped_ptr<em::PolicyData> policy,
                                  crypto::RSAPrivateKey* private_key) {
  // Assemble the policy.
  em::PolicyFetchResponse policy_response;
  if (!policy->SerializeToString(policy_response.mutable_policy_data())) {
    LOG(ERROR) << "Failed to encode policy payload.";
    return std::string();
  }

  // Generate the signature.
  scoped_ptr<crypto::SignatureCreator> signature_creator(
      crypto::SignatureCreator::Create(private_key));
  signature_creator->Update(
      reinterpret_cast<const uint8*>(policy_response.policy_data().c_str()),
      policy_response.policy_data().size());
  std::vector<uint8> signature_bytes;
  std::string policy_blob;
  if (!signature_creator->Final(&signature_bytes)) {
    LOG(ERROR) << "Failed to create policy signature.";
    return std::string();
  }

  policy_response.mutable_policy_data_signature()->assign(
      reinterpret_cast<const char*>(vector_as_array(&signature_bytes)),
      signature_bytes.size());
  return policy_response.SerializeAsString();
}

void LoadPrivateKeyByPublicKey(
    const scoped_refptr<OwnerKeyUtil>& owner_key_util,
    scoped_refptr<PublicKey> public_key,
    const std::string& username_hash,
    const base::Callback<void(scoped_refptr<PublicKey> public_key,
                              scoped_refptr<PrivateKey> private_key)>&
        callback) {
  crypto::EnsureNSSInit();
  crypto::ScopedPK11Slot slot =
      crypto::GetPublicSlotForChromeOSUser(username_hash);
  scoped_refptr<PrivateKey> private_key(new PrivateKey(
      owner_key_util->FindPrivateKeyInSlot(public_key->data(), slot.get())));
  BrowserThread::PostTask(BrowserThread::UI,
                          FROM_HERE,
                          base::Bind(callback, public_key, private_key));
}

void LoadPrivateKey(const scoped_refptr<OwnerKeyUtil>& owner_key_util,
                    const std::string username_hash,
                    const base::Callback<void(
                        scoped_refptr<PublicKey> public_key,
                        scoped_refptr<PrivateKey> private_key)>& callback) {
  std::vector<uint8> public_key_data;
  scoped_refptr<PublicKey> public_key;
  if (!owner_key_util->ImportPublicKey(&public_key_data)) {
    scoped_refptr<PrivateKey> private_key;
    BrowserThread::PostTask(BrowserThread::UI,
                            FROM_HERE,
                            base::Bind(callback, public_key, private_key));
    return;
  }
  public_key = new PublicKey();
  public_key->data().swap(public_key_data);
  bool rv = BrowserThread::PostTask(BrowserThread::IO,
                                    FROM_HERE,
                                    base::Bind(&LoadPrivateKeyByPublicKey,
                                               owner_key_util,
                                               public_key,
                                               username_hash,
                                               callback));
  if (!rv) {
    // IO thread doesn't exists in unit tests, but it's safe to use NSS from
    // BlockingPool in unit tests.
    LoadPrivateKeyByPublicKey(
        owner_key_util, public_key, username_hash, callback);
  }
}

bool DoesPrivateKeyExistAsyncHelper(
    const scoped_refptr<OwnerKeyUtil>& owner_key_util) {
  std::vector<uint8> public_key;
  if (!owner_key_util->ImportPublicKey(&public_key))
    return false;
  scoped_ptr<crypto::RSAPrivateKey> key(
      crypto::RSAPrivateKey::FindFromPublicKeyInfo(public_key));
  bool is_owner = key.get() != NULL;
  return is_owner;
}

// Checks whether NSS slots with private key are mounted or
// not. Responds via |callback|.
void DoesPrivateKeyExistAsync(
    const OwnerSettingsService::IsOwnerCallback& callback) {
  scoped_refptr<OwnerKeyUtil> owner_key_util;
  if (g_owner_key_util_for_testing)
    owner_key_util = *g_owner_key_util_for_testing;
  else
    owner_key_util = OwnerSettingsService::MakeOwnerKeyUtil();
  if (!owner_key_util) {
    callback.Run(false);
    return;
  }
  scoped_refptr<base::TaskRunner> task_runner =
      content::BrowserThread::GetBlockingPool()
          ->GetTaskRunnerWithShutdownBehavior(
              base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
  base::PostTaskAndReplyWithResult(
      task_runner.get(),
      FROM_HERE,
      base::Bind(&DoesPrivateKeyExistAsyncHelper, owner_key_util),
      callback);
}

// Returns the current management mode.
em::PolicyData::ManagementMode GetManagementMode(
    DeviceSettingsService* service) {
  if (!service) {
    LOG(ERROR) << "DeviceSettingsService is not initialized";
    return em::PolicyData::NOT_MANAGED;
  }

  const em::PolicyData* policy_data = service->policy_data();
  if (policy_data && policy_data->has_management_mode())
    return policy_data->management_mode();
  return em::PolicyData::NOT_MANAGED;
}

// Returns true if it is okay to transfer from the current mode to the new
// mode. This function should be called in SetManagementMode().
bool CheckManagementModeTransition(em::PolicyData::ManagementMode current_mode,
                                   em::PolicyData::ManagementMode new_mode) {
  // Mode is not changed.
  if (current_mode == new_mode)
    return true;

  switch (current_mode) {
    case em::PolicyData::NOT_MANAGED:
      // For consumer management enrollment.
      return new_mode == em::PolicyData::CONSUMER_MANAGED;

    case em::PolicyData::ENTERPRISE_MANAGED:
      // Management mode cannot be set when it is currently ENTERPRISE_MANAGED.
      return false;

    case em::PolicyData::CONSUMER_MANAGED:
      // For consumer management unenrollment.
      return new_mode == em::PolicyData::NOT_MANAGED;
  }

  NOTREACHED();
  return false;
}

}  // namespace

OwnerSettingsService::OwnerSettingsService(Profile* profile)
    : profile_(profile),
      owner_key_util_(MakeOwnerKeyUtil()),
      waiting_for_profile_creation_(true),
      waiting_for_tpm_token_(true),
      weak_factory_(this) {
  if (TPMTokenLoader::IsInitialized()) {
    waiting_for_tpm_token_ = !TPMTokenLoader::Get()->IsTPMTokenReady();
    TPMTokenLoader::Get()->AddObserver(this);
  }

  if (DBusThreadManager::IsInitialized() &&
      DBusThreadManager::Get()->GetSessionManagerClient()) {
    DBusThreadManager::Get()->GetSessionManagerClient()->AddObserver(this);
  }

  registrar_.Add(this,
                 chrome::NOTIFICATION_PROFILE_CREATED,
                 content::Source<Profile>(profile_));
}

OwnerSettingsService::~OwnerSettingsService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (TPMTokenLoader::IsInitialized())
    TPMTokenLoader::Get()->RemoveObserver(this);

  if (DBusThreadManager::IsInitialized() &&
      DBusThreadManager::Get()->GetSessionManagerClient()) {
    DBusThreadManager::Get()->GetSessionManagerClient()->RemoveObserver(this);
  }
}

bool OwnerSettingsService::IsOwner() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return private_key_ && private_key_->key();
}

void OwnerSettingsService::IsOwnerAsync(const IsOwnerCallback& callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (private_key_) {
    base::MessageLoop::current()->PostTask(FROM_HERE,
                                           base::Bind(callback, IsOwner()));
  } else {
    pending_is_owner_callbacks_.push_back(callback);
  }
}

bool OwnerSettingsService::AssembleAndSignPolicyAsync(
    scoped_ptr<em::PolicyData> policy,
    const AssembleAndSignPolicyCallback& callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!IsOwner())
    return false;
  base::PostTaskAndReplyWithResult(
      BrowserThread::GetBlockingPool(),
      FROM_HERE,
      base::Bind(
          &AssembleAndSignPolicy, base::Passed(&policy), private_key_->key()),
      callback);
  return true;
}

void OwnerSettingsService::SignAndStoreAsync(
    scoped_ptr<em::ChromeDeviceSettingsProto> settings,
    const base::Closure& callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  scoped_ptr<em::PolicyData> policy = AssemblePolicy(
      user_id_, GetDeviceSettingsService()->policy_data(), settings.get());
  if (!policy) {
    HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback);
    return;
  }

  EnqueueSignAndStore(policy.Pass(), callback);
}

void OwnerSettingsService::SetManagementSettingsAsync(
    em::PolicyData::ManagementMode management_mode,
    const std::string& request_token,
    const std::string& device_id,
    const base::Closure& callback) {
  em::PolicyData::ManagementMode current_mode =
      GetManagementMode(GetDeviceSettingsService());
  if (!CheckManagementModeTransition(current_mode, management_mode)) {
    LOG(ERROR) << "Invalid management mode transition: current mode = "
               << current_mode << ", new mode = " << management_mode;
    HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback);
    return;
  }

  DeviceSettingsService* service = GetDeviceSettingsService();
  scoped_ptr<em::PolicyData> policy = AssemblePolicy(
      user_id_, service->policy_data(), service->device_settings());
  if (!policy) {
    HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback);
    return;
  }

  policy->set_management_mode(management_mode);
  policy->set_request_token(request_token);
  policy->set_device_id(device_id);

  EnqueueSignAndStore(policy.Pass(), callback);
}

void OwnerSettingsService::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (type != chrome::NOTIFICATION_PROFILE_CREATED) {
    NOTREACHED();
    return;
  }

  Profile* profile = content::Source<Profile>(source).ptr();
  if (profile != profile_) {
    NOTREACHED();
    return;
  }

  waiting_for_profile_creation_ = false;
  ReloadPrivateKey();
}

void OwnerSettingsService::OnTPMTokenReady() {
  DCHECK(thread_checker_.CalledOnValidThread());
  waiting_for_tpm_token_ = false;

  // TPMTokenLoader initializes the TPM and NSS database which is necessary to
  // determine ownership. Force a reload once we know these are initialized.
  ReloadPrivateKey();
}

void OwnerSettingsService::OwnerKeySet(bool success) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (success)
    ReloadPrivateKey();
}

// static
void OwnerSettingsService::IsOwnerForSafeModeAsync(
    const std::string& user_id,
    const std::string& user_hash,
    const IsOwnerCallback& callback) {
  CHECK(chromeos::LoginState::Get()->IsInSafeMode());

  // Make sure NSS is initialized and NSS DB is loaded for the user before
  // searching for the owner key.
  BrowserThread::PostTaskAndReply(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(base::IgnoreResult(&crypto::InitializeNSSForChromeOSUser),
                 user_id,
                 user_hash,
                 ProfileHelper::GetProfilePathByUserIdHash(user_hash)),
      base::Bind(&DoesPrivateKeyExistAsync, callback));
}

// static
scoped_refptr<ownership::OwnerKeyUtil>
OwnerSettingsService::MakeOwnerKeyUtil() {
  base::FilePath public_key_path;
  if (!PathService::Get(chromeos::FILE_OWNER_KEY, &public_key_path))
    return NULL;
  return new ownership::OwnerKeyUtilImpl(public_key_path);
}

// static
void OwnerSettingsService::SetOwnerKeyUtilForTesting(
    const scoped_refptr<OwnerKeyUtil>& owner_key_util) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (g_owner_key_util_for_testing) {
    delete g_owner_key_util_for_testing;
    g_owner_key_util_for_testing = NULL;
  }
  if (owner_key_util.get()) {
    g_owner_key_util_for_testing = new scoped_refptr<OwnerKeyUtil>();
    *g_owner_key_util_for_testing = owner_key_util;
  }
}

// static
void OwnerSettingsService::SetDeviceSettingsServiceForTesting(
    DeviceSettingsService* device_settings_service) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  g_device_settings_service_for_testing = device_settings_service;
}

void OwnerSettingsService::ReloadPrivateKey() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (waiting_for_profile_creation_ || waiting_for_tpm_token_)
    return;
  scoped_refptr<base::TaskRunner> task_runner =
      content::BrowserThread::GetBlockingPool()
          ->GetTaskRunnerWithShutdownBehavior(
              base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
  task_runner->PostTask(
      FROM_HERE,
      base::Bind(&LoadPrivateKey,
                 GetOwnerKeyUtil(),
                 ProfileHelper::GetUserIdHashFromProfile(profile_),
                 base::Bind(&OwnerSettingsService::OnPrivateKeyLoaded,
                            weak_factory_.GetWeakPtr())));
}

void OwnerSettingsService::OnPrivateKeyLoaded(
    scoped_refptr<PublicKey> public_key,
    scoped_refptr<PrivateKey> private_key) {
  DCHECK(thread_checker_.CalledOnValidThread());
  public_key_ = public_key;
  private_key_ = private_key;

  user_id_ = profile_->GetProfileName();
  const bool is_owner = IsOwner() || IsOwnerInTests(user_id_);
  if (is_owner && GetDeviceSettingsService())
    GetDeviceSettingsService()->InitOwner(user_id_, weak_factory_.GetWeakPtr());

  std::vector<IsOwnerCallback> is_owner_callbacks;
  is_owner_callbacks.swap(pending_is_owner_callbacks_);
  for (std::vector<IsOwnerCallback>::iterator it(is_owner_callbacks.begin());
       it != is_owner_callbacks.end();
       ++it) {
    it->Run(is_owner);
  }
}

void OwnerSettingsService::EnqueueSignAndStore(
    scoped_ptr<em::PolicyData> policy,
    const base::Closure& callback) {
  SignAndStoreSettingsOperation* operation = new SignAndStoreSettingsOperation(
      base::Bind(&OwnerSettingsService::HandleCompletedOperation,
                 weak_factory_.GetWeakPtr(),
                 callback),
      policy.Pass());
  operation->set_delegate(weak_factory_.GetWeakPtr());
  pending_operations_.push_back(operation);
  if (pending_operations_.front() == operation)
    StartNextOperation();
}

void OwnerSettingsService::StartNextOperation() {
  DeviceSettingsService* service = GetDeviceSettingsService();
  if (!pending_operations_.empty() && service &&
      service->session_manager_client()) {
    pending_operations_.front()->Start(
        service->session_manager_client(), GetOwnerKeyUtil(), public_key_);
  }
}

void OwnerSettingsService::HandleCompletedOperation(
    const base::Closure& callback,
    SessionManagerOperation* operation,
    DeviceSettingsService::Status status) {
  DCHECK_EQ(operation, pending_operations_.front());

  DeviceSettingsService* service = GetDeviceSettingsService();
  if (status == DeviceSettingsService::STORE_SUCCESS) {
    service->set_policy_data(operation->policy_data().Pass());
    service->set_device_settings(operation->device_settings().Pass());
  }

  if ((operation->public_key() && !public_key_) ||
      (operation->public_key() && public_key_ &&
       operation->public_key()->data() != public_key_->data())) {
    // Public part changed so we need to reload private part too.
    ReloadPrivateKey();
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
        content::Source<OwnerSettingsService>(this),
        content::NotificationService::NoDetails());
  }
  service->OnSignAndStoreOperationCompleted(status);
  if (!callback.is_null())
    callback.Run();

  pending_operations_.pop_front();
  delete operation;
  StartNextOperation();
}

void OwnerSettingsService::HandleError(DeviceSettingsService::Status status,
                                       const base::Closure& callback) {
  LOG(ERROR) << "Session manager operation failed: " << status;
  GetDeviceSettingsService()->OnSignAndStoreOperationCompleted(status);
  if (!callback.is_null())
    callback.Run();
}

scoped_refptr<OwnerKeyUtil> OwnerSettingsService::GetOwnerKeyUtil() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (g_owner_key_util_for_testing)
    return *g_owner_key_util_for_testing;
  return owner_key_util_;
}

DeviceSettingsService* OwnerSettingsService::GetDeviceSettingsService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (g_device_settings_service_for_testing)
    return g_device_settings_service_for_testing;
  if (DeviceSettingsService::IsInitialized())
    return DeviceSettingsService::Get();
  return NULL;
}

}  // namespace chromeos