summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
blob: c68aaa5367bd72d6ec9044afe2687956a74e57f5 (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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
// Copyright (c) 2013 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/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h"

#include <string>
#include <utility>

#include "base/base64.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/attestation/attestation_ca_client.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/enterprise_platform_keys_private.h"
#include "chrome/common/pref_names.h"
#include "chromeos/attestation/attestation_flow.h"
#include "chromeos/cryptohome/async_method_caller.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/constants/attestation_constants.h"
#include "chromeos/dbus/cryptohome/cryptohome_client.h"
#include "chromeos/dbus/dbus_method_call_status.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/settings/cros_settings_names.h"
#include "chromeos/tpm/install_attributes.h"
#include "components/account_id/account_id.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/known_user.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/common/manifest.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace {
// Prefix for naming machine keys used for SignedPublicKeyAndChallenge when
// challenging the EMK with register=true.
const char kEnterpriseMachineKeyForSpkacPrefix[] = "attest-ent-machine-";
}  // namespace

namespace extensions {

namespace api_epkp = api::enterprise_platform_keys_private;

// Base class

const char EPKPChallengeKeyBase::kChallengeBadBase64Error[] =
    "Challenge is not base64 encoded.";
const char EPKPChallengeKeyBase::kDevicePolicyDisabledError[] =
    "Remote attestation is not enabled for your device.";
const char EPKPChallengeKeyBase::kExtensionNotWhitelistedError[] =
    "The extension does not have permission to call this function.";
const char EPKPChallengeKeyBase::kResponseBadBase64Error[] =
    "Response cannot be encoded in base64.";
const char EPKPChallengeKeyBase::kSignChallengeFailedError[] =
    "Failed to sign the challenge.";
const char EPKPChallengeKeyBase::kUserNotManaged[] =
    "The user account is not enterprise managed.";

EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext(
    chromeos::attestation::AttestationKeyType key_type,
    const AccountId& account_id,
    const std::string& key_name,
    chromeos::attestation::AttestationCertificateProfile certificate_profile,
    bool require_user_consent,
    const std::string& key_name_for_spkac,
    const base::Callback<void(PrepareKeyResult)>& callback)
    : key_type(key_type),
      account_id(account_id),
      key_name(key_name),
      certificate_profile(certificate_profile),
      require_user_consent(require_user_consent),
      key_name_for_spkac(key_name_for_spkac),
      callback(callback) {}

EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext(
    const PrepareKeyContext& other) = default;

EPKPChallengeKeyBase::PrepareKeyContext::~PrepareKeyContext() {
}

EPKPChallengeKeyBase::EPKPChallengeKeyBase()
    : cryptohome_client_(chromeos::CryptohomeClient::Get()),
      async_caller_(cryptohome::AsyncMethodCaller::GetInstance()),
      install_attributes_(g_browser_process->platform_part()
                              ->browser_policy_connector_chromeos()
                              ->GetInstallAttributes()) {
  std::unique_ptr<chromeos::attestation::ServerProxy> ca_client(
      new chromeos::attestation::AttestationCAClient());
  default_attestation_flow_.reset(new chromeos::attestation::AttestationFlow(
      async_caller_, cryptohome_client_, std::move(ca_client)));
  attestation_flow_ = default_attestation_flow_.get();
}

EPKPChallengeKeyBase::EPKPChallengeKeyBase(
    chromeos::CryptohomeClient* cryptohome_client,
    cryptohome::AsyncMethodCaller* async_caller,
    chromeos::attestation::AttestationFlow* attestation_flow,
    chromeos::InstallAttributes* install_attributes) :
    cryptohome_client_(cryptohome_client),
    async_caller_(async_caller),
    attestation_flow_(attestation_flow),
    install_attributes_(install_attributes) {
}

EPKPChallengeKeyBase::~EPKPChallengeKeyBase() {
}

void EPKPChallengeKeyBase::GetDeviceAttestationEnabled(
    const base::Callback<void(bool)>& callback) const {
  chromeos::CrosSettings* settings = chromeos::CrosSettings::Get();
  chromeos::CrosSettingsProvider::TrustedStatus status =
      settings->PrepareTrustedValues(
          base::Bind(&EPKPChallengeKeyBase::GetDeviceAttestationEnabled,
                     base::Unretained(this), callback));

  bool value = false;
  switch (status) {
    case chromeos::CrosSettingsProvider::TRUSTED:
      if (!settings->GetBoolean(chromeos::kDeviceAttestationEnabled, &value))
        value = false;
      break;
    case chromeos::CrosSettingsProvider::TEMPORARILY_UNTRUSTED:
      // Do nothing. This function will be called again when the values are
      // ready.
      return;
    case chromeos::CrosSettingsProvider::PERMANENTLY_UNTRUSTED:
      // If the value cannot be trusted, we assume that the device attestation
      // is false to be on the safe side.
      break;
  }

  callback.Run(value);
}

bool EPKPChallengeKeyBase::IsEnterpriseDevice() const {
  return install_attributes_->IsEnterpriseManaged();
}

bool EPKPChallengeKeyBase::IsExtensionWhitelisted() const {
  if (!chromeos::ProfileHelper::Get()->GetUserByProfile(profile_)) {
    // Only allow remote attestation for apps that were force-installed on the
    // login/signin screen.
    // TODO(drcrash): Use a separate device-wide policy for the API.
    return Manifest::IsPolicyLocation(extension_->location());
  }
  if (Manifest::IsComponentLocation(extension_->location())) {
    // Note: For this to even be called, the component extension must also be
    // whitelisted in chrome/common/extensions/api/_permission_features.json
    return true;
  }
  const base::ListValue* list =
      profile_->GetPrefs()->GetList(prefs::kAttestationExtensionWhitelist);
  base::Value value(extension_->id());
  return list->Find(value) != list->end();
}

AccountId EPKPChallengeKeyBase::GetAccountId() const {
  const user_manager::User* user =
      chromeos::ProfileHelper::Get()->GetUserByProfile(profile_);

  // Signin profile doesn't have associated user.
  if (!user) {
    return EmptyAccountId();
  }

  return user->GetAccountId();
}

bool EPKPChallengeKeyBase::IsUserAffiliated() const {
  const user_manager::User* const user =
      user_manager::UserManager::Get()->FindUser(GetAccountId());

  if (user) {
    return user->IsAffiliated();
  }

  return false;
}

std::string EPKPChallengeKeyBase::GetEnterpriseDomain() const {
  return install_attributes_->GetDomain();
}

std::string EPKPChallengeKeyBase::GetUserEmail() const {
  return GetAccountId().GetUserEmail();
}

std::string EPKPChallengeKeyBase::GetDeviceId() const {
  return install_attributes_->GetDeviceId();
}

void EPKPChallengeKeyBase::PrepareKey(
    chromeos::attestation::AttestationKeyType key_type,
    const AccountId& account_id,
    const std::string& key_name,
    chromeos::attestation::AttestationCertificateProfile certificate_profile,
    bool require_user_consent,
    const std::string& key_name_for_spkac,
    const base::Callback<void(PrepareKeyResult)>& callback) {
  const PrepareKeyContext context =
      PrepareKeyContext(key_type, account_id, key_name, certificate_profile,
                        require_user_consent, key_name_for_spkac, callback);
  cryptohome_client_->TpmAttestationIsPrepared(
      base::BindOnce(&EPKPChallengeKeyBase::IsAttestationPreparedCallback,
                     base::Unretained(this), context));
}

void EPKPChallengeKeyBase::IsAttestationPreparedCallback(
    const PrepareKeyContext& context,
    base::Optional<bool> result) {
  if (!result.has_value()) {
    context.callback.Run(PREPARE_KEY_DBUS_ERROR);
    return;
  }
  if (!result.value()) {
    cryptohome_client_->TpmIsEnabled(
        base::BindOnce(&EPKPChallengeKeyBase::PrepareKeyErrorHandlerCallback,
                       base::Unretained(this), context));
    return;
  }

  if (!context.key_name_for_spkac.empty()) {
    // Generate a new key and have it signed by PCA.
    attestation_flow_->GetCertificate(
        context.certificate_profile, context.account_id,
        std::string(),  // Not used.
        true,           // Force a new key to be generated.
        context.key_name_for_spkac,
        base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback,
                   base::Unretained(this), context.callback));
    return;
  }
  // Attestation is available, see if the key we need already exists.
  cryptohome_client_->TpmAttestationDoesKeyExist(
      context.key_type,
      cryptohome::CreateAccountIdentifierFromAccountId(context.account_id),
      context.key_name,
      base::BindOnce(&EPKPChallengeKeyBase::DoesKeyExistCallback,
                     base::Unretained(this), context));
}

void EPKPChallengeKeyBase::PrepareKeyErrorHandlerCallback(
    const PrepareKeyContext& context,
    base::Optional<bool> is_tpm_enabled) {
  if (!is_tpm_enabled.has_value()) {
    context.callback.Run(PREPARE_KEY_DBUS_ERROR);
    return;
  }

  if (is_tpm_enabled.value()) {
    context.callback.Run(PREPARE_KEY_RESET_REQUIRED);
  } else {
    context.callback.Run(PREPARE_KEY_ATTESTATION_UNSUPPORTED);
  }
}

void EPKPChallengeKeyBase::DoesKeyExistCallback(
    const PrepareKeyContext& context,
    base::Optional<bool> result) {
  if (!result.has_value()) {
    context.callback.Run(PREPARE_KEY_DBUS_ERROR);
    return;
  }

  if (result.value()) {
    // The key exists. Do nothing more.
    context.callback.Run(PREPARE_KEY_OK);
  } else {
    // The key does not exist. Create a new key and have it signed by PCA.
    if (context.require_user_consent) {
      // We should ask the user explicitly before sending any private
      // information to PCA.
      AskForUserConsent(
          base::Bind(&EPKPChallengeKeyBase::AskForUserConsentCallback,
                     base::Unretained(this), context));
    } else {
      // User consent is not required. Skip to the next step.
      AskForUserConsentCallback(context, true);
    }
  }
}

void EPKPChallengeKeyBase::AskForUserConsent(
    const base::Callback<void(bool)>& callback) const {
  // TODO(davidyu): right now we just simply reject the request before we have
  // a way to ask for user consent.
  callback.Run(false);
}

void EPKPChallengeKeyBase::AskForUserConsentCallback(
    const PrepareKeyContext& context,
    bool result) {
  if (!result) {
    // The user rejects the request.
    context.callback.Run(PREPARE_KEY_USER_REJECTED);
    return;
  }

  // Generate a new key and have it signed by PCA.
  attestation_flow_->GetCertificate(
      context.certificate_profile, context.account_id,
      std::string(),  // Not used.
      true,           // Force a new key to be generated.
      std::string(),  // Leave key name empty to generate a default name.
      base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback,
                 base::Unretained(this), context.callback));
}

void EPKPChallengeKeyBase::GetCertificateCallback(
    const base::Callback<void(PrepareKeyResult)>& callback,
    chromeos::attestation::AttestationStatus status,
    const std::string& pem_certificate_chain) {
  if (status != chromeos::attestation::ATTESTATION_SUCCESS) {
    callback.Run(PREPARE_KEY_GET_CERTIFICATE_FAILED);
    return;
  }

  callback.Run(PREPARE_KEY_OK);
}

// Implementation of ChallengeMachineKey()

const char EPKPChallengeMachineKey::kGetCertificateFailedError[] =
    "Failed to get Enterprise machine certificate. Error code = %d";
const char EPKPChallengeMachineKey::kKeyRegistrationFailedError[] =
    "Machine key registration failed.";
const char EPKPChallengeMachineKey::kNonEnterpriseDeviceError[] =
    "The device is not enterprise enrolled.";

EPKPChallengeMachineKey::EPKPChallengeMachineKey() : EPKPChallengeKeyBase() {
}

EPKPChallengeMachineKey::EPKPChallengeMachineKey(
    chromeos::CryptohomeClient* cryptohome_client,
    cryptohome::AsyncMethodCaller* async_caller,
    chromeos::attestation::AttestationFlow* attestation_flow,
    chromeos::InstallAttributes* install_attributes) :
    EPKPChallengeKeyBase(cryptohome_client,
                         async_caller,
                         attestation_flow,
                         install_attributes) {
}

EPKPChallengeMachineKey::~EPKPChallengeMachineKey() {
}

void EPKPChallengeMachineKey::Run(scoped_refptr<ExtensionFunction> caller,
                                  const ChallengeKeyCallback& callback,
                                  const std::string& challenge,
                                  bool register_key) {
  callback_ = callback;
  profile_ = ChromeExtensionFunctionDetails(caller.get()).GetProfile();
  extension_ = scoped_refptr<const Extension>(caller->extension());

  // Check if the device is enterprise enrolled.
  if (!IsEnterpriseDevice()) {
    callback_.Run(false, kNonEnterpriseDeviceError);
    return;
  }

  // Check if the extension is whitelisted in the user policy.
  if (!IsExtensionWhitelisted()) {
    callback_.Run(false, kExtensionNotWhitelistedError);
    return;
  }

  // Check whether the user is managed unless the signin profile is used.
  if (chromeos::ProfileHelper::Get()->GetUserByProfile(profile_) &&
      !IsUserAffiliated()) {
    callback_.Run(false, kUserNotManaged);
    return;
  }

  // Check if RA is enabled in the device policy.
  GetDeviceAttestationEnabled(
      base::Bind(&EPKPChallengeMachineKey::GetDeviceAttestationEnabledCallback,
                 base::Unretained(this), challenge, register_key));
}

void EPKPChallengeMachineKey::DecodeAndRun(
    scoped_refptr<ExtensionFunction> caller,
    const ChallengeKeyCallback& callback,
    const std::string& encoded_challenge,
    bool register_key) {
  std::string challenge;
  if (!base::Base64Decode(encoded_challenge, &challenge)) {
    callback.Run(false, kChallengeBadBase64Error);
    return;
  }
  Run(caller, callback, challenge, register_key);
}

void EPKPChallengeMachineKey::GetDeviceAttestationEnabledCallback(
    const std::string& challenge,
    bool register_key,
    bool enabled) {
  if (!enabled) {
    callback_.Run(false, kDevicePolicyDisabledError);
    return;
  }

  // The EMK cannot be registered as that would relinquish it and the DMServer
  // relies on it to remain stable. If register_key = true, generate a new
  // machine key to side-load into the system-wide token. This key will be
  // used for SignedPublicKeyAndChallenge but the challenge response will still
  // be singed using the stable EMK.
  std::string key_name_for_spkac;
  if (register_key) {
    key_name_for_spkac = kEnterpriseMachineKeyForSpkacPrefix + extension_->id();
  }
  PrepareKey(chromeos::attestation::KEY_DEVICE,
             EmptyAccountId(),  // Not used.
             chromeos::attestation::kEnterpriseMachineKey,
             chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE,
             false,  // user consent is not required.
             key_name_for_spkac,
             base::Bind(&EPKPChallengeMachineKey::PrepareKeyCallback,
                        base::Unretained(this), challenge, register_key,
                        key_name_for_spkac));
}

void EPKPChallengeMachineKey::PrepareKeyCallback(
    const std::string& challenge,
    bool register_key,
    const std::string& key_name_for_spkac,
    PrepareKeyResult result) {
  if (result != PREPARE_KEY_OK) {
    callback_.Run(false,
                  base::StringPrintf(kGetCertificateFailedError, result));
    return;
  }

  // Everything is checked. Sign the challenge.
  async_caller_->TpmAttestationSignEnterpriseChallenge(
      chromeos::attestation::KEY_DEVICE,
      cryptohome::Identification(),  // Not used.
      chromeos::attestation::kEnterpriseMachineKey, GetEnterpriseDomain(),
      GetDeviceId(),
      register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY
                   : chromeos::attestation::CHALLENGE_OPTION_NONE,
      challenge, key_name_for_spkac,
      base::Bind(&EPKPChallengeMachineKey::SignChallengeCallback,
                 base::Unretained(this), register_key));
}

void EPKPChallengeMachineKey::SignChallengeCallback(
    bool register_key,
    bool success,
    const std::string& response) {
  if (!success) {
    callback_.Run(false, kSignChallengeFailedError);
    return;
  }
  if (register_key) {
    std::string key_name_for_spkac =
        kEnterpriseMachineKeyForSpkacPrefix + extension_->id();
    async_caller_->TpmAttestationRegisterKey(
        chromeos::attestation::KEY_DEVICE,
        cryptohome::Identification(),  // Not used.
        key_name_for_spkac,
        base::Bind(&EPKPChallengeMachineKey::RegisterKeyCallback,
                   base::Unretained(this), response));
  } else {
    RegisterKeyCallback(response, true, cryptohome::MOUNT_ERROR_NONE);
  }
}

void EPKPChallengeMachineKey::RegisterKeyCallback(
    const std::string& response,
    bool success,
    cryptohome::MountError return_code) {
  if (!success || return_code != cryptohome::MOUNT_ERROR_NONE) {
    callback_.Run(false, kKeyRegistrationFailedError);
    return;
  }
  callback_.Run(true, response);
}

// Implementation of ChallengeUserKey()

const char EPKPChallengeUserKey::kGetCertificateFailedError[] =
    "Failed to get Enterprise user certificate. Error code = %d";
const char EPKPChallengeUserKey::kKeyRegistrationFailedError[] =
    "Key registration failed.";
const char EPKPChallengeUserKey::kUserPolicyDisabledError[] =
    "Remote attestation is not enabled for your account.";
const char EPKPChallengeUserKey::kUserKeyNotAvailable[] =
    "User keys cannot be challenged in this profile.";

EPKPChallengeUserKey::EPKPChallengeUserKey() : EPKPChallengeKeyBase() {
}

EPKPChallengeUserKey::EPKPChallengeUserKey(
    chromeos::CryptohomeClient* cryptohome_client,
    cryptohome::AsyncMethodCaller* async_caller,
    chromeos::attestation::AttestationFlow* attestation_flow,
    chromeos::InstallAttributes* install_attributes) :
    EPKPChallengeKeyBase(cryptohome_client,
                         async_caller,
                         attestation_flow,
                         install_attributes) {
}

EPKPChallengeUserKey::~EPKPChallengeUserKey() {
}

void EPKPChallengeUserKey::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(prefs::kAttestationEnabled, false);
  registry->RegisterListPref(prefs::kAttestationExtensionWhitelist);
}

void EPKPChallengeUserKey::Run(scoped_refptr<ExtensionFunction> caller,
                               const ChallengeKeyCallback& callback,
                               const std::string& challenge,
                               bool register_key) {
  callback_ = callback;
  profile_ = ChromeExtensionFunctionDetails(caller.get()).GetProfile();
  extension_ = scoped_refptr<const Extension>(caller->extension());

  // Check if user keys are available in this profile.
  if (!chromeos::ProfileHelper::Get()->GetUserByProfile(profile_)) {
    callback_.Run(false, EPKPChallengeUserKey::kUserKeyNotAvailable);
    return;
  }

  // Check if RA is enabled in the user policy.
  if (!IsRemoteAttestationEnabledForUser()) {
    callback_.Run(false, kUserPolicyDisabledError);
    return;
  }

  // Check if the extension is whitelisted in the user policy.
  if (!IsExtensionWhitelisted()) {
    callback_.Run(false, kExtensionNotWhitelistedError);
    return;
  }

  if (IsEnterpriseDevice()) {
    if (!IsUserAffiliated()) {
      callback_.Run(false, kUserNotManaged);
      return;
    }

    // Check if RA is enabled in the device policy.
    GetDeviceAttestationEnabled(
        base::Bind(&EPKPChallengeUserKey::GetDeviceAttestationEnabledCallback,
                   base::Unretained(this), challenge, register_key,
                   false));  // user consent is not required.
  } else {
    // For personal devices, we don't need to check if RA is enabled in the
    // device, but we need to ask for user consent if the key does not exist.
    GetDeviceAttestationEnabledCallback(challenge, register_key,
                                        true,   // user consent is required.
                                        true);  // attestation is enabled.
  }
}

void EPKPChallengeUserKey::DecodeAndRun(scoped_refptr<ExtensionFunction> caller,
                                        const ChallengeKeyCallback& callback,
                                        const std::string& encoded_challenge,
                                        bool register_key) {
  std::string challenge;
  if (!base::Base64Decode(encoded_challenge, &challenge)) {
    callback.Run(false, kChallengeBadBase64Error);
    return;
  }
  Run(caller, callback, challenge, register_key);
}

void EPKPChallengeUserKey::GetDeviceAttestationEnabledCallback(
    const std::string& challenge,
    bool register_key,
    bool require_user_consent,
    bool enabled) {
  if (!enabled) {
    callback_.Run(false, kDevicePolicyDisabledError);
    return;
  }

  PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(),
             chromeos::attestation::kEnterpriseUserKey,
             chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE,
             require_user_consent, std::string() /* key_name_for_spkac */,
             base::Bind(&EPKPChallengeUserKey::PrepareKeyCallback,
                        base::Unretained(this), challenge, register_key));
}

void EPKPChallengeUserKey::PrepareKeyCallback(const std::string& challenge,
                                              bool register_key,
                                              PrepareKeyResult result) {
  if (result != PREPARE_KEY_OK) {
    callback_.Run(false,
                  base::StringPrintf(kGetCertificateFailedError, result));
    return;
  }

  // Everything is checked. Sign the challenge.
  async_caller_->TpmAttestationSignEnterpriseChallenge(
      chromeos::attestation::KEY_USER,
      cryptohome::Identification(GetAccountId()),
      chromeos::attestation::kEnterpriseUserKey, GetUserEmail(), GetDeviceId(),
      register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY
                   : chromeos::attestation::CHALLENGE_OPTION_NONE,
      challenge, std::string() /* key_name_for_spkac */,
      base::Bind(&EPKPChallengeUserKey::SignChallengeCallback,
                 base::Unretained(this), register_key));
}

void EPKPChallengeUserKey::SignChallengeCallback(bool register_key,
                                                 bool success,
                                                 const std::string& response) {
  if (!success) {
    callback_.Run(false, kSignChallengeFailedError);
    return;
  }

  if (register_key) {
    async_caller_->TpmAttestationRegisterKey(
        chromeos::attestation::KEY_USER,
        cryptohome::Identification(GetAccountId()),
        chromeos::attestation::kEnterpriseUserKey,
        base::Bind(&EPKPChallengeUserKey::RegisterKeyCallback,
                   base::Unretained(this), response));
  } else {
    RegisterKeyCallback(response, true, cryptohome::MOUNT_ERROR_NONE);
  }
}

void EPKPChallengeUserKey::RegisterKeyCallback(
    const std::string& response,
    bool success,
    cryptohome::MountError return_code) {
  if (!success || return_code != cryptohome::MOUNT_ERROR_NONE) {
    callback_.Run(false, kKeyRegistrationFailedError);
    return;
  }
  callback_.Run(true, response);
}

bool EPKPChallengeUserKey::IsRemoteAttestationEnabledForUser() const {
  return profile_->GetPrefs()->GetBoolean(prefs::kAttestationEnabled);
}

EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::
    EnterprisePlatformKeysPrivateChallengeMachineKeyFunction()
    : default_impl_(new EPKPChallengeMachineKey), impl_(default_impl_.get()) {}

EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::
    EnterprisePlatformKeysPrivateChallengeMachineKeyFunction(
        EPKPChallengeMachineKey* impl_for_testing)
    : impl_(impl_for_testing) {}

EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::
    ~EnterprisePlatformKeysPrivateChallengeMachineKeyFunction() = default;

ExtensionFunction::ResponseAction
EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::Run() {
  std::unique_ptr<api_epkp::ChallengeMachineKey::Params> params(
      api_epkp::ChallengeMachineKey::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params);
  ChallengeKeyCallback callback =
      base::Bind(&EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::
                     OnChallengedKey,
                 this);
  // base::Unretained is safe on impl_ since its life-cycle matches |this| and
  // |callback| holds a reference to |this|.
  base::Closure task = base::Bind(&EPKPChallengeMachineKey::DecodeAndRun,
                                  base::Unretained(impl_),
                                  scoped_refptr<ExtensionFunction>(this),
                                  callback, params->challenge, false);
  base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task);
  return RespondLater();
}

void EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::OnChallengedKey(
    bool success,
    const std::string& data) {
  if (success) {
    std::string encoded_response;
    base::Base64Encode(data, &encoded_response);
    Respond(ArgumentList(
        api_epkp::ChallengeMachineKey::Results::Create(encoded_response)));
  } else {
    Respond(Error(data));
  }
}

EnterprisePlatformKeysPrivateChallengeUserKeyFunction::
    EnterprisePlatformKeysPrivateChallengeUserKeyFunction()
    : default_impl_(new EPKPChallengeUserKey), impl_(default_impl_.get()) {}

EnterprisePlatformKeysPrivateChallengeUserKeyFunction::
    EnterprisePlatformKeysPrivateChallengeUserKeyFunction(
        EPKPChallengeUserKey* impl_for_testing)
    : impl_(impl_for_testing) {}

EnterprisePlatformKeysPrivateChallengeUserKeyFunction::
    ~EnterprisePlatformKeysPrivateChallengeUserKeyFunction() = default;

ExtensionFunction::ResponseAction
EnterprisePlatformKeysPrivateChallengeUserKeyFunction::Run() {
  std::unique_ptr<api_epkp::ChallengeUserKey::Params> params(
      api_epkp::ChallengeUserKey::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params);
  ChallengeKeyCallback callback = base::Bind(
      &EnterprisePlatformKeysPrivateChallengeUserKeyFunction::OnChallengedKey,
      this);
  // base::Unretained is safe on impl_ since its life-cycle matches |this| and
  // |callback| holds a reference to |this|.
  base::Closure task =
      base::Bind(&EPKPChallengeUserKey::DecodeAndRun, base::Unretained(impl_),
                 scoped_refptr<ExtensionFunction>(this), callback,
                 params->challenge, params->register_key);
  base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task);
  return RespondLater();
}

void EnterprisePlatformKeysPrivateChallengeUserKeyFunction::OnChallengedKey(
    bool success,
    const std::string& data) {
  if (success) {
    std::string encoded_response;
    base::Base64Encode(data, &encoded_response);
    Respond(ArgumentList(
        api_epkp::ChallengeUserKey::Results::Create(encoded_response)));
  } else {
    Respond(Error(data));
  }
}

}  // namespace extensions