1 // Copyright 2012 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.
5 #include "sync/internal_api/sync_encryption_handler_impl.h"
10 #include "base/base64.h"
11 #include "base/bind.h"
12 #include "base/json/json_string_value_serializer.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/time/time.h"
16 #include "base/tracked_objects.h"
17 #include "sync/internal_api/public/read_node.h"
18 #include "sync/internal_api/public/read_transaction.h"
19 #include "sync/internal_api/public/user_share.h"
20 #include "sync/internal_api/public/util/experiments.h"
21 #include "sync/internal_api/public/util/sync_string_conversions.h"
22 #include "sync/internal_api/public/write_node.h"
23 #include "sync/internal_api/public/write_transaction.h"
24 #include "sync/protocol/encryption.pb.h"
25 #include "sync/protocol/nigori_specifics.pb.h"
26 #include "sync/protocol/sync.pb.h"
27 #include "sync/syncable/directory.h"
28 #include "sync/syncable/entry.h"
29 #include "sync/syncable/mutable_entry.h"
30 #include "sync/syncable/nigori_util.h"
31 #include "sync/syncable/syncable_base_transaction.h"
32 #include "sync/syncable/syncable_model_neutral_write_transaction.h"
33 #include "sync/syncable/syncable_write_transaction.h"
34 #include "sync/util/cryptographer.h"
35 #include "sync/util/encryptor.h"
36 #include "sync/util/time.h"
42 // The maximum number of times we will automatically overwrite the nigori node
43 // because the encryption keys don't match (per chrome instantiation).
44 // We protect ourselves against nigori rollbacks, but it's possible two
45 // different clients might have contrasting view of what the nigori node state
46 // should be, in which case they might ping pong (see crbug.com/119207).
47 static const int kNigoriOverwriteLimit
= 10;
49 // Enumeration of nigori keystore migration results (for use in UMA stats).
50 enum NigoriMigrationResult
{
51 FAILED_TO_SET_DEFAULT_KEYSTORE
,
52 FAILED_TO_SET_NONDEFAULT_KEYSTORE
,
53 FAILED_TO_EXTRACT_DECRYPTOR
,
54 FAILED_TO_EXTRACT_KEYBAG
,
55 MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT
,
56 MIGRATION_SUCCESS_KEYSTORE_DEFAULT
,
57 MIGRATION_SUCCESS_FROZEN_IMPLICIT
,
58 MIGRATION_SUCCESS_CUSTOM
,
59 MIGRATION_RESULT_SIZE
,
62 enum NigoriMigrationState
{
64 NOT_MIGRATED_CRYPTO_NOT_READY
,
65 NOT_MIGRATED_NO_KEYSTORE_KEY
,
66 NOT_MIGRATED_UNKNOWN_REASON
,
70 // The new passphrase state is sufficient to determine whether a nigori node
71 // is migrated to support keystore encryption. In addition though, we also
72 // want to verify the conditions for proper keystore encryption functionality.
73 // 1. Passphrase type is set.
74 // 2. Frozen keybag is true
75 // 3. If passphrase state is keystore, keystore_decryptor_token is set.
76 bool IsNigoriMigratedToKeystore(const sync_pb::NigoriSpecifics
& nigori
) {
77 if (!nigori
.has_passphrase_type())
79 if (!nigori
.keybag_is_frozen())
81 if (nigori
.passphrase_type() ==
82 sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE
)
84 if (nigori
.passphrase_type() ==
85 sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE
&&
86 nigori
.keystore_decryptor_token().blob().empty())
91 PassphraseType
ProtoPassphraseTypeToEnum(
92 sync_pb::NigoriSpecifics::PassphraseType type
) {
94 case sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE
:
95 return IMPLICIT_PASSPHRASE
;
96 case sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE
:
97 return KEYSTORE_PASSPHRASE
;
98 case sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE
:
99 return CUSTOM_PASSPHRASE
;
100 case sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE
:
101 return FROZEN_IMPLICIT_PASSPHRASE
;
104 return IMPLICIT_PASSPHRASE
;
108 sync_pb::NigoriSpecifics::PassphraseType
109 EnumPassphraseTypeToProto(PassphraseType type
) {
111 case IMPLICIT_PASSPHRASE
:
112 return sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE
;
113 case KEYSTORE_PASSPHRASE
:
114 return sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE
;
115 case CUSTOM_PASSPHRASE
:
116 return sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE
;
117 case FROZEN_IMPLICIT_PASSPHRASE
:
118 return sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE
;
121 return sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE
;
125 bool IsExplicitPassphrase(PassphraseType type
) {
126 return type
== CUSTOM_PASSPHRASE
|| type
== FROZEN_IMPLICIT_PASSPHRASE
;
129 // Keystore Bootstrap Token helper methods.
130 // The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
131 // strings, with the current keystore key as the last value in the list.
132 std::string
PackKeystoreBootstrapToken(
133 const std::vector
<std::string
>& old_keystore_keys
,
134 const std::string
& current_keystore_key
,
135 Encryptor
* encryptor
) {
136 if (current_keystore_key
.empty())
137 return std::string();
139 base::ListValue keystore_key_values
;
140 for (size_t i
= 0; i
< old_keystore_keys
.size(); ++i
)
141 keystore_key_values
.AppendString(old_keystore_keys
[i
]);
142 keystore_key_values
.AppendString(current_keystore_key
);
144 // Update the bootstrap token.
145 // The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
146 // strings, with the current keystore key as the last value in the list.
147 std::string serialized_keystores
;
148 JSONStringValueSerializer
json(&serialized_keystores
);
149 json
.Serialize(keystore_key_values
);
150 std::string encrypted_keystores
;
151 encryptor
->EncryptString(serialized_keystores
,
152 &encrypted_keystores
);
153 std::string keystore_bootstrap
;
154 base::Base64Encode(encrypted_keystores
, &keystore_bootstrap
);
155 return keystore_bootstrap
;
158 bool UnpackKeystoreBootstrapToken(
159 const std::string
& keystore_bootstrap_token
,
160 Encryptor
* encryptor
,
161 std::vector
<std::string
>* old_keystore_keys
,
162 std::string
* current_keystore_key
) {
163 if (keystore_bootstrap_token
.empty())
165 std::string base64_decoded_keystore_bootstrap
;
166 if (!base::Base64Decode(keystore_bootstrap_token
,
167 &base64_decoded_keystore_bootstrap
)) {
170 std::string decrypted_keystore_bootstrap
;
171 if (!encryptor
->DecryptString(base64_decoded_keystore_bootstrap
,
172 &decrypted_keystore_bootstrap
)) {
176 JSONStringValueDeserializer
json(decrypted_keystore_bootstrap
);
177 scoped_ptr
<base::Value
> deserialized_keystore_keys(
178 json
.Deserialize(NULL
, NULL
));
179 if (!deserialized_keystore_keys
)
181 base::ListValue
* internal_list_value
= NULL
;
182 if (!deserialized_keystore_keys
->GetAsList(&internal_list_value
))
184 int number_of_keystore_keys
= internal_list_value
->GetSize();
185 if (!internal_list_value
->GetString(number_of_keystore_keys
- 1,
186 current_keystore_key
)) {
189 old_keystore_keys
->resize(number_of_keystore_keys
- 1);
190 for (int i
= 0; i
< number_of_keystore_keys
- 1; ++i
)
191 internal_list_value
->GetString(i
, &(*old_keystore_keys
)[i
]);
197 SyncEncryptionHandlerImpl::Vault::Vault(
198 Encryptor
* encryptor
,
199 ModelTypeSet encrypted_types
)
200 : cryptographer(encryptor
),
201 encrypted_types(encrypted_types
) {
204 SyncEncryptionHandlerImpl::Vault::~Vault() {
207 SyncEncryptionHandlerImpl::SyncEncryptionHandlerImpl(
208 UserShare
* user_share
,
209 Encryptor
* encryptor
,
210 const std::string
& restored_key_for_bootstrapping
,
211 const std::string
& restored_keystore_key_for_bootstrapping
,
212 PassphraseTransitionClearDataOption clear_data_option
)
213 : user_share_(user_share
),
214 vault_unsafe_(encryptor
, SensitiveTypes()),
215 encrypt_everything_(false),
216 passphrase_type_(IMPLICIT_PASSPHRASE
),
217 nigori_overwrite_count_(0),
218 clear_data_option_(clear_data_option
),
219 weak_ptr_factory_(this) {
220 // Restore the cryptographer's previous keys. Note that we don't add the
221 // keystore keys into the cryptographer here, in case a migration was pending.
222 vault_unsafe_
.cryptographer
.Bootstrap(restored_key_for_bootstrapping
);
224 // If this fails, we won't have a valid keystore key, and will simply request
225 // new ones from the server on the next DownloadUpdates.
226 UnpackKeystoreBootstrapToken(
227 restored_keystore_key_for_bootstrapping
,
233 SyncEncryptionHandlerImpl::~SyncEncryptionHandlerImpl() {}
235 void SyncEncryptionHandlerImpl::AddObserver(Observer
* observer
) {
236 DCHECK(thread_checker_
.CalledOnValidThread());
237 DCHECK(!observers_
.HasObserver(observer
));
238 observers_
.AddObserver(observer
);
241 void SyncEncryptionHandlerImpl::RemoveObserver(Observer
* observer
) {
242 DCHECK(thread_checker_
.CalledOnValidThread());
243 DCHECK(observers_
.HasObserver(observer
));
244 observers_
.RemoveObserver(observer
);
247 void SyncEncryptionHandlerImpl::Init() {
248 DCHECK(thread_checker_
.CalledOnValidThread());
249 WriteTransaction
trans(FROM_HERE
, user_share_
);
250 WriteNode
node(&trans
);
252 if (node
.InitTypeRoot(NIGORI
) != BaseNode::INIT_OK
)
254 if (!ApplyNigoriUpdateImpl(node
.GetNigoriSpecifics(),
255 trans
.GetWrappedTrans())) {
256 WriteEncryptionStateToNigori(&trans
);
259 UMA_HISTOGRAM_ENUMERATION("Sync.PassphraseType",
261 PASSPHRASE_TYPE_SIZE
);
263 bool has_pending_keys
= UnlockVault(
264 trans
.GetWrappedTrans()).cryptographer
.has_pending_keys();
265 bool is_ready
= UnlockVault(
266 trans
.GetWrappedTrans()).cryptographer
.is_ready();
267 // Log the state of the cryptographer regardless of migration state.
268 UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerReady", is_ready
);
269 UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerPendingKeys", has_pending_keys
);
270 if (IsNigoriMigratedToKeystore(node
.GetNigoriSpecifics())) {
271 // This account has a nigori node that has been migrated to support
273 UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
275 MIGRATION_STATE_SIZE
);
276 if (has_pending_keys
&& passphrase_type_
== KEYSTORE_PASSPHRASE
) {
277 // If this is happening, it means the keystore decryptor is either
278 // undecryptable with the available keystore keys or does not match the
279 // nigori keybag's encryption key. Otherwise we're simply missing the
281 UMA_HISTOGRAM_BOOLEAN("Sync.KeystoreDecryptionFailed",
282 !keystore_key_
.empty());
284 } else if (!is_ready
) {
285 // Migration cannot occur until the cryptographer is ready (initialized
286 // with GAIA password and any pending keys resolved).
287 UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
288 NOT_MIGRATED_CRYPTO_NOT_READY
,
289 MIGRATION_STATE_SIZE
);
290 } else if (keystore_key_
.empty()) {
291 // The client has no keystore key, either because it is not yet enabled or
292 // the server is not sending a valid keystore key.
293 UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
294 NOT_MIGRATED_NO_KEYSTORE_KEY
,
295 MIGRATION_STATE_SIZE
);
297 // If the above conditions have been met and the nigori node is still not
298 // migrated, something failed in the migration process.
299 UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
300 NOT_MIGRATED_UNKNOWN_REASON
,
301 MIGRATION_STATE_SIZE
);
305 // Always trigger an encrypted types and cryptographer state change event at
306 // init time so observers get the initial values.
308 Observer
, observers_
,
309 OnEncryptedTypesChanged(
310 UnlockVault(trans
.GetWrappedTrans()).encrypted_types
,
311 encrypt_everything_
));
313 SyncEncryptionHandler::Observer
,
315 OnCryptographerStateChanged(
316 &UnlockVaultMutable(trans
.GetWrappedTrans())->cryptographer
));
318 // If the cryptographer is not ready (either it has pending keys or we
319 // failed to initialize it), we don't want to try and re-encrypt the data.
320 // If we had encrypted types, the DataTypeManager will block, preventing
321 // sync from happening until the the passphrase is provided.
322 if (UnlockVault(trans
.GetWrappedTrans()).cryptographer
.is_ready())
323 ReEncryptEverything(&trans
);
326 void SyncEncryptionHandlerImpl::SetEncryptionPassphrase(
327 const std::string
& passphrase
,
329 DCHECK(thread_checker_
.CalledOnValidThread());
330 // We do not accept empty passphrases.
331 if (passphrase
.empty()) {
332 NOTREACHED() << "Cannot encrypt with an empty passphrase.";
336 // All accesses to the cryptographer are protected by a transaction.
337 WriteTransaction
trans(FROM_HERE
, user_share_
);
338 KeyParams key_params
= {"localhost", "dummy", passphrase
};
339 WriteNode
node(&trans
);
340 if (node
.InitTypeRoot(NIGORI
) != BaseNode::INIT_OK
) {
345 Cryptographer
* cryptographer
=
346 &UnlockVaultMutable(trans
.GetWrappedTrans())->cryptographer
;
348 // Once we've migrated to keystore, the only way to set a passphrase for
349 // encryption is to set a custom passphrase.
350 if (IsNigoriMigratedToKeystore(node
.GetNigoriSpecifics())) {
352 // The user is setting a new implicit passphrase. At this point we don't
353 // care, so drop it on the floor. This is safe because if we have a
354 // migrated nigori node, then we don't need to create an initial
356 LOG(WARNING
) << "Ignoring new implicit passphrase. Keystore migration "
357 << "already performed.";
360 // Will fail if we already have an explicit passphrase or we have pending
362 SetCustomPassphrase(passphrase
, &trans
, &node
);
364 // When keystore migration occurs, the "CustomEncryption" UMA stat must be
366 UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
370 std::string bootstrap_token
;
371 sync_pb::EncryptedData pending_keys
;
372 if (cryptographer
->has_pending_keys())
373 pending_keys
= cryptographer
->GetPendingKeys();
374 bool success
= false;
376 // There are six cases to handle here:
377 // 1. The user has no pending keys and is setting their current GAIA password
378 // as the encryption passphrase. This happens either during first time sync
379 // with a clean profile, or after re-authenticating on a profile that was
380 // already signed in with the cryptographer ready.
381 // 2. The user has no pending keys, and is overwriting an (already provided)
382 // implicit passphrase with an explicit (custom) passphrase.
383 // 3. The user has pending keys for an explicit passphrase that is somehow set
384 // to their current GAIA passphrase.
385 // 4. The user has pending keys encrypted with their current GAIA passphrase
386 // and the caller passes in the current GAIA passphrase.
387 // 5. The user has pending keys encrypted with an older GAIA passphrase
388 // and the caller passes in the current GAIA passphrase.
389 // 6. The user has previously done encryption with an explicit passphrase.
390 // Furthermore, we enforce the fact that the bootstrap encryption token will
391 // always be derived from the newest GAIA password if the account is using
392 // an implicit passphrase (even if the data is encrypted with an old GAIA
393 // password). If the account is using an explicit (custom) passphrase, the
394 // bootstrap token will be derived from the most recently provided explicit
395 // passphrase (that was able to decrypt the data).
396 if (!IsExplicitPassphrase(passphrase_type_
)) {
397 if (!cryptographer
->has_pending_keys()) {
398 if (cryptographer
->AddKey(key_params
)) {
399 // Case 1 and 2. We set a new GAIA passphrase when there are no pending
400 // keys (1), or overwriting an implicit passphrase with a new explicit
401 // one (2) when there are no pending keys.
403 DVLOG(1) << "Setting explicit passphrase for encryption.";
404 passphrase_type_
= CUSTOM_PASSPHRASE
;
405 custom_passphrase_time_
= base::Time::Now();
406 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
407 OnPassphraseTypeChanged(
409 GetExplicitPassphraseTime()));
411 DVLOG(1) << "Setting implicit passphrase for encryption.";
413 cryptographer
->GetBootstrapToken(&bootstrap_token
);
415 // With M26, sync accounts can be in only one of two encryption states:
416 // 1) Encrypt only passwords with an implicit passphrase.
417 // 2) Encrypt all sync datatypes with an explicit passphrase.
418 // We deprecate the "EncryptAllData" and "CustomPassphrase" histograms,
419 // and keep track of an account's encryption state via the
420 // "CustomEncryption" histogram. See http://crbug.com/131478.
421 UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", is_explicit
);
425 NOTREACHED() << "Failed to add key to cryptographer.";
428 } else { // cryptographer->has_pending_keys() == true
430 // This can only happen if the nigori node is updated with a new
431 // implicit passphrase while a client is attempting to set a new custom
432 // passphrase (race condition).
433 DVLOG(1) << "Failing because an implicit passphrase is already set.";
435 } else { // is_explicit == false
436 if (cryptographer
->DecryptPendingKeys(key_params
)) {
437 // Case 4. We successfully decrypted with the implicit GAIA passphrase
439 DVLOG(1) << "Implicit internal passphrase accepted for decryption.";
440 cryptographer
->GetBootstrapToken(&bootstrap_token
);
443 // Case 5. Encryption was done with an old GAIA password, but we were
444 // provided with the current GAIA password. We need to generate a new
445 // bootstrap token to preserve it. We build a temporary cryptographer
446 // to allow us to extract these params without polluting our current
448 DVLOG(1) << "Implicit internal passphrase failed to decrypt, adding "
449 << "anyways as default passphrase and persisting via "
450 << "bootstrap token.";
451 Cryptographer
temp_cryptographer(cryptographer
->encryptor());
452 temp_cryptographer
.AddKey(key_params
);
453 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
454 // We then set the new passphrase as the default passphrase of the
455 // real cryptographer, even though we have pending keys. This is safe,
456 // as although Cryptographer::is_initialized() will now be true,
457 // is_ready() will remain false due to having pending keys.
458 cryptographer
->AddKey(key_params
);
462 } // cryptographer->has_pending_keys()
463 } else { // IsExplicitPassphrase(passphrase_type_) == true.
464 // Case 6. We do not want to override a previously set explicit passphrase,
465 // so we return a failure.
466 DVLOG(1) << "Failing because an explicit passphrase is already set.";
470 DVLOG_IF(1, !success
)
471 << "Failure in SetEncryptionPassphrase; notifying and returning.";
473 << "Successfully set encryption passphrase; updating nigori and "
476 FinishSetPassphrase(success
, bootstrap_token
, &trans
, &node
);
479 void SyncEncryptionHandlerImpl::SetDecryptionPassphrase(
480 const std::string
& passphrase
) {
481 DCHECK(thread_checker_
.CalledOnValidThread());
482 // We do not accept empty passphrases.
483 if (passphrase
.empty()) {
484 NOTREACHED() << "Cannot decrypt with an empty passphrase.";
488 // All accesses to the cryptographer are protected by a transaction.
489 WriteTransaction
trans(FROM_HERE
, user_share_
);
490 KeyParams key_params
= {"localhost", "dummy", passphrase
};
491 WriteNode
node(&trans
);
492 if (node
.InitTypeRoot(NIGORI
) != BaseNode::INIT_OK
) {
497 // Once we've migrated to keystore, we're only ever decrypting keys derived
498 // from an explicit passphrase. But, for clients without a keystore key yet
499 // (either not on by default or failed to download one), we still support
500 // decrypting with a gaia passphrase, and therefore bypass the
501 // DecryptPendingKeysWithExplicitPassphrase logic.
502 if (IsNigoriMigratedToKeystore(node
.GetNigoriSpecifics()) &&
503 IsExplicitPassphrase(passphrase_type_
)) {
504 DecryptPendingKeysWithExplicitPassphrase(passphrase
, &trans
, &node
);
508 Cryptographer
* cryptographer
=
509 &UnlockVaultMutable(trans
.GetWrappedTrans())->cryptographer
;
510 if (!cryptographer
->has_pending_keys()) {
511 // Note that this *can* happen in a rare situation where data is
512 // re-encrypted on another client while a SetDecryptionPassphrase() call is
513 // in-flight on this client. It is rare enough that we choose to do nothing.
514 NOTREACHED() << "Attempt to set decryption passphrase failed because there "
515 << "were no pending keys.";
519 std::string bootstrap_token
;
520 sync_pb::EncryptedData pending_keys
;
521 pending_keys
= cryptographer
->GetPendingKeys();
522 bool success
= false;
524 // There are three cases to handle here:
525 // 7. We're using the current GAIA password to decrypt the pending keys. This
526 // happens when signing in to an account with a previously set implicit
527 // passphrase, where the data is already encrypted with the newest GAIA
529 // 8. The user is providing an old GAIA password to decrypt the pending keys.
530 // In this case, the user is using an implicit passphrase, but has changed
531 // their password since they last encrypted their data, and therefore
532 // their current GAIA password was unable to decrypt the data. This will
533 // happen when the user is setting up a new profile with a previously
534 // encrypted account (after changing passwords).
535 // 9. The user is providing a previously set explicit passphrase to decrypt
537 if (!IsExplicitPassphrase(passphrase_type_
)) {
538 if (cryptographer
->is_initialized()) {
539 // We only want to change the default encryption key to the pending
540 // one if the pending keybag already contains the current default.
541 // This covers the case where a different client re-encrypted
542 // everything with a newer gaia passphrase (and hence the keybag
543 // contains keys from all previously used gaia passphrases).
544 // Otherwise, we're in a situation where the pending keys are
545 // encrypted with an old gaia passphrase, while the default is the
546 // current gaia passphrase. In that case, we preserve the default.
547 Cryptographer
temp_cryptographer(cryptographer
->encryptor());
548 temp_cryptographer
.SetPendingKeys(cryptographer
->GetPendingKeys());
549 if (temp_cryptographer
.DecryptPendingKeys(key_params
)) {
550 // Check to see if the pending bag of keys contains the current
552 sync_pb::EncryptedData encrypted
;
553 cryptographer
->GetKeys(&encrypted
);
554 if (temp_cryptographer
.CanDecrypt(encrypted
)) {
555 DVLOG(1) << "Implicit user provided passphrase accepted for "
556 << "decryption, overwriting default.";
557 // Case 7. The pending keybag contains the current default. Go ahead
558 // and update the cryptographer, letting the default change.
559 cryptographer
->DecryptPendingKeys(key_params
);
560 cryptographer
->GetBootstrapToken(&bootstrap_token
);
563 // Case 8. The pending keybag does not contain the current default
564 // encryption key. We decrypt the pending keys here, and in
565 // FinishSetPassphrase, re-encrypt everything with the current GAIA
566 // passphrase instead of the passphrase just provided by the user.
567 DVLOG(1) << "Implicit user provided passphrase accepted for "
568 << "decryption, restoring implicit internal passphrase "
570 std::string bootstrap_token_from_current_key
;
571 cryptographer
->GetBootstrapToken(
572 &bootstrap_token_from_current_key
);
573 cryptographer
->DecryptPendingKeys(key_params
);
574 // Overwrite the default from the pending keys.
575 cryptographer
->AddKeyFromBootstrapToken(
576 bootstrap_token_from_current_key
);
579 } else { // !temp_cryptographer.DecryptPendingKeys(..)
580 DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
582 } // temp_cryptographer.DecryptPendingKeys(...)
583 } else { // cryptographer->is_initialized() == false
584 if (cryptographer
->DecryptPendingKeys(key_params
)) {
585 // This can happpen in two cases:
586 // - First time sync on android, where we'll never have a
587 // !user_provided passphrase.
588 // - This is a restart for a client that lost their bootstrap token.
589 // In both cases, we should go ahead and initialize the cryptographer
590 // and persist the new bootstrap token.
592 // Note: at this point, we cannot distinguish between cases 7 and 8
593 // above. This user provided passphrase could be the current or the
594 // old. But, as long as we persist the token, there's nothing more
596 cryptographer
->GetBootstrapToken(&bootstrap_token
);
597 DVLOG(1) << "Implicit user provided passphrase accepted, initializing"
598 << " cryptographer.";
601 DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
604 } // cryptographer->is_initialized()
605 } else { // nigori_has_explicit_passphrase == true
606 // Case 9. Encryption was done with an explicit passphrase, and we decrypt
607 // with the passphrase provided by the user.
608 if (cryptographer
->DecryptPendingKeys(key_params
)) {
609 DVLOG(1) << "Explicit passphrase accepted for decryption.";
610 cryptographer
->GetBootstrapToken(&bootstrap_token
);
613 DVLOG(1) << "Explicit passphrase failed to decrypt.";
616 } // nigori_has_explicit_passphrase
618 DVLOG_IF(1, !success
)
619 << "Failure in SetDecryptionPassphrase; notifying and returning.";
621 << "Successfully set decryption passphrase; updating nigori and "
624 FinishSetPassphrase(success
, bootstrap_token
, &trans
, &node
);
627 void SyncEncryptionHandlerImpl::EnableEncryptEverything() {
628 DCHECK(thread_checker_
.CalledOnValidThread());
629 WriteTransaction
trans(FROM_HERE
, user_share_
);
630 DVLOG(1) << "Enabling encrypt everything.";
631 if (encrypt_everything_
)
633 EnableEncryptEverythingImpl(trans
.GetWrappedTrans());
634 WriteEncryptionStateToNigori(&trans
);
635 if (UnlockVault(trans
.GetWrappedTrans()).cryptographer
.is_ready())
636 ReEncryptEverything(&trans
);
639 bool SyncEncryptionHandlerImpl::IsEncryptEverythingEnabled() const {
640 DCHECK(thread_checker_
.CalledOnValidThread());
641 return encrypt_everything_
;
644 PassphraseType
SyncEncryptionHandlerImpl::GetPassphraseType() const {
645 DCHECK(thread_checker_
.CalledOnValidThread());
646 return passphrase_type_
;
649 // Note: this is called from within a syncable transaction, so we need to post
650 // tasks if we want to do any work that creates a new sync_api transaction.
651 void SyncEncryptionHandlerImpl::ApplyNigoriUpdate(
652 const sync_pb::NigoriSpecifics
& nigori
,
653 syncable::BaseTransaction
* const trans
) {
654 DCHECK(thread_checker_
.CalledOnValidThread());
656 if (!ApplyNigoriUpdateImpl(nigori
, trans
)) {
657 base::MessageLoop::current()->PostTask(
659 base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori
,
660 weak_ptr_factory_
.GetWeakPtr()));
664 SyncEncryptionHandler::Observer
,
666 OnCryptographerStateChanged(
667 &UnlockVaultMutable(trans
)->cryptographer
));
670 void SyncEncryptionHandlerImpl::UpdateNigoriFromEncryptedTypes(
671 sync_pb::NigoriSpecifics
* nigori
,
672 syncable::BaseTransaction
* const trans
) const {
673 DCHECK(thread_checker_
.CalledOnValidThread());
674 syncable::UpdateNigoriFromEncryptedTypes(UnlockVault(trans
).encrypted_types
,
679 bool SyncEncryptionHandlerImpl::NeedKeystoreKey(
680 syncable::BaseTransaction
* const trans
) const {
681 DCHECK(thread_checker_
.CalledOnValidThread());
682 return keystore_key_
.empty();
685 bool SyncEncryptionHandlerImpl::SetKeystoreKeys(
686 const google::protobuf::RepeatedPtrField
<google::protobuf::string
>& keys
,
687 syncable::BaseTransaction
* const trans
) {
688 DCHECK(thread_checker_
.CalledOnValidThread());
689 if (keys
.size() == 0)
691 // The last key in the vector is the current keystore key. The others are kept
692 // around for decryption only.
693 const std::string
& raw_keystore_key
= keys
.Get(keys
.size() - 1);
694 if (raw_keystore_key
.empty())
697 // Note: in order to Pack the keys, they must all be base64 encoded (else
698 // JSON serialization fails).
699 base::Base64Encode(raw_keystore_key
, &keystore_key_
);
701 // Go through and save the old keystore keys. We always persist all keystore
702 // keys the server sends us.
703 old_keystore_keys_
.resize(keys
.size() - 1);
704 for (int i
= 0; i
< keys
.size() - 1; ++i
)
705 base::Base64Encode(keys
.Get(i
), &old_keystore_keys_
[i
]);
707 Cryptographer
* cryptographer
= &UnlockVaultMutable(trans
)->cryptographer
;
709 // Update the bootstrap token. If this fails, we persist an empty string,
710 // which will force us to download the keystore keys again on the next
712 std::string keystore_bootstrap
= PackKeystoreBootstrapToken(
715 cryptographer
->encryptor());
717 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
718 OnBootstrapTokenUpdated(keystore_bootstrap
,
719 KEYSTORE_BOOTSTRAP_TOKEN
));
720 DVLOG(1) << "Keystore bootstrap token updated.";
722 // If this is a first time sync, we get the encryption keys before we process
723 // the nigori node. Just return for now, ApplyNigoriUpdate will be invoked
724 // once we have the nigori node.
725 syncable::Entry
entry(trans
, syncable::GET_TYPE_ROOT
, NIGORI
);
729 const sync_pb::NigoriSpecifics
& nigori
=
730 entry
.GetSpecifics().nigori();
731 if (cryptographer
->has_pending_keys() &&
732 IsNigoriMigratedToKeystore(nigori
) &&
733 !nigori
.keystore_decryptor_token().blob().empty()) {
734 // If the nigori is already migrated and we have pending keys, we might
735 // be able to decrypt them using either the keystore decryptor token
736 // or the existing keystore keys.
737 DecryptPendingKeysWithKeystoreKey(keystore_key_
,
738 nigori
.keystore_decryptor_token(),
742 // Note that triggering migration will have no effect if we're already
743 // properly migrated with the newest keystore keys.
744 if (ShouldTriggerMigration(nigori
, *cryptographer
)) {
745 base::MessageLoop::current()->PostTask(
747 base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori
,
748 weak_ptr_factory_
.GetWeakPtr()));
754 ModelTypeSet
SyncEncryptionHandlerImpl::GetEncryptedTypes(
755 syncable::BaseTransaction
* const trans
) const {
756 return UnlockVault(trans
).encrypted_types
;
759 Cryptographer
* SyncEncryptionHandlerImpl::GetCryptographerUnsafe() {
760 DCHECK(thread_checker_
.CalledOnValidThread());
761 return &vault_unsafe_
.cryptographer
;
764 ModelTypeSet
SyncEncryptionHandlerImpl::GetEncryptedTypesUnsafe() {
765 DCHECK(thread_checker_
.CalledOnValidThread());
766 return vault_unsafe_
.encrypted_types
;
769 bool SyncEncryptionHandlerImpl::MigratedToKeystore() {
770 DCHECK(thread_checker_
.CalledOnValidThread());
771 ReadTransaction
trans(FROM_HERE
, user_share_
);
772 ReadNode
nigori_node(&trans
);
773 if (nigori_node
.InitTypeRoot(NIGORI
) != BaseNode::INIT_OK
)
775 return IsNigoriMigratedToKeystore(nigori_node
.GetNigoriSpecifics());
778 base::Time
SyncEncryptionHandlerImpl::migration_time() const {
779 return migration_time_
;
782 base::Time
SyncEncryptionHandlerImpl::custom_passphrase_time() const {
783 return custom_passphrase_time_
;
786 void SyncEncryptionHandlerImpl::RestoreNigori(
787 const SyncEncryptionHandler::NigoriState
& nigori_state
) {
788 DCHECK(thread_checker_
.CalledOnValidThread());
790 WriteTransaction
trans(FROM_HERE
, user_share_
);
792 // Verify we don't already have a nigori node.
793 WriteNode
nigori_node(&trans
);
794 BaseNode::InitByLookupResult init_result
= nigori_node
.InitTypeRoot(NIGORI
);
795 DCHECK(init_result
== BaseNode::INIT_FAILED_ENTRY_NOT_GOOD
);
798 syncable::ModelNeutralMutableEntry
model_neutral_mutable_entry(
799 trans
.GetWrappedWriteTrans(), syncable::CREATE_NEW_TYPE_ROOT
, NIGORI
);
800 DCHECK(model_neutral_mutable_entry
.good());
801 model_neutral_mutable_entry
.PutServerIsDir(true);
802 model_neutral_mutable_entry
.PutUniqueServerTag(ModelTypeToRootTag(NIGORI
));
803 model_neutral_mutable_entry
.PutIsUnsynced(true);
805 // Update it with the saved nigori specifics.
806 syncable::MutableEntry
mutable_entry(trans
.GetWrappedWriteTrans(),
807 syncable::GET_TYPE_ROOT
, NIGORI
);
808 DCHECK(mutable_entry
.good());
809 sync_pb::EntitySpecifics specifics
;
810 specifics
.mutable_nigori()->CopyFrom(nigori_state
.nigori_specifics
);
811 mutable_entry
.PutSpecifics(specifics
);
813 // Update our state based on the saved nigori node.
814 ApplyNigoriUpdate(nigori_state
.nigori_specifics
, trans
.GetWrappedTrans());
817 // This function iterates over all encrypted types. There are many scenarios in
818 // which data for some or all types is not currently available. In that case,
819 // the lookup of the root node will fail and we will skip encryption for that
821 void SyncEncryptionHandlerImpl::ReEncryptEverything(
822 WriteTransaction
* trans
) {
823 DCHECK(thread_checker_
.CalledOnValidThread());
824 DCHECK(UnlockVault(trans
->GetWrappedTrans()).cryptographer
.is_ready());
825 for (ModelTypeSet::Iterator iter
=
826 UnlockVault(trans
->GetWrappedTrans()).encrypted_types
.First();
827 iter
.Good(); iter
.Inc()) {
828 if (iter
.Get() == PASSWORDS
|| IsControlType(iter
.Get()))
829 continue; // These types handle encryption differently.
831 ReadNode
type_root(trans
);
832 if (type_root
.InitTypeRoot(iter
.Get()) != BaseNode::INIT_OK
)
833 continue; // Don't try to reencrypt if the type's data is unavailable.
835 // Iterate through all children of this datatype.
836 std::queue
<int64
> to_visit
;
837 int64 child_id
= type_root
.GetFirstChildId();
838 to_visit
.push(child_id
);
839 while (!to_visit
.empty()) {
840 child_id
= to_visit
.front();
842 if (child_id
== kInvalidId
)
845 WriteNode
child(trans
);
846 if (child
.InitByIdLookup(child_id
) != BaseNode::INIT_OK
)
847 continue; // Possible for locally deleted items.
848 if (child
.GetIsFolder()) {
849 to_visit
.push(child
.GetFirstChildId());
851 if (child
.GetEntry()->GetUniqueServerTag().empty()) {
852 // Rewrite the specifics of the node with encrypted data if necessary
853 // (only rewrite the non-unique folders).
854 child
.ResetFromSpecifics();
856 to_visit
.push(child
.GetSuccessorId());
860 // Passwords are encrypted with their own legacy scheme. Passwords are always
861 // encrypted so we don't need to check GetEncryptedTypes() here.
862 ReadNode
passwords_root(trans
);
863 if (passwords_root
.InitTypeRoot(PASSWORDS
) == BaseNode::INIT_OK
) {
864 int64 child_id
= passwords_root
.GetFirstChildId();
865 while (child_id
!= kInvalidId
) {
866 WriteNode
child(trans
);
867 if (child
.InitByIdLookup(child_id
) != BaseNode::INIT_OK
)
868 break; // Possible if we failed to decrypt the data for some reason.
869 child
.SetPasswordSpecifics(child
.GetPasswordSpecifics());
870 child_id
= child
.GetSuccessorId();
874 DVLOG(1) << "Re-encrypt everything complete.";
876 // NOTE: We notify from within a transaction.
877 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
878 OnEncryptionComplete());
881 bool SyncEncryptionHandlerImpl::ApplyNigoriUpdateImpl(
882 const sync_pb::NigoriSpecifics
& nigori
,
883 syncable::BaseTransaction
* const trans
) {
884 DCHECK(thread_checker_
.CalledOnValidThread());
885 DVLOG(1) << "Applying nigori node update.";
886 bool nigori_types_need_update
= !UpdateEncryptedTypesFromNigori(nigori
,
889 if (nigori
.custom_passphrase_time() != 0) {
890 custom_passphrase_time_
=
891 ProtoTimeToTime(nigori
.custom_passphrase_time());
893 bool is_nigori_migrated
= IsNigoriMigratedToKeystore(nigori
);
894 if (is_nigori_migrated
) {
895 migration_time_
= ProtoTimeToTime(nigori
.keystore_migration_time());
896 PassphraseType nigori_passphrase_type
=
897 ProtoPassphraseTypeToEnum(nigori
.passphrase_type());
899 // Only update the local passphrase state if it's a valid transition:
900 // - implicit -> keystore
901 // - implicit -> frozen implicit
902 // - implicit -> custom
903 // - keystore -> custom
904 // Note: frozen implicit -> custom is not technically a valid transition,
905 // but we let it through here as well in case future versions do add support
906 // for this transition.
907 if (passphrase_type_
!= nigori_passphrase_type
&&
908 nigori_passphrase_type
!= IMPLICIT_PASSPHRASE
&&
909 (passphrase_type_
== IMPLICIT_PASSPHRASE
||
910 nigori_passphrase_type
== CUSTOM_PASSPHRASE
)) {
911 DVLOG(1) << "Changing passphrase state from "
912 << PassphraseTypeToString(passphrase_type_
)
914 << PassphraseTypeToString(nigori_passphrase_type
);
915 passphrase_type_
= nigori_passphrase_type
;
916 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
917 OnPassphraseTypeChanged(
919 GetExplicitPassphraseTime()));
921 if (passphrase_type_
== KEYSTORE_PASSPHRASE
&& encrypt_everything_
) {
922 // This is the case where another client that didn't support keystore
923 // encryption attempted to enable full encryption. We detect it
924 // and switch the passphrase type to frozen implicit passphrase instead
925 // due to full encryption not being compatible with keystore passphrase.
926 // Because the local passphrase type will not match the nigori passphrase
927 // type, we will trigger a rewrite and subsequently a re-migration.
928 DVLOG(1) << "Changing passphrase state to FROZEN_IMPLICIT_PASSPHRASE "
929 << "due to full encryption.";
930 passphrase_type_
= FROZEN_IMPLICIT_PASSPHRASE
;
931 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
932 OnPassphraseTypeChanged(
934 GetExplicitPassphraseTime()));
937 // It's possible that while we're waiting for migration a client that does
938 // not have keystore encryption enabled switches to a custom passphrase.
939 if (nigori
.keybag_is_frozen() &&
940 passphrase_type_
!= CUSTOM_PASSPHRASE
) {
941 passphrase_type_
= CUSTOM_PASSPHRASE
;
942 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
943 OnPassphraseTypeChanged(
945 GetExplicitPassphraseTime()));
949 Cryptographer
* cryptographer
= &UnlockVaultMutable(trans
)->cryptographer
;
950 bool nigori_needs_new_keys
= false;
951 if (!nigori
.encryption_keybag().blob().empty()) {
952 // We only update the default key if this was a new explicit passphrase.
953 // Else, since it was decryptable, it must not have been a new key.
954 bool need_new_default_key
= false;
955 if (is_nigori_migrated
) {
956 need_new_default_key
= IsExplicitPassphrase(
957 ProtoPassphraseTypeToEnum(nigori
.passphrase_type()));
959 need_new_default_key
= nigori
.keybag_is_frozen();
961 if (!AttemptToInstallKeybag(nigori
.encryption_keybag(),
962 need_new_default_key
,
964 // Check to see if we can decrypt the keybag using the keystore decryptor
966 cryptographer
->SetPendingKeys(nigori
.encryption_keybag());
967 if (!nigori
.keystore_decryptor_token().blob().empty() &&
968 !keystore_key_
.empty()) {
969 if (DecryptPendingKeysWithKeystoreKey(keystore_key_
,
970 nigori
.keystore_decryptor_token(),
972 nigori_needs_new_keys
=
973 cryptographer
->KeybagIsStale(nigori
.encryption_keybag());
975 LOG(ERROR
) << "Failed to decrypt pending keys using keystore "
980 // Keybag was installed. We write back our local keybag into the nigori
981 // node if the nigori node's keybag either contains less keys or
982 // has a different default key.
983 nigori_needs_new_keys
=
984 cryptographer
->KeybagIsStale(nigori
.encryption_keybag());
987 // The nigori node has an empty encryption keybag. Attempt to write our
988 // local encryption keys into it.
989 LOG(WARNING
) << "Nigori had empty encryption keybag.";
990 nigori_needs_new_keys
= true;
993 // If we've completed a sync cycle and the cryptographer isn't ready
994 // yet or has pending keys, prompt the user for a passphrase.
995 if (cryptographer
->has_pending_keys()) {
996 DVLOG(1) << "OnPassphraseRequired Sent";
997 sync_pb::EncryptedData pending_keys
= cryptographer
->GetPendingKeys();
998 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
999 OnPassphraseRequired(REASON_DECRYPTION
,
1001 } else if (!cryptographer
->is_ready()) {
1002 DVLOG(1) << "OnPassphraseRequired sent because cryptographer is not "
1004 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1005 OnPassphraseRequired(REASON_ENCRYPTION
,
1006 sync_pb::EncryptedData()));
1009 // Check if the current local encryption state is stricter/newer than the
1010 // nigori state. If so, we need to overwrite the nigori node with the local
1012 bool passphrase_type_matches
= true;
1013 if (!is_nigori_migrated
) {
1014 DCHECK(passphrase_type_
== CUSTOM_PASSPHRASE
||
1015 passphrase_type_
== IMPLICIT_PASSPHRASE
);
1016 passphrase_type_matches
=
1017 nigori
.keybag_is_frozen() == IsExplicitPassphrase(passphrase_type_
);
1019 passphrase_type_matches
=
1020 (ProtoPassphraseTypeToEnum(nigori
.passphrase_type()) ==
1023 if (!passphrase_type_matches
||
1024 nigori
.encrypt_everything() != encrypt_everything_
||
1025 nigori_types_need_update
||
1026 nigori_needs_new_keys
) {
1027 DVLOG(1) << "Triggering nigori rewrite.";
1033 void SyncEncryptionHandlerImpl::RewriteNigori() {
1034 DVLOG(1) << "Writing local encryption state into nigori.";
1035 DCHECK(thread_checker_
.CalledOnValidThread());
1036 WriteTransaction
trans(FROM_HERE
, user_share_
);
1037 WriteEncryptionStateToNigori(&trans
);
1040 void SyncEncryptionHandlerImpl::WriteEncryptionStateToNigori(
1041 WriteTransaction
* trans
) {
1042 DCHECK(thread_checker_
.CalledOnValidThread());
1043 WriteNode
nigori_node(trans
);
1044 // This can happen in tests that don't have nigori nodes.
1045 if (nigori_node
.InitTypeRoot(NIGORI
) != BaseNode::INIT_OK
)
1048 sync_pb::NigoriSpecifics nigori
= nigori_node
.GetNigoriSpecifics();
1049 const Cryptographer
& cryptographer
=
1050 UnlockVault(trans
->GetWrappedTrans()).cryptographer
;
1052 // Will not do anything if we shouldn't or can't migrate. Otherwise
1053 // migrates, writing the full encryption state as it does.
1054 if (!AttemptToMigrateNigoriToKeystore(trans
, &nigori_node
)) {
1055 if (cryptographer
.is_ready() &&
1056 nigori_overwrite_count_
< kNigoriOverwriteLimit
) {
1057 // Does not modify the encrypted blob if the unencrypted data already
1058 // matches what is about to be written.
1059 sync_pb::EncryptedData original_keys
= nigori
.encryption_keybag();
1060 if (!cryptographer
.GetKeys(nigori
.mutable_encryption_keybag()))
1063 if (nigori
.encryption_keybag().SerializeAsString() !=
1064 original_keys
.SerializeAsString()) {
1065 // We've updated the nigori node's encryption keys. In order to prevent
1066 // a possible looping of two clients constantly overwriting each other,
1067 // we limit the absolute number of overwrites per client instantiation.
1068 nigori_overwrite_count_
++;
1069 UMA_HISTOGRAM_COUNTS("Sync.AutoNigoriOverwrites",
1070 nigori_overwrite_count_
);
1073 // Note: we don't try to set keybag_is_frozen here since if that
1074 // is lost the user can always set it again (and we don't want to clobber
1075 // any migration state). The main goal at this point is to preserve
1076 // the encryption keys so all data remains decryptable.
1078 syncable::UpdateNigoriFromEncryptedTypes(
1079 UnlockVault(trans
->GetWrappedTrans()).encrypted_types
,
1080 encrypt_everything_
,
1082 if (!custom_passphrase_time_
.is_null()) {
1083 nigori
.set_custom_passphrase_time(
1084 TimeToProtoTime(custom_passphrase_time_
));
1087 // If nothing has changed, this is a no-op.
1088 nigori_node
.SetNigoriSpecifics(nigori
);
1092 bool SyncEncryptionHandlerImpl::UpdateEncryptedTypesFromNigori(
1093 const sync_pb::NigoriSpecifics
& nigori
,
1094 syncable::BaseTransaction
* const trans
) {
1095 DCHECK(thread_checker_
.CalledOnValidThread());
1096 ModelTypeSet
* encrypted_types
= &UnlockVaultMutable(trans
)->encrypted_types
;
1097 if (nigori
.encrypt_everything()) {
1098 EnableEncryptEverythingImpl(trans
);
1099 DCHECK(encrypted_types
->Equals(EncryptableUserTypes()));
1101 } else if (encrypt_everything_
) {
1102 DCHECK(encrypted_types
->Equals(EncryptableUserTypes()));
1106 ModelTypeSet nigori_encrypted_types
;
1107 nigori_encrypted_types
= syncable::GetEncryptedTypesFromNigori(nigori
);
1108 nigori_encrypted_types
.PutAll(SensitiveTypes());
1110 // If anything more than the sensitive types were encrypted, and
1111 // encrypt_everything is not explicitly set to false, we assume it means
1112 // a client intended to enable encrypt everything.
1113 if (!nigori
.has_encrypt_everything() &&
1114 !Difference(nigori_encrypted_types
, SensitiveTypes()).Empty()) {
1115 if (!encrypt_everything_
) {
1116 encrypt_everything_
= true;
1117 *encrypted_types
= EncryptableUserTypes();
1119 Observer
, observers_
,
1120 OnEncryptedTypesChanged(*encrypted_types
, encrypt_everything_
));
1122 DCHECK(encrypted_types
->Equals(EncryptableUserTypes()));
1126 MergeEncryptedTypes(nigori_encrypted_types
, trans
);
1127 return encrypted_types
->Equals(nigori_encrypted_types
);
1130 void SyncEncryptionHandlerImpl::SetCustomPassphrase(
1131 const std::string
& passphrase
,
1132 WriteTransaction
* trans
,
1133 WriteNode
* nigori_node
) {
1134 DCHECK(thread_checker_
.CalledOnValidThread());
1135 DCHECK(IsNigoriMigratedToKeystore(nigori_node
->GetNigoriSpecifics()));
1136 KeyParams key_params
= {"localhost", "dummy", passphrase
};
1138 if (passphrase_type_
!= KEYSTORE_PASSPHRASE
) {
1139 DVLOG(1) << "Failing to set a custom passphrase because one has already "
1141 FinishSetPassphrase(false, std::string(), trans
, nigori_node
);
1145 Cryptographer
* cryptographer
=
1146 &UnlockVaultMutable(trans
->GetWrappedTrans())->cryptographer
;
1147 if (cryptographer
->has_pending_keys()) {
1148 // This theoretically shouldn't happen, because the only way to have pending
1149 // keys after migrating to keystore support is if a custom passphrase was
1150 // set, which should update passpshrase_state_ and should be caught by the
1151 // if statement above. For the sake of safety though, we check for it in
1152 // case a client is misbehaving.
1153 LOG(ERROR
) << "Failing to set custom passphrase because of pending keys.";
1154 FinishSetPassphrase(false, std::string(), trans
, nigori_node
);
1158 std::string bootstrap_token
;
1159 if (!cryptographer
->AddKey(key_params
)) {
1160 NOTREACHED() << "Failed to add key to cryptographer.";
1164 DVLOG(1) << "Setting custom passphrase.";
1165 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1166 passphrase_type_
= CUSTOM_PASSPHRASE
;
1167 custom_passphrase_time_
= base::Time::Now();
1169 SyncEncryptionHandler::Observer
, observers_
,
1170 OnPassphraseTypeChanged(passphrase_type_
, GetExplicitPassphraseTime()));
1171 FinishSetPassphrase(true, bootstrap_token
, trans
, nigori_node
);
1174 void SyncEncryptionHandlerImpl::NotifyObserversOfLocalCustomPassphrase(
1175 WriteTransaction
* trans
) {
1176 WriteNode
nigori_node(trans
);
1177 BaseNode::InitByLookupResult init_result
= nigori_node
.InitTypeRoot(NIGORI
);
1178 DCHECK_EQ(init_result
, BaseNode::INIT_OK
);
1179 NigoriState nigori_state
;
1180 nigori_state
.nigori_specifics
= nigori_node
.GetNigoriSpecifics();
1181 DCHECK(nigori_state
.nigori_specifics
.passphrase_type() ==
1182 sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE
||
1183 nigori_state
.nigori_specifics
.passphrase_type() ==
1184 sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE
);
1185 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1186 OnLocalSetPassphraseEncryption(nigori_state
));
1189 void SyncEncryptionHandlerImpl::DecryptPendingKeysWithExplicitPassphrase(
1190 const std::string
& passphrase
,
1191 WriteTransaction
* trans
,
1192 WriteNode
* nigori_node
) {
1193 DCHECK(thread_checker_
.CalledOnValidThread());
1194 DCHECK(IsExplicitPassphrase(passphrase_type_
));
1195 KeyParams key_params
= {"localhost", "dummy", passphrase
};
1197 Cryptographer
* cryptographer
=
1198 &UnlockVaultMutable(trans
->GetWrappedTrans())->cryptographer
;
1199 if (!cryptographer
->has_pending_keys()) {
1200 // Note that this *can* happen in a rare situation where data is
1201 // re-encrypted on another client while a SetDecryptionPassphrase() call is
1202 // in-flight on this client. It is rare enough that we choose to do nothing.
1203 NOTREACHED() << "Attempt to set decryption passphrase failed because there "
1204 << "were no pending keys.";
1208 DCHECK(IsExplicitPassphrase(passphrase_type_
));
1209 bool success
= false;
1210 std::string bootstrap_token
;
1211 if (cryptographer
->DecryptPendingKeys(key_params
)) {
1212 DVLOG(1) << "Explicit passphrase accepted for decryption.";
1213 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1216 DVLOG(1) << "Explicit passphrase failed to decrypt.";
1219 if (success
&& !keystore_key_
.empty()) {
1220 // Should already be part of the encryption keybag, but we add it just
1222 KeyParams key_params
= {"localhost", "dummy", keystore_key_
};
1223 cryptographer
->AddNonDefaultKey(key_params
);
1225 FinishSetPassphrase(success
, bootstrap_token
, trans
, nigori_node
);
1228 void SyncEncryptionHandlerImpl::FinishSetPassphrase(
1230 const std::string
& bootstrap_token
,
1231 WriteTransaction
* trans
,
1232 WriteNode
* nigori_node
) {
1233 DCHECK(thread_checker_
.CalledOnValidThread());
1235 SyncEncryptionHandler::Observer
,
1237 OnCryptographerStateChanged(
1238 &UnlockVaultMutable(trans
->GetWrappedTrans())->cryptographer
));
1240 // It's possible we need to change the bootstrap token even if we failed to
1241 // set the passphrase (for example if we need to preserve the new GAIA
1243 if (!bootstrap_token
.empty()) {
1244 DVLOG(1) << "Passphrase bootstrap token updated.";
1245 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1246 OnBootstrapTokenUpdated(bootstrap_token
,
1247 PASSPHRASE_BOOTSTRAP_TOKEN
));
1250 const Cryptographer
& cryptographer
=
1251 UnlockVault(trans
->GetWrappedTrans()).cryptographer
;
1253 if (cryptographer
.is_ready()) {
1254 LOG(ERROR
) << "Attempt to change passphrase failed while cryptographer "
1256 } else if (cryptographer
.has_pending_keys()) {
1257 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1258 OnPassphraseRequired(REASON_DECRYPTION
,
1259 cryptographer
.GetPendingKeys()));
1261 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1262 OnPassphraseRequired(REASON_ENCRYPTION
,
1263 sync_pb::EncryptedData()));
1268 DCHECK(cryptographer
.is_ready());
1270 // Will do nothing if we're already properly migrated or unable to migrate
1271 // (in otherwords, if ShouldTriggerMigration is false).
1272 // Otherwise will update the nigori node with the current migrated state,
1273 // writing all encryption state as it does.
1274 if (!AttemptToMigrateNigoriToKeystore(trans
, nigori_node
)) {
1275 sync_pb::NigoriSpecifics
nigori(nigori_node
->GetNigoriSpecifics());
1276 // Does not modify nigori.encryption_keybag() if the original decrypted
1277 // data was the same.
1278 if (!cryptographer
.GetKeys(nigori
.mutable_encryption_keybag()))
1280 if (IsNigoriMigratedToKeystore(nigori
)) {
1281 DCHECK(keystore_key_
.empty() || IsExplicitPassphrase(passphrase_type_
));
1282 DVLOG(1) << "Leaving nigori migration state untouched after setting"
1285 nigori
.set_keybag_is_frozen(
1286 IsExplicitPassphrase(passphrase_type_
));
1288 // If we set a new custom passphrase, store the timestamp.
1289 if (!custom_passphrase_time_
.is_null()) {
1290 nigori
.set_custom_passphrase_time(
1291 TimeToProtoTime(custom_passphrase_time_
));
1293 nigori_node
->SetNigoriSpecifics(nigori
);
1296 // Must do this after OnPassphraseTypeChanged, in order to ensure the PSS
1297 // checks the passphrase state after it has been set.
1298 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1299 OnPassphraseAccepted());
1301 // Does nothing if everything is already encrypted.
1302 // TODO(zea): If we just migrated and enabled encryption, this will be
1303 // redundant. Figure out a way to not do this unnecessarily.
1304 ReEncryptEverything(trans
);
1307 void SyncEncryptionHandlerImpl::MergeEncryptedTypes(
1308 ModelTypeSet new_encrypted_types
,
1309 syncable::BaseTransaction
* const trans
) {
1310 DCHECK(thread_checker_
.CalledOnValidThread());
1312 // Only UserTypes may be encrypted.
1313 DCHECK(EncryptableUserTypes().HasAll(new_encrypted_types
));
1315 ModelTypeSet
* encrypted_types
= &UnlockVaultMutable(trans
)->encrypted_types
;
1316 if (!encrypted_types
->HasAll(new_encrypted_types
)) {
1317 *encrypted_types
= new_encrypted_types
;
1319 Observer
, observers_
,
1320 OnEncryptedTypesChanged(*encrypted_types
, encrypt_everything_
));
1324 SyncEncryptionHandlerImpl::Vault
* SyncEncryptionHandlerImpl::UnlockVaultMutable(
1325 syncable::BaseTransaction
* const trans
) {
1326 DCHECK_EQ(user_share_
->directory
.get(), trans
->directory());
1327 return &vault_unsafe_
;
1330 const SyncEncryptionHandlerImpl::Vault
& SyncEncryptionHandlerImpl::UnlockVault(
1331 syncable::BaseTransaction
* const trans
) const {
1332 DCHECK_EQ(user_share_
->directory
.get(), trans
->directory());
1333 return vault_unsafe_
;
1336 bool SyncEncryptionHandlerImpl::ShouldTriggerMigration(
1337 const sync_pb::NigoriSpecifics
& nigori
,
1338 const Cryptographer
& cryptographer
) const {
1339 DCHECK(thread_checker_
.CalledOnValidThread());
1340 // Don't migrate if there are pending encryption keys (because data
1341 // encrypted with the pending keys will not be decryptable).
1342 if (cryptographer
.has_pending_keys())
1344 if (IsNigoriMigratedToKeystore(nigori
)) {
1345 // If the nigori is already migrated but does not reflect the explicit
1346 // passphrase state, remigrate. Similarly, if the nigori has an explicit
1347 // passphrase but does not have full encryption, or the nigori has an
1348 // implicit passphrase but does have full encryption, re-migrate.
1349 // Note that this is to defend against other clients without keystore
1350 // encryption enabled transitioning to states that are no longer valid.
1351 if (passphrase_type_
!= KEYSTORE_PASSPHRASE
&&
1352 nigori
.passphrase_type() ==
1353 sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE
) {
1355 } else if (IsExplicitPassphrase(passphrase_type_
) &&
1356 !encrypt_everything_
) {
1358 } else if (passphrase_type_
== KEYSTORE_PASSPHRASE
&&
1359 encrypt_everything_
) {
1362 cryptographer
.is_ready() &&
1363 !cryptographer
.CanDecryptUsingDefaultKey(nigori
.encryption_keybag())) {
1364 // We need to overwrite the keybag. This might involve overwriting the
1365 // keystore decryptor too.
1367 } else if (old_keystore_keys_
.size() > 0 && !keystore_key_
.empty()) {
1368 // Check to see if a server key rotation has happened, but the nigori
1369 // node's keys haven't been rotated yet, and hence we should re-migrate.
1370 // Note that once a key rotation has been performed, we no longer
1371 // preserve backwards compatibility, and the keybag will therefore be
1372 // encrypted with the current keystore key.
1373 Cryptographer
temp_cryptographer(cryptographer
.encryptor());
1374 KeyParams keystore_params
= {"localhost", "dummy", keystore_key_
};
1375 temp_cryptographer
.AddKey(keystore_params
);
1376 if (!temp_cryptographer
.CanDecryptUsingDefaultKey(
1377 nigori
.encryption_keybag())) {
1382 } else if (keystore_key_
.empty()) {
1383 // If we haven't already migrated, we don't want to do anything unless
1384 // a keystore key is available (so that those clients without keystore
1385 // encryption enabled aren't forced into new states, e.g. frozen implicit
1392 bool SyncEncryptionHandlerImpl::AttemptToMigrateNigoriToKeystore(
1393 WriteTransaction
* trans
,
1394 WriteNode
* nigori_node
) {
1395 DCHECK(thread_checker_
.CalledOnValidThread());
1396 const sync_pb::NigoriSpecifics
& old_nigori
=
1397 nigori_node
->GetNigoriSpecifics();
1398 Cryptographer
* cryptographer
=
1399 &UnlockVaultMutable(trans
->GetWrappedTrans())->cryptographer
;
1401 if (!ShouldTriggerMigration(old_nigori
, *cryptographer
))
1404 DVLOG(1) << "Starting nigori migration to keystore support.";
1405 sync_pb::NigoriSpecifics
migrated_nigori(old_nigori
);
1407 PassphraseType new_passphrase_type
= passphrase_type_
;
1408 bool new_encrypt_everything
= encrypt_everything_
;
1409 if (encrypt_everything_
&& !IsExplicitPassphrase(passphrase_type_
)) {
1410 DVLOG(1) << "Switching to frozen implicit passphrase due to already having "
1411 << "full encryption.";
1412 new_passphrase_type
= FROZEN_IMPLICIT_PASSPHRASE
;
1413 migrated_nigori
.clear_keystore_decryptor_token();
1414 } else if (IsExplicitPassphrase(passphrase_type_
)) {
1415 DVLOG_IF(1, !encrypt_everything_
) << "Enabling encrypt everything due to "
1416 << "explicit passphrase";
1417 new_encrypt_everything
= true;
1418 migrated_nigori
.clear_keystore_decryptor_token();
1420 DCHECK(!encrypt_everything_
);
1421 new_passphrase_type
= KEYSTORE_PASSPHRASE
;
1422 DVLOG(1) << "Switching to keystore passphrase state.";
1424 migrated_nigori
.set_encrypt_everything(new_encrypt_everything
);
1425 migrated_nigori
.set_passphrase_type(
1426 EnumPassphraseTypeToProto(new_passphrase_type
));
1427 migrated_nigori
.set_keybag_is_frozen(true);
1429 if (!keystore_key_
.empty()) {
1430 KeyParams key_params
= {"localhost", "dummy", keystore_key_
};
1431 if ((old_keystore_keys_
.size() > 0 &&
1432 new_passphrase_type
== KEYSTORE_PASSPHRASE
) ||
1433 !cryptographer
->is_initialized()) {
1434 // Either at least one key rotation has been performed, so we no longer
1435 // care about backwards compatibility, or we're generating keystore-based
1436 // encryption keys without knowing the GAIA password (and therefore the
1437 // cryptographer is not initialized), so we can't support backwards
1438 // compatibility. Ensure the keystore key is the default key.
1439 DVLOG(1) << "Migrating keybag to keystore key.";
1440 bool cryptographer_was_ready
= cryptographer
->is_ready();
1441 if (!cryptographer
->AddKey(key_params
)) {
1442 LOG(ERROR
) << "Failed to add keystore key as default key";
1443 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1444 FAILED_TO_SET_DEFAULT_KEYSTORE
,
1445 MIGRATION_RESULT_SIZE
);
1448 if (!cryptographer_was_ready
&& cryptographer
->is_ready()) {
1450 SyncEncryptionHandler::Observer
,
1452 OnPassphraseAccepted());
1455 // We're in backwards compatible mode -- either the account has an
1456 // explicit passphrase, or we want to preserve the current GAIA-based key
1457 // as the default because we can (there have been no key rotations since
1459 DVLOG(1) << "Migrating keybag while preserving old key";
1460 if (!cryptographer
->AddNonDefaultKey(key_params
)) {
1461 LOG(ERROR
) << "Failed to add keystore key as non-default key.";
1462 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1463 FAILED_TO_SET_NONDEFAULT_KEYSTORE
,
1464 MIGRATION_RESULT_SIZE
);
1469 if (!old_keystore_keys_
.empty()) {
1470 // Go through and add all the old keystore keys as non default keys, so
1471 // they'll be preserved in the encryption_keybag when we next write the
1473 for (std::vector
<std::string
>::const_iterator iter
=
1474 old_keystore_keys_
.begin(); iter
!= old_keystore_keys_
.end();
1476 KeyParams key_params
= {"localhost", "dummy", *iter
};
1477 cryptographer
->AddNonDefaultKey(key_params
);
1480 if (new_passphrase_type
== KEYSTORE_PASSPHRASE
&&
1481 !GetKeystoreDecryptor(
1484 migrated_nigori
.mutable_keystore_decryptor_token())) {
1485 LOG(ERROR
) << "Failed to extract keystore decryptor token.";
1486 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1487 FAILED_TO_EXTRACT_DECRYPTOR
,
1488 MIGRATION_RESULT_SIZE
);
1491 if (!cryptographer
->GetKeys(migrated_nigori
.mutable_encryption_keybag())) {
1492 LOG(ERROR
) << "Failed to extract encryption keybag.";
1493 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1494 FAILED_TO_EXTRACT_KEYBAG
,
1495 MIGRATION_RESULT_SIZE
);
1499 if (migration_time_
.is_null())
1500 migration_time_
= base::Time::Now();
1501 migrated_nigori
.set_keystore_migration_time(TimeToProtoTime(migration_time_
));
1503 if (!custom_passphrase_time_
.is_null()) {
1504 migrated_nigori
.set_custom_passphrase_time(
1505 TimeToProtoTime(custom_passphrase_time_
));
1509 SyncEncryptionHandler::Observer
,
1511 OnCryptographerStateChanged(cryptographer
));
1512 if (passphrase_type_
!= new_passphrase_type
) {
1513 passphrase_type_
= new_passphrase_type
;
1514 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer
, observers_
,
1515 OnPassphraseTypeChanged(
1517 GetExplicitPassphraseTime()));
1520 if (new_encrypt_everything
&& !encrypt_everything_
) {
1521 EnableEncryptEverythingImpl(trans
->GetWrappedTrans());
1522 ReEncryptEverything(trans
);
1523 } else if (!cryptographer
->CanDecryptUsingDefaultKey(
1524 old_nigori
.encryption_keybag())) {
1525 DVLOG(1) << "Rencrypting everything due to key rotation.";
1526 ReEncryptEverything(trans
);
1529 DVLOG(1) << "Completing nigori migration to keystore support.";
1530 nigori_node
->SetNigoriSpecifics(migrated_nigori
);
1532 if (new_encrypt_everything
&&
1533 (new_passphrase_type
== FROZEN_IMPLICIT_PASSPHRASE
||
1534 new_passphrase_type
== CUSTOM_PASSPHRASE
)) {
1535 NotifyObserversOfLocalCustomPassphrase(trans
);
1538 switch (new_passphrase_type
) {
1539 case KEYSTORE_PASSPHRASE
:
1540 if (old_keystore_keys_
.size() > 0) {
1541 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1542 MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT
,
1543 MIGRATION_RESULT_SIZE
);
1545 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1546 MIGRATION_SUCCESS_KEYSTORE_DEFAULT
,
1547 MIGRATION_RESULT_SIZE
);
1550 case FROZEN_IMPLICIT_PASSPHRASE
:
1551 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1552 MIGRATION_SUCCESS_FROZEN_IMPLICIT
,
1553 MIGRATION_RESULT_SIZE
);
1555 case CUSTOM_PASSPHRASE
:
1556 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1557 MIGRATION_SUCCESS_CUSTOM
,
1558 MIGRATION_RESULT_SIZE
);
1567 bool SyncEncryptionHandlerImpl::GetKeystoreDecryptor(
1568 const Cryptographer
& cryptographer
,
1569 const std::string
& keystore_key
,
1570 sync_pb::EncryptedData
* encrypted_blob
) {
1571 DCHECK(thread_checker_
.CalledOnValidThread());
1572 DCHECK(!keystore_key
.empty());
1573 DCHECK(cryptographer
.is_ready());
1574 std::string serialized_nigori
;
1575 serialized_nigori
= cryptographer
.GetDefaultNigoriKeyData();
1576 if (serialized_nigori
.empty()) {
1577 LOG(ERROR
) << "Failed to get cryptographer bootstrap token.";
1580 Cryptographer
temp_cryptographer(cryptographer
.encryptor());
1581 KeyParams key_params
= {"localhost", "dummy", keystore_key
};
1582 if (!temp_cryptographer
.AddKey(key_params
))
1584 if (!temp_cryptographer
.EncryptString(serialized_nigori
, encrypted_blob
))
1589 bool SyncEncryptionHandlerImpl::AttemptToInstallKeybag(
1590 const sync_pb::EncryptedData
& keybag
,
1591 bool update_default
,
1592 Cryptographer
* cryptographer
) {
1593 if (!cryptographer
->CanDecrypt(keybag
))
1595 cryptographer
->InstallKeys(keybag
);
1597 cryptographer
->SetDefaultKey(keybag
.key_name());
1601 void SyncEncryptionHandlerImpl::EnableEncryptEverythingImpl(
1602 syncable::BaseTransaction
* const trans
) {
1603 ModelTypeSet
* encrypted_types
= &UnlockVaultMutable(trans
)->encrypted_types
;
1604 if (encrypt_everything_
) {
1605 DCHECK(encrypted_types
->Equals(EncryptableUserTypes()));
1608 encrypt_everything_
= true;
1609 *encrypted_types
= EncryptableUserTypes();
1611 Observer
, observers_
,
1612 OnEncryptedTypesChanged(*encrypted_types
, encrypt_everything_
));
1615 bool SyncEncryptionHandlerImpl::DecryptPendingKeysWithKeystoreKey(
1616 const std::string
& keystore_key
,
1617 const sync_pb::EncryptedData
& keystore_decryptor_token
,
1618 Cryptographer
* cryptographer
) {
1619 DCHECK(cryptographer
->has_pending_keys());
1620 if (keystore_decryptor_token
.blob().empty())
1622 Cryptographer
temp_cryptographer(cryptographer
->encryptor());
1624 // First, go through and all all the old keystore keys to the temporary
1626 for (size_t i
= 0; i
< old_keystore_keys_
.size(); ++i
) {
1627 KeyParams old_key_params
= {"localhost", "dummy", old_keystore_keys_
[i
]};
1628 temp_cryptographer
.AddKey(old_key_params
);
1631 // Then add the current keystore key as the default key and see if we can
1633 KeyParams keystore_params
= {"localhost", "dummy", keystore_key_
};
1634 if (temp_cryptographer
.AddKey(keystore_params
) &&
1635 temp_cryptographer
.CanDecrypt(keystore_decryptor_token
)) {
1636 // Someone else migrated the nigori for us! How generous! Go ahead and
1637 // install both the keystore key and the new default encryption key
1638 // (i.e. the one provided by the keystore decryptor token) into the
1640 // The keystore decryptor token is a keystore key encrypted blob containing
1641 // the current serialized default encryption key (and as such should be
1642 // able to decrypt the nigori node's encryption keybag).
1643 // Note: it's possible a key rotation has happened since the migration, and
1644 // we're decrypting using an old keystore key. In that case we need to
1645 // ensure we re-encrypt using the newest key.
1646 DVLOG(1) << "Attempting to decrypt pending keys using "
1647 << "keystore decryptor token.";
1648 std::string serialized_nigori
=
1649 temp_cryptographer
.DecryptToString(keystore_decryptor_token
);
1651 // This will decrypt the pending keys and add them if possible. The key
1652 // within |serialized_nigori| will be the default after.
1653 cryptographer
->ImportNigoriKey(serialized_nigori
);
1655 if (!temp_cryptographer
.CanDecryptUsingDefaultKey(
1656 keystore_decryptor_token
)) {
1657 // The keystore decryptor token was derived from an old keystore key.
1658 // A key rotation is necessary, so set the current keystore key as the
1659 // default key (which will trigger a re-migration).
1660 DVLOG(1) << "Pending keys based on old keystore key. Setting newest "
1661 << "keystore key as default.";
1662 cryptographer
->AddKey(keystore_params
);
1664 // Theoretically the encryption keybag should already contain the keystore
1665 // key. We explicitly add it as a safety measure.
1666 DVLOG(1) << "Pending keys based on newest keystore key.";
1667 cryptographer
->AddNonDefaultKey(keystore_params
);
1669 if (cryptographer
->is_ready()) {
1670 std::string bootstrap_token
;
1671 cryptographer
->GetBootstrapToken(&bootstrap_token
);
1672 DVLOG(1) << "Keystore decryptor token decrypted pending keys.";
1674 SyncEncryptionHandler::Observer
,
1676 OnPassphraseAccepted());
1678 SyncEncryptionHandler::Observer
,
1680 OnBootstrapTokenUpdated(bootstrap_token
,
1681 PASSPHRASE_BOOTSTRAP_TOKEN
));
1683 SyncEncryptionHandler::Observer
,
1685 OnCryptographerStateChanged(cryptographer
));
1692 base::Time
SyncEncryptionHandlerImpl::GetExplicitPassphraseTime() const {
1693 if (passphrase_type_
== FROZEN_IMPLICIT_PASSPHRASE
)
1694 return migration_time();
1695 else if (passphrase_type_
== CUSTOM_PASSPHRASE
)
1696 return custom_passphrase_time();
1697 return base::Time();
1700 } // namespace browser_sync