File: tpm_challenge_key_subtle.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (778 lines) | stat: -rw-r--r-- 27,778 bytes parent folder | download | duplicates (6)
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/attestation/tpm_challenge_key_subtle.h"

#include <stdint.h>

#include <optional>
#include <vector>

#include "base/base64.h"
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/values.h"
#include "chrome/browser/ash/attestation/attestation_ca_client.h"
#include "chrome/browser/ash/attestation/machine_certificate_uploader.h"
#include "chrome/browser/ash/platform_keys/key_permissions/key_permissions_manager.h"
#include "chrome/browser/ash/platform_keys/key_permissions/key_permissions_manager_impl.h"
#include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h"
#include "chrome/browser/ash/policy/core/device_cloud_policy_manager_ash.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part_ash.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/attestation/attestation_flow_adaptive.h"
#include "chromeos/ash/components/cryptohome/cryptohome_parameters.h"
#include "chromeos/ash/components/dbus/attestation/attestation_client.h"
#include "chromeos/ash/components/dbus/attestation/interface.pb.h"
#include "chromeos/ash/components/dbus/constants/attestation_constants.h"
#include "chromeos/ash/components/install_attributes/install_attributes.h"
#include "chromeos/ash/components/settings/cros_settings.h"
#include "chromeos/ash/components/settings/cros_settings_names.h"
#include "chromeos/components/kiosk/kiosk_utils.h"
#include "chromeos/dbus/tpm_manager/tpm_manager.pb.h"
#include "chromeos/dbus/tpm_manager/tpm_manager_client.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"

namespace ash {
namespace attestation {

using ::attestation::VerifiedAccessFlow;
using Result = TpmChallengeKeyResult;
using ResultCode = TpmChallengeKeyResultCode;

//==================== TpmChallengeKeySubtleFactory ============================

TpmChallengeKeySubtle* TpmChallengeKeySubtleFactory::next_result_for_testing_ =
    nullptr;

// static
std::unique_ptr<TpmChallengeKeySubtle> TpmChallengeKeySubtleFactory::Create() {
  if (next_result_for_testing_) [[unlikely]] {
    std::unique_ptr<TpmChallengeKeySubtle> result(next_result_for_testing_);
    next_result_for_testing_ = nullptr;
    return result;
  }

  return std::make_unique<TpmChallengeKeySubtleImpl>();
}

// static
std::unique_ptr<TpmChallengeKeySubtle>
TpmChallengeKeySubtleFactory::CreateForPreparedKey(
    VerifiedAccessFlow flow_type,
    bool will_register_key,
    ::attestation::KeyType key_crypto_type,
    const std::string& key_name,
    const std::string& public_key,
    Profile* profile) {
  auto result = TpmChallengeKeySubtleFactory::Create();
  result->RestorePreparedKeyState(flow_type, will_register_key, key_crypto_type,
                                  key_name, public_key, profile);
  return result;
}

// static
void TpmChallengeKeySubtleFactory::SetForTesting(
    std::unique_ptr<TpmChallengeKeySubtle> next_result) {
  DCHECK(next_result_for_testing_ == nullptr);
  // unique_ptr itself cannot be stored in a static variable because of its
  // complex destructor.
  next_result_for_testing_ = next_result.release();
}

// static
bool TpmChallengeKeySubtleFactory::WillReturnTestingInstance() {
  return (next_result_for_testing_ != nullptr);
}

//===================== TpmChallengeKeySubtleImpl ==============================

namespace {

// Returns true if the device is enterprise managed.
bool IsEnterpriseDevice() {
  return InstallAttributes::Get()->IsEnterpriseManaged();
}

// For unmanaged devices we need to ask for user consent if the key does not
// exist because data will be sent to the PCA. In case of the flow type being
// DEVICE_TRUST_CONNECTOR, user consent is not required since it's only used
// for attesting the DTC payload and is not usable by extensions.
// Historical note: For managed device there used to be policies to control this
// (AttestationEnabledForUser,AttestationEnabledForDevice) but they were removed
// from the client after having been set to true unconditionally for all clients
// for a long time.
bool IsUserConsentRequired(VerifiedAccessFlow flow_type) {
  if (flow_type == VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR) {
    return false;
  }

  return !IsEnterpriseDevice();
}

// If no key name was given, use default well-known key names so they can be
// reused across attestation operations (multiple challenge responses can be
// generated using the same key).
std::string GetDefaultKeyName(VerifiedAccessFlow flow_type,
                              ::attestation::KeyType key_crypto_type) {
  // When the caller wants to "register" a key through attestation (resulting in
  // a general-purpose key in the chaps PKCS#11 store), the behavior is
  // different between EUK and EMK:
  //
  // For EUK, the EUK used to sign the attestation response is also the key that
  // is "registered". If the EUK does not exist, one will be generated; but if
  // it does already exist, the existing key will be used.  Thus it must be
  // parameterized with the crypto algorithm type to ensure that the caller gets
  // a key of the type they expect.
  //
  //  For EMK, the EMK used to sign the attestation response must remain stable
  //  and instead a newly-generated EMK is registered. This function returns the
  //  EMK that is used to sign the attesation response, so it may not be
  //  parametrized with the crypto algorithm type.
  //
  //  See http://go/chromeos-va-registering-device-wide-keys-support for details
  //  on the concept of the stable EMK.
  switch (flow_type) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      return kEnterpriseMachineKey;
    case VerifiedAccessFlow::ENTERPRISE_USER:
      switch (key_crypto_type) {
        case ::attestation::KEY_TYPE_RSA:
          return kEnterpriseUserKey;
        case ::attestation::KEY_TYPE_ECC:
          return std::string(kEnterpriseUserKey) + "-ecdsa";
      }
    default:
      NOTREACHED();
  }
}

// Returns the key name that should be used for the attestation platform APIs.
std::string GetKeyNameWithDefault(VerifiedAccessFlow flow_type,
                                  ::attestation::KeyType key_crypto_type,
                                  const std::string& key_name) {
  if (!key_name.empty())
    return key_name;

  return GetDefaultKeyName(flow_type, key_crypto_type);
}

}  // namespace

TpmChallengeKeySubtleImpl::TpmChallengeKeySubtleImpl()
    : default_attestation_flow_(std::make_unique<AttestationFlowAdaptive>(
          std::make_unique<AttestationCAClient>())),
      attestation_flow_(default_attestation_flow_.get()) {
  policy::DeviceCloudPolicyManagerAsh* manager =
      g_browser_process->platform_part()
          ->browser_policy_connector_ash()
          ->GetDeviceCloudPolicyManager();
  if (manager) {
    machine_certificate_uploader_ = manager->GetMachineCertificateUploader();
  }
}

TpmChallengeKeySubtleImpl::TpmChallengeKeySubtleImpl(
    AttestationFlow* attestation_flow_for_testing,
    MachineCertificateUploader* machine_certificate_uploader_for_testing)
    : attestation_flow_(attestation_flow_for_testing),
      machine_certificate_uploader_(machine_certificate_uploader_for_testing) {}

TpmChallengeKeySubtleImpl::~TpmChallengeKeySubtleImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void TpmChallengeKeySubtleImpl::RestorePreparedKeyState(
    VerifiedAccessFlow flow_type,
    bool will_register_key,
    ::attestation::KeyType key_crypto_type,
    const std::string& key_name,
    const std::string& public_key,
    Profile* profile) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!will_register_key || !public_key.empty());

  // Ensure that the selected flow type is supported
  CHECK(flow_type == VerifiedAccessFlow::ENTERPRISE_MACHINE ||
        flow_type == VerifiedAccessFlow::ENTERPRISE_USER);

  // For the ENTERPRISE_USER flow, a |profile| is strictly necessary.
  DCHECK(flow_type != VerifiedAccessFlow::ENTERPRISE_USER || profile);

  // For DEVICE_TRUST_CONNECTOR, a key name is required and registering a key is
  // not allowed.
  CHECK(flow_type != VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR ||
        !key_name.empty());
  CHECK(flow_type != VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR ||
        !will_register_key);

  flow_type_ = flow_type;
  will_register_key_ = will_register_key;
  key_crypto_type_ = key_crypto_type;
  key_name_ = GetKeyNameWithDefault(flow_type, key_crypto_type, key_name);
  public_key_ = public_key;
  profile_ = profile;
}

void TpmChallengeKeySubtleImpl::StartPrepareKeyStep(
    VerifiedAccessFlow flow_type,
    bool will_register_key,
    ::attestation::KeyType key_crypto_type,
    const std::string& key_name,
    Profile* profile,
    TpmChallengeKeyCallback callback,
    const std::optional<std::string>& signals) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(callback_.is_null());

  // For ENTERPRISE_MACHINE: if |will_register_key| is true, |key_name| should
  // not be empty, if |register_key| is false, |key_name| will not be used.
  DCHECK((flow_type != VerifiedAccessFlow::ENTERPRISE_MACHINE) ||
         (will_register_key == !key_name.empty()))
      << "Invalid arguments: " << will_register_key << " " << !key_name.empty();

  // For ENTERPRISE_USER, a |profile| is strictly necessary.
  DCHECK(flow_type != VerifiedAccessFlow::ENTERPRISE_USER || profile);

  // For DEVICE_TRUST_CONNECTOR, a key name is required and registering a key is
  // not allowed.
  CHECK(flow_type != VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR ||
        !key_name.empty());
  CHECK(flow_type != VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR ||
        !will_register_key);

  // Ensure that the selected flow type is supported
  if (flow_type != VerifiedAccessFlow::ENTERPRISE_MACHINE &&
      flow_type != VerifiedAccessFlow::ENTERPRISE_USER &&
      flow_type != VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR) {
    std::move(callback).Run(
        Result::MakeError(ResultCode::kVerifiedAccessFlowUnsupportedError));
    return;
  }

  flow_type_ = flow_type;
  will_register_key_ = will_register_key;
  key_crypto_type_ = key_crypto_type;
  key_name_ = GetKeyNameWithDefault(flow_type, key_crypto_type, key_name);
  profile_ = profile;
  callback_ = std::move(callback);
  signals_ = signals;

  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      PrepareEnterpriseMachineFlow();
      return;
    case VerifiedAccessFlow::ENTERPRISE_USER:
      PrepareEnterpriseUserFlow();
      return;
    case VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR:
      PrepareDeviceTrustConnectorFlow();
      return;
    default:
      NOTREACHED();
  }
}

void TpmChallengeKeySubtleImpl::PrepareEnterpriseMachineFlow() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Check if the device is enterprise enrolled.
  if (!IsEnterpriseDevice()) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kNonEnterpriseDeviceError));
    return;
  }

  // Check whether the user is affiliated unless this is a device-wide instance.
  if (GetUser() && !IsUserAffiliated()) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kUserNotManagedError));
    return;
  }

  // Wait for the machine certificate to be uploaded.
  if (machine_certificate_uploader_) {
    machine_certificate_uploader_->WaitForUploadComplete(base::BindOnce(
        &TpmChallengeKeySubtleImpl::PrepareKey, weak_factory_.GetWeakPtr()));
  } else {
    PrepareKey(true);
  }
}

void TpmChallengeKeySubtleImpl::PrepareEnterpriseUserFlow() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Check if user keys are available in this profile.
  if (!GetUser()) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kUserKeyNotAvailableError));
    return;
  }

  if (IsEnterpriseDevice()) {
    if (!IsUserAffiliated()) {
      std::move(callback_).Run(
          Result::MakeError(ResultCode::kUserNotManagedError));
      return;
    }
  }

  PrepareKey(true);
}

void TpmChallengeKeySubtleImpl::PrepareDeviceTrustConnectorFlow() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // TODO(b/277707201): remove once user email from login screen is available
  // here.
  if (!GetUser()) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kUserKeyNotAvailableError));
    return;
  }

  // Check whether the user is managed unless this is a device-wide instance.
  if (GetUser() && !IsUserManaged()) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kUserNotManagedError));
    return;
  }

  PrepareKey(true);
}

bool TpmChallengeKeySubtleImpl::IsUserManaged() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!profile_) {
    return false;
  }

  const auto* profile_policy_connector = profile_->GetProfilePolicyConnector();

  if (!profile_policy_connector) {
    return false;
  }

  return profile_policy_connector->IsManaged();
}

bool TpmChallengeKeySubtleImpl::IsUserAffiliated() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const user_manager::User* const user = GetUser();
  if (user) {
    return user->IsAffiliated();
  }
  return false;
}

std::string TpmChallengeKeySubtleImpl::GetEmail() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      return std::string();
    case VerifiedAccessFlow::ENTERPRISE_USER:
      [[fallthrough]];
    case VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR:
      return GetAccountId().GetUserEmail();
    default:
      NOTREACHED();
  }
}

AttestationCertificateProfile TpmChallengeKeySubtleImpl::GetCertificateProfile()
    const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      return PROFILE_ENTERPRISE_MACHINE_CERTIFICATE;
    case VerifiedAccessFlow::ENTERPRISE_USER:
      return PROFILE_ENTERPRISE_USER_CERTIFICATE;
    case VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR:
      return PROFILE_DEVICE_TRUST_USER_CERTIFICATE;
    default:
      NOTREACHED();
  }
}

const user_manager::User* TpmChallengeKeySubtleImpl::GetUser() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!profile_)
    return nullptr;
  return ProfileHelper::Get()->GetUserByProfile(profile_);
}

AccountId TpmChallengeKeySubtleImpl::GetAccountId() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const user_manager::User* user = GetUser();
  if (user) {
    return user->GetAccountId();
  }
  // Signin profile doesn't have associated user.
  return EmptyAccountId();
}

AccountId TpmChallengeKeySubtleImpl::GetAccountIdForAttestationFlow() const {
  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      [[fallthrough]];
    case VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR:
      return EmptyAccountId();
    case VerifiedAccessFlow::ENTERPRISE_USER:
      return GetAccountId();
    default:
      LOG(DFATAL) << "Unsupported Verified Access flow type: " << flow_type_;
      return EmptyAccountId();
  }
}

std::string TpmChallengeKeySubtleImpl::GetUsernameForAttestationClient() const {
  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      [[fallthrough]];
    case VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR:
      return std::string();
    case VerifiedAccessFlow::ENTERPRISE_USER:
      return cryptohome::Identification(GetAccountId()).id();
    default:
      LOG(DFATAL) << "Unsupported Verified Access flow type: " << flow_type_;
      return std::string();
  }
}

// For ENTERPRISE_MACHINE attestation, don't include the certificate of the
// signing key, because the verified access server uses the "stable EMK
// certificate" uploaded to DMServer after enrollment.
bool TpmChallengeKeySubtleImpl::ShouldIncludeSigningKeyCertificate() const {
  if (flow_type_ == VerifiedAccessFlow::ENTERPRISE_MACHINE) {
    return false;
  }
  return true;
}

bool TpmChallengeKeySubtleImpl::ShouldIncludeCustomerId() const {
  // Request to include the customer ID in the challenge response when:
  // * the request is a machine challenge
  // * the request is a user challenge and this is a kiosk session
  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      return true;
    case VerifiedAccessFlow::ENTERPRISE_USER:
      return chromeos::IsKioskSession();
    case VerifiedAccessFlow::DEVICE_TRUST_CONNECTOR:
      return false;
    default:
      NOTREACHED() << "Unsupported Verified Access flow type: " << flow_type_;
  }
}

void TpmChallengeKeySubtleImpl::PrepareKey(bool can_continue) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!can_continue) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kUploadCertificateFailedError));
    return;
  }

  ::attestation::GetEnrollmentPreparationsRequest request;
  AttestationClient::Get()->GetEnrollmentPreparations(
      request,
      base::BindOnce(
          &TpmChallengeKeySubtleImpl::GetEnrollmentPreparationsCallback,
          weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeySubtleImpl::GetEnrollmentPreparationsCallback(
    const ::attestation::GetEnrollmentPreparationsReply& reply) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (reply.status() != ::attestation::STATUS_SUCCESS) {
    std::move(callback_).Run(
        Result::MakeError(reply.status() == ::attestation::STATUS_DBUS_ERROR
                              ? ResultCode::kDbusError
                              : ResultCode::kAttestationServiceInternalError));
    return;
  }

  if (!AttestationClient::IsAttestationPrepared(reply)) {
    chromeos::TpmManagerClient::Get()->GetTpmNonsensitiveStatus(
        ::tpm_manager::GetTpmNonsensitiveStatusRequest(),
        base::BindOnce(
            &TpmChallengeKeySubtleImpl::PrepareKeyErrorHandlerCallback,
            weak_factory_.GetWeakPtr()));
    return;
  }

  ::attestation::GetKeyInfoRequest request;
  request.set_username(GetUsernameForAttestationClient());
  request.set_key_label(key_name_);
  AttestationClient::Get()->GetKeyInfo(
      request, base::BindOnce(&TpmChallengeKeySubtleImpl::DoesKeyExistCallback,
                              weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeySubtleImpl::PrepareKeyErrorHandlerCallback(
    const ::tpm_manager::GetTpmNonsensitiveStatusReply& reply) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (reply.status() != ::tpm_manager::STATUS_SUCCESS) {
    LOG(ERROR) << "Failed to get TPM status; status: " << reply.status();
    std::move(callback_).Run(Result::MakeError(ResultCode::kDbusError));
    return;
  }

  if (reply.is_enabled()) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kResetRequiredError));
  } else {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kAttestationUnsupportedError));
  }
}

void TpmChallengeKeySubtleImpl::DoesKeyExistCallback(
    const ::attestation::GetKeyInfoReply& reply) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (reply.status() != ::attestation::STATUS_SUCCESS &&
      reply.status() != ::attestation::STATUS_INVALID_PARAMETER) {
    std::move(callback_).Run(
        Result::MakeError(reply.status() == ::attestation::STATUS_DBUS_ERROR
                              ? ResultCode::kDbusError
                              : ResultCode::kAttestationServiceInternalError));
    return;
  }

  if (reply.status() == ::attestation::STATUS_SUCCESS) {
    // The key exists. Do nothing more.
    PrepareKeyFinished(reply);
    return;
  }

  // The key does not exist. Create a new key and have it signed by PCA.
  if (IsUserConsentRequired(flow_type_)) {
    // We should ask the user explicitly before sending any private
    // information to PCA.
    AskForUserConsent(
        base::BindOnce(&TpmChallengeKeySubtleImpl::AskForUserConsentCallback,
                       weak_factory_.GetWeakPtr()));
  } else {
    // User consent is not required. Skip to the next step.
    AskForUserConsentCallback(true);
  }
}

void TpmChallengeKeySubtleImpl::AskForUserConsent(
    base::OnceCallback<void(bool)> callback) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // TODO(davidyu): right now we just simply reject the request before we have
  // a way to ask for user consent.
  std::move(callback).Run(false);
}

void TpmChallengeKeySubtleImpl::AskForUserConsentCallback(bool result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!result) {
    // The user rejects the request.
    std::move(callback_).Run(Result::MakeError(ResultCode::kUserRejectedError));
    return;
  }

  // Generate a new key and have it signed by PCA.
  attestation_flow_->GetCertificate(
      /*certificate_profile=*/GetCertificateProfile(),
      /*account_id=*/GetAccountIdForAttestationFlow(),
      /*request_origin=*/std::string(),  // Not used.
      /*force_new_key=*/true, /*key_crypto_type=*/key_crypto_type_,
      /*key_name=*/key_name_, /*profile_specific_data=*/std::nullopt,
      /*callback=*/
      base::BindOnce(&TpmChallengeKeySubtleImpl::GetCertificateCallback,
                     weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeySubtleImpl::GetCertificateCallback(
    AttestationStatus status,
    const std::string& pem_certificate_chain) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (status != ATTESTATION_SUCCESS) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kGetCertificateFailedError));
    return;
  }

  GetPublicKey();
}

void TpmChallengeKeySubtleImpl::GetPublicKey() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  ::attestation::GetKeyInfoRequest request;
  request.set_username(GetUsernameForAttestationClient());
  request.set_key_label(key_name_);
  AttestationClient::Get()->GetKeyInfo(
      request, base::BindOnce(&TpmChallengeKeySubtleImpl::PrepareKeyFinished,
                              weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeySubtleImpl::PrepareKeyFinished(
    const ::attestation::GetKeyInfoReply& reply) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (reply.status() != ::attestation::STATUS_SUCCESS) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kGetPublicKeyFailedError));
    return;
  }

  if (will_register_key_) {
    public_key_ = reply.public_key();
  }

  std::move(callback_).Run(Result::MakePublicKey(reply.public_key()));
}

void TpmChallengeKeySubtleImpl::StartSignChallengeStep(
    const std::string& challenge,
    TpmChallengeKeyCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(callback_.is_null());

  callback_ = std::move(callback);

  // See http://go/chromeos-va-registering-device-wide-keys-support for details
  // about both key names.

  // Name of the key that will be used to sign challenge.
  // ENTERPRISE_MACHINE challenges are signed using a stable key.
  std::string key_name_for_challenge =
      (flow_type_ == VerifiedAccessFlow::ENTERPRISE_MACHINE)
          ? GetDefaultKeyName(flow_type_, key_crypto_type_)
          : key_name_;
  // Name of the key that will be included in SPKAC, it is used only when SPKAC
  // should be included for the flow type ENTERPRISE_MACHINE.
  std::string key_name_for_spkac =
      (will_register_key_ &&
       flow_type_ == VerifiedAccessFlow::ENTERPRISE_MACHINE)
          ? key_name_
          : std::string();

  ::attestation::SignEnterpriseChallengeRequest request;
  request.set_username(GetUsernameForAttestationClient());
  request.set_key_label(key_name_for_challenge);
  request.set_key_name_for_spkac(key_name_for_spkac);
  request.set_domain(GetEmail());
  request.set_device_id(InstallAttributes::Get()->GetDeviceId());
  request.set_include_signed_public_key(will_register_key_);
  request.set_challenge(challenge);
  request.set_va_type(AttestationClient::GetVerifiedAccessServerType());
  request.set_flow_type(flow_type_);
  request.set_include_certificate(ShouldIncludeSigningKeyCertificate());
  if (signals_.has_value()) {
    request.set_device_trust_signals_json(signals_.value());
  }
  request.set_include_customer_id(ShouldIncludeCustomerId());
  AttestationClient::Get()->SignEnterpriseChallenge(
      request, base::BindOnce(&TpmChallengeKeySubtleImpl::SignChallengeCallback,
                              weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeySubtleImpl::SignChallengeCallback(
    const ::attestation::SignEnterpriseChallengeReply& reply) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (reply.status() != ::attestation::STATUS_SUCCESS) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kSignChallengeFailedError));
    return;
  }

  std::move(callback_).Run(
      Result::MakeChallengeResponse(reply.challenge_response()));
}

void TpmChallengeKeySubtleImpl::StartRegisterKeyStep(
    TpmChallengeKeyCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(callback_.is_null());
  DCHECK(will_register_key_);

  callback_ = std::move(callback);

  ::attestation::RegisterKeyWithChapsTokenRequest request;
  request.set_username(GetUsernameForAttestationClient());
  request.set_key_label(key_name_);
  request.set_include_certificates(false);

  AttestationClient::Get()->RegisterKeyWithChapsToken(
      request, base::BindOnce(&TpmChallengeKeySubtleImpl::RegisterKeyCallback,
                              weak_factory_.GetWeakPtr()));
}

void TpmChallengeKeySubtleImpl::RegisterKeyCallback(
    const ::attestation::RegisterKeyWithChapsTokenReply& reply) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (reply.status() != ::attestation::STATUS_SUCCESS) {
    LOG(ERROR) << "Failed to call RegisterKeyWithChapsToken; status: "
               << reply.status();
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kKeyRegistrationFailedError));
    return;
  }

  DCHECK(flow_type_ == VerifiedAccessFlow::ENTERPRISE_MACHINE || profile_);

  platform_keys::KeyPermissionsManager* key_permissions_manager = nullptr;
  switch (flow_type_) {
    case VerifiedAccessFlow::ENTERPRISE_USER:
      key_permissions_manager = platform_keys::KeyPermissionsManagerImpl::
          GetUserPrivateTokenKeyPermissionsManager(profile_);
      break;
    case VerifiedAccessFlow::ENTERPRISE_MACHINE:
      key_permissions_manager = platform_keys::KeyPermissionsManagerImpl::
          GetSystemTokenKeyPermissionsManager();
      break;
    default:
      NOTREACHED();
  }

  DCHECK(!public_key_.empty());
  key_permissions_manager->AllowKeyForUsage(
      base::BindOnce(&TpmChallengeKeySubtleImpl::MarkCorporateKeyCallback,
                     weak_factory_.GetWeakPtr()),
      platform_keys::KeyUsage::kCorporate,
      std::vector<uint8_t>(public_key_.begin(), public_key_.end()));
}

void TpmChallengeKeySubtleImpl::MarkCorporateKeyCallback(
    chromeos::platform_keys::Status status) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (status != chromeos::platform_keys::Status::kSuccess) {
    std::move(callback_).Run(
        Result::MakeError(ResultCode::kMarkCorporateKeyFailedError));
    return;
  }

  std::move(callback_).Run(Result::MakeSuccess());
}

}  // namespace attestation
}  // namespace ash