1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.h"
6
7#include <string>
8
9#include "base/base64.h"
10#include "base/bind.h"
11#include "base/logging.h"
12#include "base/memory/scoped_ptr.h"
13#include "base/strings/string_util.h"
14#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h"
15#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_types.h"
16#include "chromeos/cryptohome/homedir_methods.h"
17#include "chromeos/cryptohome/system_salt_getter.h"
18#include "chromeos/dbus/dbus_thread_manager.h"
19#include "chromeos/dbus/easy_unlock_client.h"
20#include "chromeos/login/auth/key.h"
21#include "crypto/encryptor.h"
22#include "crypto/random.h"
23#include "crypto/symmetric_key.h"
24#include "google_apis/gaia/gaia_auth_util.h"
25#include "third_party/cros_system_api/dbus/service_constants.h"
26
27namespace chromeos {
28
29namespace {
30
31const int kUserKeyByteSize = 16;
32const int kSessionKeyByteSize = 16;
33
34const int kEasyUnlockKeyRevision = 1;
35const int kEasyUnlockKeyPrivileges =
36    cryptohome::PRIV_MOUNT | cryptohome::PRIV_ADD | cryptohome::PRIV_REMOVE;
37
38// TODO(xiyuan): Use real keys. http://crbug.com/409027
39const char kTpmPubKey[] = {
40    0x08, 0x02, 0x1a, 0x88, 0x02, 0x0a, 0x81, 0x02, 0x00, 0xdc, 0xfa, 0x10,
41    0xff, 0xa7, 0x46, 0x65, 0xae, 0xef, 0x87, 0x09, 0x74, 0xea, 0x99, 0xb2,
42    0xce, 0x54, 0x54, 0x7c, 0x67, 0xf4, 0x2a, 0xaa, 0x6d, 0xd0, 0x1a, 0x2e,
43    0xd3, 0x1f, 0xd2, 0xc2, 0x42, 0xaf, 0x5d, 0x96, 0x0b, 0x1f, 0x89, 0x6e,
44    0xfb, 0xa3, 0x54, 0x3d, 0x65, 0x54, 0xb7, 0xb1, 0x26, 0x87, 0xa5, 0xc6,
45    0x88, 0x56, 0x8f, 0x32, 0xe0, 0x26, 0xc5, 0x32, 0xd2, 0x59, 0x93, 0xb9,
46    0x7a, 0x7c, 0x28, 0x42, 0xec, 0x2b, 0x8e, 0x12, 0x35, 0xee, 0xe2, 0x41,
47    0x4d, 0x25, 0x80, 0x6c, 0x6f, 0xba, 0xe4, 0x38, 0x95, 0x4e, 0xba, 0x9d,
48    0x27, 0x55, 0xdf, 0xfe, 0xeb, 0x1b, 0x47, 0x70, 0x09, 0x57, 0x81, 0x5a,
49    0x8a, 0x23, 0x3f, 0x97, 0xb1, 0xa2, 0xc7, 0x14, 0xb3, 0xe2, 0xbe, 0x2e,
50    0x42, 0xd8, 0xbe, 0x30, 0xb1, 0x96, 0x15, 0x82, 0xea, 0x99, 0x48, 0x91,
51    0x0e, 0x0c, 0x79, 0x7c, 0x50, 0xfc, 0x4b, 0xb4, 0x55, 0xf0, 0xfc, 0x45,
52    0xe5, 0xe3, 0x4e, 0x63, 0x96, 0xac, 0x5b, 0x2d, 0x46, 0x23, 0x93, 0x65,
53    0xc7, 0xf3, 0xda, 0xaf, 0x09, 0x09, 0x40, 0x0d, 0x61, 0xcf, 0x9e, 0x0c,
54    0xa8, 0x08, 0x3e, 0xaf, 0x33, 0x5a, 0x6f, 0xce, 0xb6, 0x86, 0x3c, 0x1c,
55    0xc0, 0xcf, 0x5a, 0x17, 0x1a, 0xff, 0x35, 0xd9, 0x7e, 0xcb, 0x60, 0xef,
56    0x25, 0x1c, 0x7e, 0xc2, 0xc8, 0xa5, 0x88, 0x36, 0x1d, 0xc4, 0x12, 0x66,
57    0xa4, 0xb7, 0xed, 0x38, 0xb0, 0x26, 0xce, 0x0d, 0x53, 0x78, 0x64, 0x49,
58    0xdb, 0xb1, 0x1a, 0x06, 0xea, 0x33, 0xcc, 0xf1, 0xec, 0xa5, 0x75, 0x20,
59    0x1e, 0xd1, 0xaa, 0x47, 0x3e, 0xd1, 0x18, 0x7e, 0xc1, 0xd8, 0xa7, 0x44,
60    0xea, 0x34, 0x5b, 0xed, 0x7e, 0xa0, 0x0e, 0xe4, 0xe8, 0x1b, 0xba, 0x46,
61    0x48, 0x60, 0x1d, 0xd5, 0x37, 0xdc, 0x91, 0x01, 0x5d, 0x31, 0xf0, 0xc2,
62    0xc1, 0x10, 0x81, 0x80, 0x04
63};
64
65bool WebSafeBase64Decode(const std::string& encoded, std::string* decoded) {
66  std::string adjusted_encoded = encoded;
67  base::ReplaceChars(adjusted_encoded, "-", "+", &adjusted_encoded);
68  base::ReplaceChars(adjusted_encoded, "_", "/", &adjusted_encoded);
69
70  return base::Base64Decode(adjusted_encoded, decoded);
71}
72
73}  // namespace
74
75/////////////////////////////////////////////////////////////////////////////
76// EasyUnlockCreateKeysOperation::ChallengeCreator
77
78class EasyUnlockCreateKeysOperation::ChallengeCreator {
79 public:
80  typedef base::Callback<void (bool success)> ChallengeCreatedCallback;
81  ChallengeCreator(const std::string& user_key,
82                   const std::string& session_key,
83                   const std::string& tpm_pub_key,
84                   EasyUnlockDeviceKeyData* device,
85                   const ChallengeCreatedCallback& callback);
86  ~ChallengeCreator();
87
88  void Start();
89
90  const std::string& user_key() const { return user_key_; }
91
92 private:
93  void OnEcKeyPairGenerated(const std::string& ec_public_key,
94                            const std::string& ec_private_key);
95  void OnEskGenerated(const std::string& esk);
96
97  void GeneratePayload();
98  void OnPayloadMessageGenerated(const std::string& payload_message);
99  void OnPayloadGenerated(const std::string& payload);
100
101  void OnChallengeGenerated(const std::string& challenge);
102
103  const std::string user_key_;
104  const std::string session_key_;
105  const std::string tpm_pub_key_;
106  EasyUnlockDeviceKeyData* device_;
107  ChallengeCreatedCallback callback_;
108
109  std::string ec_public_key_;
110  std::string esk_;
111
112  // Owned by DBusThreadManager
113  chromeos::EasyUnlockClient* easy_unlock_client_;
114
115  base::WeakPtrFactory<ChallengeCreator> weak_ptr_factory_;
116
117  DISALLOW_COPY_AND_ASSIGN(ChallengeCreator);
118};
119
120EasyUnlockCreateKeysOperation::ChallengeCreator::ChallengeCreator(
121    const std::string& user_key,
122    const std::string& session_key,
123    const std::string& tpm_pub_key,
124    EasyUnlockDeviceKeyData* device,
125    const ChallengeCreatedCallback& callback)
126    : user_key_(user_key),
127      session_key_(session_key),
128      tpm_pub_key_(tpm_pub_key),
129      device_(device),
130      callback_(callback),
131      easy_unlock_client_(
132          chromeos::DBusThreadManager::Get()->GetEasyUnlockClient()),
133      weak_ptr_factory_(this) {
134}
135
136EasyUnlockCreateKeysOperation::ChallengeCreator::~ChallengeCreator() {
137}
138
139void EasyUnlockCreateKeysOperation::ChallengeCreator::Start() {
140  easy_unlock_client_->GenerateEcP256KeyPair(
141      base::Bind(&ChallengeCreator::OnEcKeyPairGenerated,
142                 weak_ptr_factory_.GetWeakPtr()));
143}
144
145void EasyUnlockCreateKeysOperation::ChallengeCreator::OnEcKeyPairGenerated(
146    const std::string& ec_private_key,
147    const std::string& ec_public_key) {
148  if (ec_private_key.empty() || ec_public_key.empty()) {
149    LOG(ERROR) << "Easy unlock failed to generate ec key pair.";
150    callback_.Run(false);
151    return;
152  }
153
154  std::string device_pub_key;
155  if (!WebSafeBase64Decode(device_->public_key, &device_pub_key)) {
156    LOG(ERROR) << "Easy unlock failed to decode device public key.";
157    callback_.Run(false);
158    return;
159  }
160
161  ec_public_key_ = ec_public_key;
162  easy_unlock_client_->PerformECDHKeyAgreement(
163      ec_private_key,
164      device_pub_key,
165      base::Bind(&ChallengeCreator::OnEskGenerated,
166                 weak_ptr_factory_.GetWeakPtr()));
167}
168
169void EasyUnlockCreateKeysOperation::ChallengeCreator::OnEskGenerated(
170    const std::string& esk) {
171  if (esk.empty()) {
172    LOG(ERROR) << "Easy unlock failed to generate challenge esk.";
173    callback_.Run(false);
174    return;
175  }
176
177  esk_ = esk;
178  GeneratePayload();
179}
180
181void EasyUnlockCreateKeysOperation::ChallengeCreator::GeneratePayload() {
182  // Work around to get HeaderAndBody bytes to use as challenge payload.
183  EasyUnlockClient::CreateSecureMessageOptions options;
184  options.key = esk_;
185  // TODO(xiyuan, tbarzic): Wrap in a GenericPublicKey proto.
186  options.verification_key_id = tpm_pub_key_;
187  options.encryption_type = easy_unlock::kEncryptionTypeAES256CBC;
188  options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;
189
190  easy_unlock_client_->CreateSecureMessage(
191      session_key_,
192      options,
193      base::Bind(&ChallengeCreator::OnPayloadMessageGenerated,
194                 weak_ptr_factory_.GetWeakPtr()));
195}
196
197void
198EasyUnlockCreateKeysOperation::ChallengeCreator::OnPayloadMessageGenerated(
199    const std::string& payload_message) {
200  EasyUnlockClient::UnwrapSecureMessageOptions options;
201  options.key = esk_;
202  options.encryption_type = easy_unlock::kEncryptionTypeAES256CBC;
203  options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;
204
205  easy_unlock_client_->UnwrapSecureMessage(
206      payload_message,
207      options,
208      base::Bind(&ChallengeCreator::OnPayloadGenerated,
209                 weak_ptr_factory_.GetWeakPtr()));
210}
211
212void EasyUnlockCreateKeysOperation::ChallengeCreator::OnPayloadGenerated(
213    const std::string& payload) {
214  if (payload.empty()) {
215    LOG(ERROR) << "Easy unlock failed to generate challenge payload.";
216    callback_.Run(false);
217    return;
218  }
219
220  EasyUnlockClient::CreateSecureMessageOptions options;
221  options.key = esk_;
222  options.decryption_key_id = ec_public_key_;
223  options.encryption_type = easy_unlock::kEncryptionTypeAES256CBC;
224  options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;
225
226  easy_unlock_client_->CreateSecureMessage(
227      payload,
228      options,
229      base::Bind(&ChallengeCreator::OnChallengeGenerated,
230                 weak_ptr_factory_.GetWeakPtr()));
231}
232
233void EasyUnlockCreateKeysOperation::ChallengeCreator::OnChallengeGenerated(
234    const std::string& challenge) {
235  if (challenge.empty()) {
236    LOG(ERROR) << "Easy unlock failed to generate challenge.";
237    callback_.Run(false);
238    return;
239  }
240
241  device_->challenge = challenge;
242  callback_.Run(true);
243}
244
245/////////////////////////////////////////////////////////////////////////////
246// EasyUnlockCreateKeysOperation
247
248EasyUnlockCreateKeysOperation::EasyUnlockCreateKeysOperation(
249    const UserContext& user_context,
250    const EasyUnlockDeviceKeyDataList& devices,
251    const CreateKeysCallback& callback)
252    : user_context_(user_context),
253      devices_(devices),
254      callback_(callback),
255      key_creation_index_(0),
256      weak_ptr_factory_(this) {
257  // Must have the secret and callback.
258  DCHECK(!user_context_.GetKey()->GetSecret().empty());
259  DCHECK(!callback_.is_null());
260}
261
262EasyUnlockCreateKeysOperation::~EasyUnlockCreateKeysOperation() {
263}
264
265void EasyUnlockCreateKeysOperation::Start() {
266  key_creation_index_ = 0;
267  CreateKeyForDeviceAtIndex(key_creation_index_);
268}
269
270void EasyUnlockCreateKeysOperation::CreateKeyForDeviceAtIndex(size_t index) {
271  DCHECK_GE(index, 0u);
272  if (index == devices_.size()) {
273    callback_.Run(true);
274    return;
275  }
276
277  std::string user_key;
278  crypto::RandBytes(WriteInto(&user_key, kUserKeyByteSize + 1),
279                    kUserKeyByteSize);
280
281  scoped_ptr<crypto::SymmetricKey> session_key(
282      crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES,
283                                              kSessionKeyByteSize * 8));
284
285  std::string iv(kSessionKeyByteSize, ' ');
286  crypto::Encryptor encryptor;
287  if (!encryptor.Init(session_key.get(), crypto::Encryptor::CBC, iv)) {
288    LOG(ERROR) << "Easy unlock failed to init encryptor for key creation.";
289    callback_.Run(false);
290    return;
291  }
292
293  EasyUnlockDeviceKeyData* device = &devices_[index];
294  if (!encryptor.Encrypt(user_key, &device->wrapped_secret)) {
295    LOG(ERROR) << "Easy unlock failed to encrypt user key for key creation.";
296    callback_.Run(false);
297    return;
298  }
299
300  std::string raw_session_key;
301  session_key->GetRawKey(&raw_session_key);
302
303  challenge_creator_.reset(new ChallengeCreator(
304      user_key,
305      raw_session_key,
306      std::string(kTpmPubKey, arraysize(kTpmPubKey)),
307      device,
308      base::Bind(&EasyUnlockCreateKeysOperation::OnChallengeCreated,
309                 weak_ptr_factory_.GetWeakPtr(),
310                 index)));
311  challenge_creator_->Start();
312}
313
314void EasyUnlockCreateKeysOperation::OnChallengeCreated(size_t index,
315                                                       bool success) {
316  DCHECK_EQ(key_creation_index_, index);
317
318  if (!success) {
319    LOG(ERROR) << "Easy unlock failed to create challenge for key creation.";
320    callback_.Run(false);
321    return;
322  }
323
324  SystemSaltGetter::Get()->GetSystemSalt(
325      base::Bind(&EasyUnlockCreateKeysOperation::OnGetSystemSalt,
326                 weak_ptr_factory_.GetWeakPtr(),
327                 index));
328}
329
330void EasyUnlockCreateKeysOperation::OnGetSystemSalt(
331    size_t index,
332    const std::string& system_salt) {
333  DCHECK_EQ(key_creation_index_, index);
334  if (system_salt.empty()) {
335    LOG(ERROR) << "Easy unlock failed to get system salt for key creation.";
336    callback_.Run(false);
337    return;
338  }
339
340  Key user_key(challenge_creator_->user_key());
341  user_key.Transform(Key::KEY_TYPE_SALTED_SHA256_TOP_HALF, system_salt);
342
343  EasyUnlockDeviceKeyData* device = &devices_[index];
344  cryptohome::KeyDefinition key_def(
345      user_key.GetSecret(),
346      EasyUnlockKeyManager::GetKeyLabel(index),
347      kEasyUnlockKeyPrivileges);
348  key_def.revision = kEasyUnlockKeyRevision;
349  key_def.provider_data.push_back(cryptohome::KeyDefinition::ProviderData(
350      kEasyUnlockKeyMetaNameBluetoothAddress, device->bluetooth_address));
351  key_def.provider_data.push_back(cryptohome::KeyDefinition::ProviderData(
352      kEasyUnlockKeyMetaNamePsk, device->psk));
353  key_def.provider_data.push_back(cryptohome::KeyDefinition::ProviderData(
354      kEasyUnlockKeyMetaNamePubKey, device->public_key));
355  key_def.provider_data.push_back(cryptohome::KeyDefinition::ProviderData(
356      kEasyUnlockKeyMetaNameChallenge, device->challenge));
357  key_def.provider_data.push_back(cryptohome::KeyDefinition::ProviderData(
358      kEasyUnlockKeyMetaNameWrappedSecret, device->wrapped_secret));
359
360  // Add cryptohome key.
361  std::string canonicalized =
362      gaia::CanonicalizeEmail(user_context_.GetUserID());
363  cryptohome::Identification id(canonicalized);
364
365  scoped_ptr<Key> auth_key(new Key(*user_context_.GetKey()));
366  if (auth_key->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN)
367    auth_key->Transform(Key::KEY_TYPE_SALTED_SHA256_TOP_HALF, system_salt);
368
369  cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel());
370  cryptohome::HomedirMethods::GetInstance()->AddKeyEx(
371      id,
372      auth,
373      key_def,
374      true,  // clobber
375      base::Bind(&EasyUnlockCreateKeysOperation::OnKeyCreated,
376                 weak_ptr_factory_.GetWeakPtr(),
377                 index,
378                 user_key));
379}
380
381void EasyUnlockCreateKeysOperation::OnKeyCreated(
382    size_t index,
383    const Key& user_key,
384    bool success,
385    cryptohome::MountError return_code) {
386  DCHECK_EQ(key_creation_index_, index);
387
388  if (!success) {
389    LOG(ERROR) << "Easy unlock failed to create key, code=" << return_code;
390    callback_.Run(false);
391    return;
392  }
393
394  // If the key associated with the current context changed (i.e. in the case
395  // the current signin flow was Easy signin), update the user context.
396  if (user_context_.GetAuthFlow() == UserContext::AUTH_FLOW_EASY_UNLOCK &&
397      user_context_.GetKey()->GetLabel() ==
398          EasyUnlockKeyManager::GetKeyLabel(key_creation_index_)) {
399    user_context_.SetKey(user_key);
400  }
401
402  ++key_creation_index_;
403  CreateKeyForDeviceAtIndex(key_creation_index_);
404}
405
406}  // namespace chromeos
407