summaryrefslogtreecommitdiff
path: root/chromium/components/cryptauth/cryptauth_enroller_impl.cc
blob: 88e025f538585cfa4481be105764870bf70a2d85 (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
// Copyright 2015 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 "components/cryptauth/cryptauth_enroller_impl.h"

#include <utility>

#include "base/bind.h"
#include "base/metrics/histogram_macros.h"
#include "chromeos/components/proximity_auth/logging/logging.h"
#include "components/cryptauth/cryptauth_client_impl.h"
#include "components/cryptauth/cryptauth_enrollment_utils.h"
#include "components/cryptauth/secure_message_delegate.h"
#include "crypto/sha2.h"

namespace cryptauth {

namespace {

// A successful SetupEnrollment or FinishEnrollment response should contain this
// status string.
const char kResponseStatusOk[] = "ok";

// The name of the "gcmV1" protocol that the enrolling device supports.
const char kSupportedEnrollmentTypeGcmV1[] = "gcmV1";

// The version field of the GcmMetadata message.
const int kGCMMetadataVersion = 1;

// Returns true if |device_info| contains the required fields for enrollment.
bool ValidateDeviceInfo(const GcmDeviceInfo& device_info) {
  if (!device_info.has_long_device_id()) {
    PA_LOG(ERROR) << "Expected long_device_id field in GcmDeviceInfo.";
    return false;
  }

  if (!device_info.has_device_type()) {
    PA_LOG(ERROR) << "Expected device_type field in GcmDeviceInfo.";
    return false;
  }

  return true;
}

// Creates the public metadata to put in the SecureMessage that is sent to the
// server with the FinishEnrollment request.
std::string CreateEnrollmentPublicMetadata() {
  GcmMetadata metadata;
  metadata.set_version(kGCMMetadataVersion);
  metadata.set_type(MessageType::ENROLLMENT);
  return metadata.SerializeAsString();
}

}  // namespace

CryptAuthEnrollerImpl::CryptAuthEnrollerImpl(
    CryptAuthClientFactory* client_factory,
    std::unique_ptr<SecureMessageDelegate> secure_message_delegate)
    : client_factory_(client_factory),
      secure_message_delegate_(std::move(secure_message_delegate)),
      weak_ptr_factory_(this) {}

CryptAuthEnrollerImpl::~CryptAuthEnrollerImpl() {
}

void CryptAuthEnrollerImpl::Enroll(
    const std::string& user_public_key,
    const std::string& user_private_key,
    const GcmDeviceInfo& device_info,
    InvocationReason invocation_reason,
    const EnrollmentFinishedCallback& callback) {
  if (!callback_.is_null()) {
    PA_LOG(ERROR) << "Enroll() already called. Do not reuse.";
    callback.Run(false);
    return;
  }

  user_public_key_ = user_public_key;
  user_private_key_ = user_private_key;
  device_info_ = device_info;
  invocation_reason_ = invocation_reason;
  callback_ = callback;

  if (!ValidateDeviceInfo(device_info)) {
    callback.Run(false);
    return;
  }

  secure_message_delegate_->GenerateKeyPair(
      base::Bind(&CryptAuthEnrollerImpl::OnKeyPairGenerated,
                 weak_ptr_factory_.GetWeakPtr()));
}

void CryptAuthEnrollerImpl::OnKeyPairGenerated(const std::string& public_key,
                                               const std::string& private_key) {
  PA_LOG(INFO) << "Ephemeral key pair generated, calling SetupEnrollment API.";
  session_public_key_ = public_key;
  session_private_key_ = private_key;

  cryptauth_client_ = client_factory_->CreateInstance();
  SetupEnrollmentRequest request;
  request.add_types(kSupportedEnrollmentTypeGcmV1);
  request.set_invocation_reason(invocation_reason_);
  cryptauth_client_->SetupEnrollment(
      request, base::Bind(&CryptAuthEnrollerImpl::OnSetupEnrollmentSuccess,
                          weak_ptr_factory_.GetWeakPtr()),
      base::Bind(&CryptAuthEnrollerImpl::OnSetupEnrollmentFailure,
                 weak_ptr_factory_.GetWeakPtr()));
}

void CryptAuthEnrollerImpl::OnSetupEnrollmentSuccess(
    const SetupEnrollmentResponse& response) {
  if (response.status() != kResponseStatusOk) {
    PA_LOG(WARNING) << "Unexpected status for SetupEnrollment: "
                    << response.status();
    callback_.Run(false);
    return;
  }

  if (response.infos_size() == 0) {
    PA_LOG(ERROR) << "No response info returned by server for SetupEnrollment";
    callback_.Run(false);
    return;
  }

  PA_LOG(INFO) << "SetupEnrollment request succeeded: deriving symmetric key.";
  setup_info_ = response.infos(0);
  device_info_.set_enrollment_session_id(setup_info_.enrollment_session_id());

  secure_message_delegate_->DeriveKey(
      session_private_key_, setup_info_.server_ephemeral_key(),
      base::Bind(&CryptAuthEnrollerImpl::OnKeyDerived,
                 weak_ptr_factory_.GetWeakPtr()));
}

void CryptAuthEnrollerImpl::OnSetupEnrollmentFailure(
    NetworkRequestError error) {
  PA_LOG(WARNING) << "SetupEnrollment API failed with error: " << error;
  callback_.Run(false);
}

void CryptAuthEnrollerImpl::OnKeyDerived(const std::string& symmetric_key) {
  PA_LOG(INFO) << "Derived symmetric key, "
               << "encrypting enrollment data for upload.";

  // Make sure we're enrolling the same public key used below to sign the
  // secure message.
  device_info_.set_user_public_key(user_public_key_);
  device_info_.set_key_handle(user_public_key_);

  // Hash the symmetric key and add it to the |device_info_| to be uploaded.
  device_info_.set_device_master_key_hash(
      crypto::SHA256HashString(symmetric_key));

  // The server verifies that the access token set here and in the header
  // of the FinishEnrollment() request are the same.
  device_info_.set_oauth_token(cryptauth_client_->GetAccessTokenUsed());
  PA_LOG(INFO) << "Using access token: " << device_info_.oauth_token();

  symmetric_key_ = symmetric_key;
  SecureMessageDelegate::CreateOptions options;
  options.encryption_scheme = securemessage::NONE;
  options.signature_scheme = securemessage::ECDSA_P256_SHA256;
  options.verification_key_id = user_public_key_;

  // The inner message contains the signed device information that will be
  // sent to CryptAuth.
  secure_message_delegate_->CreateSecureMessage(
      device_info_.SerializeAsString(), user_private_key_, options,
      base::Bind(&CryptAuthEnrollerImpl::OnInnerSecureMessageCreated,
                 weak_ptr_factory_.GetWeakPtr()));
}

void CryptAuthEnrollerImpl::OnInnerSecureMessageCreated(
    const std::string& inner_message) {
  if (inner_message.empty()) {
    PA_LOG(ERROR) << "Error creating inner message";
    callback_.Run(false);
    return;
  }

  SecureMessageDelegate::CreateOptions options;
  options.encryption_scheme = securemessage::AES_256_CBC;
  options.signature_scheme = securemessage::HMAC_SHA256;
  options.public_metadata = CreateEnrollmentPublicMetadata();

  // The outer message encrypts and signs the inner message with the derived
  // symmetric session key.
  secure_message_delegate_->CreateSecureMessage(
      inner_message, symmetric_key_, options,
      base::Bind(&CryptAuthEnrollerImpl::OnOuterSecureMessageCreated,
                 weak_ptr_factory_.GetWeakPtr()));
}

void CryptAuthEnrollerImpl::OnOuterSecureMessageCreated(
    const std::string& outer_message) {
  PA_LOG(INFO) << "SecureMessage created, calling FinishEnrollment API.";

  FinishEnrollmentRequest request;
  request.set_enrollment_session_id(setup_info_.enrollment_session_id());
  request.set_enrollment_message(outer_message);
  request.set_device_ephemeral_key(session_public_key_);
  request.set_invocation_reason(invocation_reason_);

  cryptauth_client_ = client_factory_->CreateInstance();
  cryptauth_client_->FinishEnrollment(
      request, base::Bind(&CryptAuthEnrollerImpl::OnFinishEnrollmentSuccess,
                          weak_ptr_factory_.GetWeakPtr()),
      base::Bind(&CryptAuthEnrollerImpl::OnFinishEnrollmentFailure,
                 weak_ptr_factory_.GetWeakPtr()));
}

void CryptAuthEnrollerImpl::OnFinishEnrollmentSuccess(
    const FinishEnrollmentResponse& response) {
  const bool success = response.status() == kResponseStatusOk;

  if (!success) {
    PA_LOG(WARNING) << "Unexpected status for FinishEnrollment: "
                    << response.status();
  }

  UMA_HISTOGRAM_BOOLEAN("CryptAuth.Enrollment.Result", success);
  callback_.Run(success);
}

void CryptAuthEnrollerImpl::OnFinishEnrollmentFailure(
    NetworkRequestError error) {
  PA_LOG(WARNING) << "FinishEnrollment API failed with error: " << error;
  callback_.Run(false);
}

}  // namespace cryptauth