mac: Rename the method -accessibilityChildren on TabStripView.
[chromium-blink-merge.git] / sync / internal_api / sync_encryption_handler_impl.cc
blob4bf559fd8580c958fe0caa8d18ddfa01ceb933a5
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"
7 #include <queue>
8 #include <string>
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/nigori_util.h"
30 #include "sync/syncable/syncable_base_transaction.h"
31 #include "sync/util/cryptographer.h"
32 #include "sync/util/encryptor.h"
33 #include "sync/util/time.h"
35 namespace syncer {
37 namespace {
39 // The maximum number of times we will automatically overwrite the nigori node
40 // because the encryption keys don't match (per chrome instantiation).
41 // We protect ourselves against nigori rollbacks, but it's possible two
42 // different clients might have contrasting view of what the nigori node state
43 // should be, in which case they might ping pong (see crbug.com/119207).
44 static const int kNigoriOverwriteLimit = 10;
46 // Enumeration of nigori keystore migration results (for use in UMA stats).
47 enum NigoriMigrationResult {
48 FAILED_TO_SET_DEFAULT_KEYSTORE,
49 FAILED_TO_SET_NONDEFAULT_KEYSTORE,
50 FAILED_TO_EXTRACT_DECRYPTOR,
51 FAILED_TO_EXTRACT_KEYBAG,
52 MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
53 MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
54 MIGRATION_SUCCESS_FROZEN_IMPLICIT,
55 MIGRATION_SUCCESS_CUSTOM,
56 MIGRATION_RESULT_SIZE,
59 enum NigoriMigrationState {
60 MIGRATED,
61 NOT_MIGRATED_CRYPTO_NOT_READY,
62 NOT_MIGRATED_NO_KEYSTORE_KEY,
63 NOT_MIGRATED_UNKNOWN_REASON,
64 MIGRATION_STATE_SIZE,
67 // The new passphrase state is sufficient to determine whether a nigori node
68 // is migrated to support keystore encryption. In addition though, we also
69 // want to verify the conditions for proper keystore encryption functionality.
70 // 1. Passphrase state is set.
71 // 2. Migration time is set.
72 // 3. Frozen keybag is true
73 // 4. If passphrase state is keystore, keystore_decryptor_token is set.
74 bool IsNigoriMigratedToKeystore(const sync_pb::NigoriSpecifics& nigori) {
75 if (!nigori.has_passphrase_type())
76 return false;
77 if (!nigori.has_keystore_migration_time())
78 return false;
79 if (!nigori.keybag_is_frozen())
80 return false;
81 if (nigori.passphrase_type() ==
82 sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE)
83 return false;
84 if (nigori.passphrase_type() ==
85 sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE &&
86 nigori.keystore_decryptor_token().blob().empty())
87 return false;
88 if (!nigori.has_keystore_migration_time())
89 return false;
90 return true;
93 PassphraseType ProtoPassphraseTypeToEnum(
94 sync_pb::NigoriSpecifics::PassphraseType type) {
95 switch(type) {
96 case sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE:
97 return IMPLICIT_PASSPHRASE;
98 case sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE:
99 return KEYSTORE_PASSPHRASE;
100 case sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE:
101 return CUSTOM_PASSPHRASE;
102 case sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE:
103 return FROZEN_IMPLICIT_PASSPHRASE;
104 default:
105 NOTREACHED();
106 return IMPLICIT_PASSPHRASE;
110 sync_pb::NigoriSpecifics::PassphraseType
111 EnumPassphraseTypeToProto(PassphraseType type) {
112 switch(type) {
113 case IMPLICIT_PASSPHRASE:
114 return sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE;
115 case KEYSTORE_PASSPHRASE:
116 return sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE;
117 case CUSTOM_PASSPHRASE:
118 return sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE;
119 case FROZEN_IMPLICIT_PASSPHRASE:
120 return sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE;
121 default:
122 NOTREACHED();
123 return sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE;
127 bool IsExplicitPassphrase(PassphraseType type) {
128 return type == CUSTOM_PASSPHRASE || type == FROZEN_IMPLICIT_PASSPHRASE;
131 // Keystore Bootstrap Token helper methods.
132 // The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
133 // strings, with the current keystore key as the last value in the list.
134 std::string PackKeystoreBootstrapToken(
135 const std::vector<std::string>& old_keystore_keys,
136 const std::string& current_keystore_key,
137 Encryptor* encryptor) {
138 if (current_keystore_key.empty())
139 return std::string();
141 base::ListValue keystore_key_values;
142 for (size_t i = 0; i < old_keystore_keys.size(); ++i)
143 keystore_key_values.AppendString(old_keystore_keys[i]);
144 keystore_key_values.AppendString(current_keystore_key);
146 // Update the bootstrap token.
147 // The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
148 // strings, with the current keystore key as the last value in the list.
149 std::string serialized_keystores;
150 JSONStringValueSerializer json(&serialized_keystores);
151 json.Serialize(keystore_key_values);
152 std::string encrypted_keystores;
153 encryptor->EncryptString(serialized_keystores,
154 &encrypted_keystores);
155 std::string keystore_bootstrap;
156 base::Base64Encode(encrypted_keystores, &keystore_bootstrap);
157 return keystore_bootstrap;
160 bool UnpackKeystoreBootstrapToken(
161 const std::string& keystore_bootstrap_token,
162 Encryptor* encryptor,
163 std::vector<std::string>* old_keystore_keys,
164 std::string* current_keystore_key) {
165 if (keystore_bootstrap_token.empty())
166 return false;
167 std::string base64_decoded_keystore_bootstrap;
168 if (!base::Base64Decode(keystore_bootstrap_token,
169 &base64_decoded_keystore_bootstrap)) {
170 return false;
172 std::string decrypted_keystore_bootstrap;
173 if (!encryptor->DecryptString(base64_decoded_keystore_bootstrap,
174 &decrypted_keystore_bootstrap)) {
175 return false;
178 JSONStringValueDeserializer json(decrypted_keystore_bootstrap);
179 scoped_ptr<base::Value> deserialized_keystore_keys(
180 json.Deserialize(NULL, NULL));
181 if (!deserialized_keystore_keys)
182 return false;
183 base::ListValue* internal_list_value = NULL;
184 if (!deserialized_keystore_keys->GetAsList(&internal_list_value))
185 return false;
186 int number_of_keystore_keys = internal_list_value->GetSize();
187 if (!internal_list_value->GetString(number_of_keystore_keys - 1,
188 current_keystore_key)) {
189 return false;
191 old_keystore_keys->resize(number_of_keystore_keys - 1);
192 for (int i = 0; i < number_of_keystore_keys - 1; ++i)
193 internal_list_value->GetString(i, &(*old_keystore_keys)[i]);
194 return true;
197 } // namespace
199 SyncEncryptionHandlerImpl::Vault::Vault(
200 Encryptor* encryptor,
201 ModelTypeSet encrypted_types)
202 : cryptographer(encryptor),
203 encrypted_types(encrypted_types) {
206 SyncEncryptionHandlerImpl::Vault::~Vault() {
209 SyncEncryptionHandlerImpl::SyncEncryptionHandlerImpl(
210 UserShare* user_share,
211 Encryptor* encryptor,
212 const std::string& restored_key_for_bootstrapping,
213 const std::string& restored_keystore_key_for_bootstrapping)
214 : user_share_(user_share),
215 vault_unsafe_(encryptor, SensitiveTypes()),
216 encrypt_everything_(false),
217 passphrase_type_(IMPLICIT_PASSPHRASE),
218 nigori_overwrite_count_(0),
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,
228 encryptor,
229 &old_keystore_keys_,
230 &keystore_key_);
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)
253 return;
254 if (!ApplyNigoriUpdateImpl(node.GetNigoriSpecifics(),
255 trans.GetWrappedTrans())) {
256 WriteEncryptionStateToNigori(&trans);
259 UMA_HISTOGRAM_ENUMERATION("Sync.PassphraseType",
260 GetPassphraseType(),
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
272 // keystore.
273 UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
274 MIGRATED,
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
280 // keystore key.
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);
296 } else {
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.
307 FOR_EACH_OBSERVER(
308 Observer, observers_,
309 OnEncryptedTypesChanged(
310 UnlockVault(trans.GetWrappedTrans()).encrypted_types,
311 encrypt_everything_));
312 FOR_EACH_OBSERVER(
313 SyncEncryptionHandler::Observer,
314 observers_,
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,
328 bool is_explicit) {
329 DCHECK(thread_checker_.CalledOnValidThread());
330 // We do not accept empty passphrases.
331 if (passphrase.empty()) {
332 NOTREACHED() << "Cannot encrypt with an empty passphrase.";
333 return;
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) {
341 NOTREACHED();
342 return;
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())) {
351 if (!is_explicit) {
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
355 // encryption key.
356 LOG(WARNING) << "Ignoring new implicit passphrase. Keystore migration "
357 << "already performed.";
358 return;
360 // Will fail if we already have an explicit passphrase or we have pending
361 // keys.
362 SetCustomPassphrase(passphrase, &trans, &node);
364 // When keystore migration occurs, the "CustomEncryption" UMA stat must be
365 // logged as true.
366 UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
367 return;
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.
402 if (is_explicit) {
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(
408 passphrase_type_,
409 GetExplicitPassphraseTime()));
410 } else {
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);
423 success = true;
424 } else {
425 NOTREACHED() << "Failed to add key to cryptographer.";
426 success = false;
428 } else { // cryptographer->has_pending_keys() == true
429 if (is_explicit) {
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.";
434 success = false;
435 } else { // is_explicit == false
436 if (cryptographer->DecryptPendingKeys(key_params)) {
437 // Case 4. We successfully decrypted with the implicit GAIA passphrase
438 // passed in.
439 DVLOG(1) << "Implicit internal passphrase accepted for decryption.";
440 cryptographer->GetBootstrapToken(&bootstrap_token);
441 success = true;
442 } else {
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
447 // cryptographer.
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);
459 success = false;
461 } // is_explicit
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.";
467 success = false;
470 DVLOG_IF(1, !success)
471 << "Failure in SetEncryptionPassphrase; notifying and returning.";
472 DVLOG_IF(1, success)
473 << "Successfully set encryption passphrase; updating nigori and "
474 "reencrypting.";
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.";
485 return;
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) {
493 NOTREACHED();
494 return;
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);
505 return;
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.";
516 return;
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
528 // password.
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
536 // the pending keys.
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
551 // default key.
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);
561 success = true;
562 } else {
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 "
569 << "as default.";
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);
577 success = true;
579 } else { // !temp_cryptographer.DecryptPendingKeys(..)
580 DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
581 success = false;
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
595 // we can do.
596 cryptographer->GetBootstrapToken(&bootstrap_token);
597 DVLOG(1) << "Implicit user provided passphrase accepted, initializing"
598 << " cryptographer.";
599 success = true;
600 } else {
601 DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
602 success = false;
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);
611 success = true;
612 } else {
613 DVLOG(1) << "Explicit passphrase failed to decrypt.";
614 success = false;
616 } // nigori_has_explicit_passphrase
618 DVLOG_IF(1, !success)
619 << "Failure in SetDecryptionPassphrase; notifying and returning.";
620 DVLOG_IF(1, success)
621 << "Successfully set decryption passphrase; updating nigori and "
622 "reencrypting.";
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_)
632 return;
633 EnableEncryptEverythingImpl(trans.GetWrappedTrans());
634 WriteEncryptionStateToNigori(&trans);
635 if (UnlockVault(trans.GetWrappedTrans()).cryptographer.is_ready())
636 ReEncryptEverything(&trans);
639 bool SyncEncryptionHandlerImpl::EncryptEverythingEnabled() 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());
655 DCHECK(trans);
656 if (!ApplyNigoriUpdateImpl(nigori, trans)) {
657 base::MessageLoop::current()->PostTask(
658 FROM_HERE,
659 base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori,
660 weak_ptr_factory_.GetWeakPtr()));
663 FOR_EACH_OBSERVER(
664 SyncEncryptionHandler::Observer,
665 observers_,
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,
675 encrypt_everything_,
676 nigori);
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)
690 return false;
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())
695 return false;
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
711 // restart.
712 std::string keystore_bootstrap = PackKeystoreBootstrapToken(
713 old_keystore_keys_,
714 keystore_key_,
715 cryptographer->encryptor());
716 DCHECK_EQ(keystore_bootstrap.empty(), keystore_key_.empty());
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);
726 if (!entry.good())
727 return true;
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(),
739 cryptographer);
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(
746 FROM_HERE,
747 base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori,
748 weak_ptr_factory_.GetWeakPtr()));
751 return true;
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)
774 return false;
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 // This function iterates over all encrypted types. There are many scenarios in
787 // which data for some or all types is not currently available. In that case,
788 // the lookup of the root node will fail and we will skip encryption for that
789 // type.
790 void SyncEncryptionHandlerImpl::ReEncryptEverything(
791 WriteTransaction* trans) {
792 DCHECK(thread_checker_.CalledOnValidThread());
793 DCHECK(UnlockVault(trans->GetWrappedTrans()).cryptographer.is_ready());
794 for (ModelTypeSet::Iterator iter =
795 UnlockVault(trans->GetWrappedTrans()).encrypted_types.First();
796 iter.Good(); iter.Inc()) {
797 if (iter.Get() == PASSWORDS || IsControlType(iter.Get()))
798 continue; // These types handle encryption differently.
800 ReadNode type_root(trans);
801 if (type_root.InitTypeRoot(iter.Get()) != BaseNode::INIT_OK)
802 continue; // Don't try to reencrypt if the type's data is unavailable.
804 // Iterate through all children of this datatype.
805 std::queue<int64> to_visit;
806 int64 child_id = type_root.GetFirstChildId();
807 to_visit.push(child_id);
808 while (!to_visit.empty()) {
809 child_id = to_visit.front();
810 to_visit.pop();
811 if (child_id == kInvalidId)
812 continue;
814 WriteNode child(trans);
815 if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
816 continue; // Possible for locally deleted items.
817 if (child.GetIsFolder()) {
818 to_visit.push(child.GetFirstChildId());
820 if (child.GetEntry()->GetUniqueServerTag().empty()) {
821 // Rewrite the specifics of the node with encrypted data if necessary
822 // (only rewrite the non-unique folders).
823 child.ResetFromSpecifics();
825 to_visit.push(child.GetSuccessorId());
829 // Passwords are encrypted with their own legacy scheme. Passwords are always
830 // encrypted so we don't need to check GetEncryptedTypes() here.
831 ReadNode passwords_root(trans);
832 if (passwords_root.InitTypeRoot(PASSWORDS) == BaseNode::INIT_OK) {
833 int64 child_id = passwords_root.GetFirstChildId();
834 while (child_id != kInvalidId) {
835 WriteNode child(trans);
836 if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK) {
837 NOTREACHED();
838 return;
840 child.SetPasswordSpecifics(child.GetPasswordSpecifics());
841 child_id = child.GetSuccessorId();
845 DVLOG(1) << "Re-encrypt everything complete.";
847 // NOTE: We notify from within a transaction.
848 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
849 OnEncryptionComplete());
852 bool SyncEncryptionHandlerImpl::ApplyNigoriUpdateImpl(
853 const sync_pb::NigoriSpecifics& nigori,
854 syncable::BaseTransaction* const trans) {
855 DCHECK(thread_checker_.CalledOnValidThread());
856 DVLOG(1) << "Applying nigori node update.";
857 bool nigori_types_need_update = !UpdateEncryptedTypesFromNigori(nigori,
858 trans);
860 if (nigori.custom_passphrase_time() != 0) {
861 custom_passphrase_time_ =
862 ProtoTimeToTime(nigori.custom_passphrase_time());
864 bool is_nigori_migrated = IsNigoriMigratedToKeystore(nigori);
865 if (is_nigori_migrated) {
866 DCHECK(nigori.has_keystore_migration_time());
867 migration_time_ = ProtoTimeToTime(nigori.keystore_migration_time());
868 PassphraseType nigori_passphrase_type =
869 ProtoPassphraseTypeToEnum(nigori.passphrase_type());
871 // Only update the local passphrase state if it's a valid transition:
872 // - implicit -> keystore
873 // - implicit -> frozen implicit
874 // - implicit -> custom
875 // - keystore -> custom
876 // Note: frozen implicit -> custom is not technically a valid transition,
877 // but we let it through here as well in case future versions do add support
878 // for this transition.
879 if (passphrase_type_ != nigori_passphrase_type &&
880 nigori_passphrase_type != IMPLICIT_PASSPHRASE &&
881 (passphrase_type_ == IMPLICIT_PASSPHRASE ||
882 nigori_passphrase_type == CUSTOM_PASSPHRASE)) {
883 DVLOG(1) << "Changing passphrase state from "
884 << PassphraseTypeToString(passphrase_type_)
885 << " to "
886 << PassphraseTypeToString(nigori_passphrase_type);
887 passphrase_type_ = nigori_passphrase_type;
888 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
889 OnPassphraseTypeChanged(
890 passphrase_type_,
891 GetExplicitPassphraseTime()));
893 if (passphrase_type_ == KEYSTORE_PASSPHRASE && encrypt_everything_) {
894 // This is the case where another client that didn't support keystore
895 // encryption attempted to enable full encryption. We detect it
896 // and switch the passphrase type to frozen implicit passphrase instead
897 // due to full encryption not being compatible with keystore passphrase.
898 // Because the local passphrase type will not match the nigori passphrase
899 // type, we will trigger a rewrite and subsequently a re-migration.
900 DVLOG(1) << "Changing passphrase state to FROZEN_IMPLICIT_PASSPHRASE "
901 << "due to full encryption.";
902 passphrase_type_ = FROZEN_IMPLICIT_PASSPHRASE;
903 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
904 OnPassphraseTypeChanged(
905 passphrase_type_,
906 GetExplicitPassphraseTime()));
908 } else {
909 // It's possible that while we're waiting for migration a client that does
910 // not have keystore encryption enabled switches to a custom passphrase.
911 if (nigori.keybag_is_frozen() &&
912 passphrase_type_ != CUSTOM_PASSPHRASE) {
913 passphrase_type_ = CUSTOM_PASSPHRASE;
914 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
915 OnPassphraseTypeChanged(
916 passphrase_type_,
917 GetExplicitPassphraseTime()));
921 Cryptographer* cryptographer = &UnlockVaultMutable(trans)->cryptographer;
922 bool nigori_needs_new_keys = false;
923 if (!nigori.encryption_keybag().blob().empty()) {
924 // We only update the default key if this was a new explicit passphrase.
925 // Else, since it was decryptable, it must not have been a new key.
926 bool need_new_default_key = false;
927 if (is_nigori_migrated) {
928 need_new_default_key = IsExplicitPassphrase(
929 ProtoPassphraseTypeToEnum(nigori.passphrase_type()));
930 } else {
931 need_new_default_key = nigori.keybag_is_frozen();
933 if (!AttemptToInstallKeybag(nigori.encryption_keybag(),
934 need_new_default_key,
935 cryptographer)) {
936 // Check to see if we can decrypt the keybag using the keystore decryptor
937 // token.
938 cryptographer->SetPendingKeys(nigori.encryption_keybag());
939 if (!nigori.keystore_decryptor_token().blob().empty() &&
940 !keystore_key_.empty()) {
941 if (DecryptPendingKeysWithKeystoreKey(keystore_key_,
942 nigori.keystore_decryptor_token(),
943 cryptographer)) {
944 nigori_needs_new_keys =
945 cryptographer->KeybagIsStale(nigori.encryption_keybag());
946 } else {
947 LOG(ERROR) << "Failed to decrypt pending keys using keystore "
948 << "bootstrap key.";
951 } else {
952 // Keybag was installed. We write back our local keybag into the nigori
953 // node if the nigori node's keybag either contains less keys or
954 // has a different default key.
955 nigori_needs_new_keys =
956 cryptographer->KeybagIsStale(nigori.encryption_keybag());
958 } else {
959 // The nigori node has an empty encryption keybag. Attempt to write our
960 // local encryption keys into it.
961 LOG(WARNING) << "Nigori had empty encryption keybag.";
962 nigori_needs_new_keys = true;
965 // If we've completed a sync cycle and the cryptographer isn't ready
966 // yet or has pending keys, prompt the user for a passphrase.
967 if (cryptographer->has_pending_keys()) {
968 DVLOG(1) << "OnPassphraseRequired Sent";
969 sync_pb::EncryptedData pending_keys = cryptographer->GetPendingKeys();
970 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
971 OnPassphraseRequired(REASON_DECRYPTION,
972 pending_keys));
973 } else if (!cryptographer->is_ready()) {
974 DVLOG(1) << "OnPassphraseRequired sent because cryptographer is not "
975 << "ready";
976 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
977 OnPassphraseRequired(REASON_ENCRYPTION,
978 sync_pb::EncryptedData()));
981 // Check if the current local encryption state is stricter/newer than the
982 // nigori state. If so, we need to overwrite the nigori node with the local
983 // state.
984 bool passphrase_type_matches = true;
985 if (!is_nigori_migrated) {
986 DCHECK(passphrase_type_ == CUSTOM_PASSPHRASE ||
987 passphrase_type_ == IMPLICIT_PASSPHRASE);
988 passphrase_type_matches =
989 nigori.keybag_is_frozen() == IsExplicitPassphrase(passphrase_type_);
990 } else {
991 passphrase_type_matches =
992 (ProtoPassphraseTypeToEnum(nigori.passphrase_type()) ==
993 passphrase_type_);
995 if (!passphrase_type_matches ||
996 nigori.encrypt_everything() != encrypt_everything_ ||
997 nigori_types_need_update ||
998 nigori_needs_new_keys) {
999 DVLOG(1) << "Triggering nigori rewrite.";
1000 return false;
1002 return true;
1005 void SyncEncryptionHandlerImpl::RewriteNigori() {
1006 DVLOG(1) << "Writing local encryption state into nigori.";
1007 DCHECK(thread_checker_.CalledOnValidThread());
1008 WriteTransaction trans(FROM_HERE, user_share_);
1009 WriteEncryptionStateToNigori(&trans);
1012 void SyncEncryptionHandlerImpl::WriteEncryptionStateToNigori(
1013 WriteTransaction* trans) {
1014 DCHECK(thread_checker_.CalledOnValidThread());
1015 WriteNode nigori_node(trans);
1016 // This can happen in tests that don't have nigori nodes.
1017 if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
1018 return;
1020 sync_pb::NigoriSpecifics nigori = nigori_node.GetNigoriSpecifics();
1021 const Cryptographer& cryptographer =
1022 UnlockVault(trans->GetWrappedTrans()).cryptographer;
1024 // Will not do anything if we shouldn't or can't migrate. Otherwise
1025 // migrates, writing the full encryption state as it does.
1026 if (!AttemptToMigrateNigoriToKeystore(trans, &nigori_node)) {
1027 if (cryptographer.is_ready() &&
1028 nigori_overwrite_count_ < kNigoriOverwriteLimit) {
1029 // Does not modify the encrypted blob if the unencrypted data already
1030 // matches what is about to be written.
1031 sync_pb::EncryptedData original_keys = nigori.encryption_keybag();
1032 if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
1033 NOTREACHED();
1035 if (nigori.encryption_keybag().SerializeAsString() !=
1036 original_keys.SerializeAsString()) {
1037 // We've updated the nigori node's encryption keys. In order to prevent
1038 // a possible looping of two clients constantly overwriting each other,
1039 // we limit the absolute number of overwrites per client instantiation.
1040 nigori_overwrite_count_++;
1041 UMA_HISTOGRAM_COUNTS("Sync.AutoNigoriOverwrites",
1042 nigori_overwrite_count_);
1045 // Note: we don't try to set keybag_is_frozen here since if that
1046 // is lost the user can always set it again (and we don't want to clobber
1047 // any migration state). The main goal at this point is to preserve
1048 // the encryption keys so all data remains decryptable.
1050 syncable::UpdateNigoriFromEncryptedTypes(
1051 UnlockVault(trans->GetWrappedTrans()).encrypted_types,
1052 encrypt_everything_,
1053 &nigori);
1054 if (!custom_passphrase_time_.is_null()) {
1055 nigori.set_custom_passphrase_time(
1056 TimeToProtoTime(custom_passphrase_time_));
1059 // If nothing has changed, this is a no-op.
1060 nigori_node.SetNigoriSpecifics(nigori);
1064 bool SyncEncryptionHandlerImpl::UpdateEncryptedTypesFromNigori(
1065 const sync_pb::NigoriSpecifics& nigori,
1066 syncable::BaseTransaction* const trans) {
1067 DCHECK(thread_checker_.CalledOnValidThread());
1068 ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
1069 if (nigori.encrypt_everything()) {
1070 EnableEncryptEverythingImpl(trans);
1071 DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1072 return true;
1073 } else if (encrypt_everything_) {
1074 DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1075 return false;
1078 ModelTypeSet nigori_encrypted_types;
1079 nigori_encrypted_types = syncable::GetEncryptedTypesFromNigori(nigori);
1080 nigori_encrypted_types.PutAll(SensitiveTypes());
1082 // If anything more than the sensitive types were encrypted, and
1083 // encrypt_everything is not explicitly set to false, we assume it means
1084 // a client intended to enable encrypt everything.
1085 if (!nigori.has_encrypt_everything() &&
1086 !Difference(nigori_encrypted_types, SensitiveTypes()).Empty()) {
1087 if (!encrypt_everything_) {
1088 encrypt_everything_ = true;
1089 *encrypted_types = EncryptableUserTypes();
1090 FOR_EACH_OBSERVER(
1091 Observer, observers_,
1092 OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
1094 DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1095 return false;
1098 MergeEncryptedTypes(nigori_encrypted_types, trans);
1099 return encrypted_types->Equals(nigori_encrypted_types);
1102 void SyncEncryptionHandlerImpl::SetCustomPassphrase(
1103 const std::string& passphrase,
1104 WriteTransaction* trans,
1105 WriteNode* nigori_node) {
1106 DCHECK(thread_checker_.CalledOnValidThread());
1107 DCHECK(IsNigoriMigratedToKeystore(nigori_node->GetNigoriSpecifics()));
1108 KeyParams key_params = {"localhost", "dummy", passphrase};
1110 if (passphrase_type_ != KEYSTORE_PASSPHRASE) {
1111 DVLOG(1) << "Failing to set a custom passphrase because one has already "
1112 << "been set.";
1113 FinishSetPassphrase(false, std::string(), trans, nigori_node);
1114 return;
1117 Cryptographer* cryptographer =
1118 &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
1119 if (cryptographer->has_pending_keys()) {
1120 // This theoretically shouldn't happen, because the only way to have pending
1121 // keys after migrating to keystore support is if a custom passphrase was
1122 // set, which should update passpshrase_state_ and should be caught by the
1123 // if statement above. For the sake of safety though, we check for it in
1124 // case a client is misbehaving.
1125 LOG(ERROR) << "Failing to set custom passphrase because of pending keys.";
1126 FinishSetPassphrase(false, std::string(), trans, nigori_node);
1127 return;
1130 std::string bootstrap_token;
1131 if (cryptographer->AddKey(key_params)) {
1132 DVLOG(1) << "Setting custom passphrase.";
1133 cryptographer->GetBootstrapToken(&bootstrap_token);
1134 passphrase_type_ = CUSTOM_PASSPHRASE;
1135 custom_passphrase_time_ = base::Time::Now();
1136 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1137 OnPassphraseTypeChanged(
1138 passphrase_type_,
1139 GetExplicitPassphraseTime()));
1140 } else {
1141 NOTREACHED() << "Failed to add key to cryptographer.";
1142 return;
1144 FinishSetPassphrase(true, bootstrap_token, trans, nigori_node);
1147 void SyncEncryptionHandlerImpl::DecryptPendingKeysWithExplicitPassphrase(
1148 const std::string& passphrase,
1149 WriteTransaction* trans,
1150 WriteNode* nigori_node) {
1151 DCHECK(thread_checker_.CalledOnValidThread());
1152 DCHECK(IsExplicitPassphrase(passphrase_type_));
1153 KeyParams key_params = {"localhost", "dummy", passphrase};
1155 Cryptographer* cryptographer =
1156 &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
1157 if (!cryptographer->has_pending_keys()) {
1158 // Note that this *can* happen in a rare situation where data is
1159 // re-encrypted on another client while a SetDecryptionPassphrase() call is
1160 // in-flight on this client. It is rare enough that we choose to do nothing.
1161 NOTREACHED() << "Attempt to set decryption passphrase failed because there "
1162 << "were no pending keys.";
1163 return;
1166 DCHECK(IsExplicitPassphrase(passphrase_type_));
1167 bool success = false;
1168 std::string bootstrap_token;
1169 if (cryptographer->DecryptPendingKeys(key_params)) {
1170 DVLOG(1) << "Explicit passphrase accepted for decryption.";
1171 cryptographer->GetBootstrapToken(&bootstrap_token);
1172 success = true;
1173 } else {
1174 DVLOG(1) << "Explicit passphrase failed to decrypt.";
1175 success = false;
1177 if (success && !keystore_key_.empty()) {
1178 // Should already be part of the encryption keybag, but we add it just
1179 // in case.
1180 KeyParams key_params = {"localhost", "dummy", keystore_key_};
1181 cryptographer->AddNonDefaultKey(key_params);
1183 FinishSetPassphrase(success, bootstrap_token, trans, nigori_node);
1186 void SyncEncryptionHandlerImpl::FinishSetPassphrase(
1187 bool success,
1188 const std::string& bootstrap_token,
1189 WriteTransaction* trans,
1190 WriteNode* nigori_node) {
1191 DCHECK(thread_checker_.CalledOnValidThread());
1192 FOR_EACH_OBSERVER(
1193 SyncEncryptionHandler::Observer,
1194 observers_,
1195 OnCryptographerStateChanged(
1196 &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer));
1198 // It's possible we need to change the bootstrap token even if we failed to
1199 // set the passphrase (for example if we need to preserve the new GAIA
1200 // passphrase).
1201 if (!bootstrap_token.empty()) {
1202 DVLOG(1) << "Passphrase bootstrap token updated.";
1203 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1204 OnBootstrapTokenUpdated(bootstrap_token,
1205 PASSPHRASE_BOOTSTRAP_TOKEN));
1208 const Cryptographer& cryptographer =
1209 UnlockVault(trans->GetWrappedTrans()).cryptographer;
1210 if (!success) {
1211 if (cryptographer.is_ready()) {
1212 LOG(ERROR) << "Attempt to change passphrase failed while cryptographer "
1213 << "was ready.";
1214 } else if (cryptographer.has_pending_keys()) {
1215 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1216 OnPassphraseRequired(REASON_DECRYPTION,
1217 cryptographer.GetPendingKeys()));
1218 } else {
1219 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1220 OnPassphraseRequired(REASON_ENCRYPTION,
1221 sync_pb::EncryptedData()));
1223 return;
1225 DCHECK(success);
1226 DCHECK(cryptographer.is_ready());
1228 // Will do nothing if we're already properly migrated or unable to migrate
1229 // (in otherwords, if ShouldTriggerMigration is false).
1230 // Otherwise will update the nigori node with the current migrated state,
1231 // writing all encryption state as it does.
1232 if (!AttemptToMigrateNigoriToKeystore(trans, nigori_node)) {
1233 sync_pb::NigoriSpecifics nigori(nigori_node->GetNigoriSpecifics());
1234 // Does not modify nigori.encryption_keybag() if the original decrypted
1235 // data was the same.
1236 if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
1237 NOTREACHED();
1238 if (IsNigoriMigratedToKeystore(nigori)) {
1239 DCHECK(keystore_key_.empty() || IsExplicitPassphrase(passphrase_type_));
1240 DVLOG(1) << "Leaving nigori migration state untouched after setting"
1241 << " passphrase.";
1242 } else {
1243 nigori.set_keybag_is_frozen(
1244 IsExplicitPassphrase(passphrase_type_));
1246 // If we set a new custom passphrase, store the timestamp.
1247 if (!custom_passphrase_time_.is_null()) {
1248 nigori.set_custom_passphrase_time(
1249 TimeToProtoTime(custom_passphrase_time_));
1251 nigori_node->SetNigoriSpecifics(nigori);
1254 // Must do this after OnPassphraseTypeChanged, in order to ensure the PSS
1255 // checks the passphrase state after it has been set.
1256 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1257 OnPassphraseAccepted());
1259 // Does nothing if everything is already encrypted.
1260 // TODO(zea): If we just migrated and enabled encryption, this will be
1261 // redundant. Figure out a way to not do this unnecessarily.
1262 ReEncryptEverything(trans);
1265 void SyncEncryptionHandlerImpl::MergeEncryptedTypes(
1266 ModelTypeSet new_encrypted_types,
1267 syncable::BaseTransaction* const trans) {
1268 DCHECK(thread_checker_.CalledOnValidThread());
1270 // Only UserTypes may be encrypted.
1271 DCHECK(EncryptableUserTypes().HasAll(new_encrypted_types));
1273 ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
1274 if (!encrypted_types->HasAll(new_encrypted_types)) {
1275 *encrypted_types = new_encrypted_types;
1276 FOR_EACH_OBSERVER(
1277 Observer, observers_,
1278 OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
1282 SyncEncryptionHandlerImpl::Vault* SyncEncryptionHandlerImpl::UnlockVaultMutable(
1283 syncable::BaseTransaction* const trans) {
1284 DCHECK_EQ(user_share_->directory.get(), trans->directory());
1285 return &vault_unsafe_;
1288 const SyncEncryptionHandlerImpl::Vault& SyncEncryptionHandlerImpl::UnlockVault(
1289 syncable::BaseTransaction* const trans) const {
1290 DCHECK_EQ(user_share_->directory.get(), trans->directory());
1291 return vault_unsafe_;
1294 bool SyncEncryptionHandlerImpl::ShouldTriggerMigration(
1295 const sync_pb::NigoriSpecifics& nigori,
1296 const Cryptographer& cryptographer) const {
1297 DCHECK(thread_checker_.CalledOnValidThread());
1298 // Don't migrate if there are pending encryption keys (because data
1299 // encrypted with the pending keys will not be decryptable).
1300 if (cryptographer.has_pending_keys())
1301 return false;
1302 if (IsNigoriMigratedToKeystore(nigori)) {
1303 // If the nigori is already migrated but does not reflect the explicit
1304 // passphrase state, remigrate. Similarly, if the nigori has an explicit
1305 // passphrase but does not have full encryption, or the nigori has an
1306 // implicit passphrase but does have full encryption, re-migrate.
1307 // Note that this is to defend against other clients without keystore
1308 // encryption enabled transitioning to states that are no longer valid.
1309 if (passphrase_type_ != KEYSTORE_PASSPHRASE &&
1310 nigori.passphrase_type() ==
1311 sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE) {
1312 return true;
1313 } else if (IsExplicitPassphrase(passphrase_type_) &&
1314 !encrypt_everything_) {
1315 return true;
1316 } else if (passphrase_type_ == KEYSTORE_PASSPHRASE &&
1317 encrypt_everything_) {
1318 return true;
1319 } else if (
1320 cryptographer.is_ready() &&
1321 !cryptographer.CanDecryptUsingDefaultKey(nigori.encryption_keybag())) {
1322 // We need to overwrite the keybag. This might involve overwriting the
1323 // keystore decryptor too.
1324 return true;
1325 } else if (old_keystore_keys_.size() > 0 && !keystore_key_.empty()) {
1326 // Check to see if a server key rotation has happened, but the nigori
1327 // node's keys haven't been rotated yet, and hence we should re-migrate.
1328 // Note that once a key rotation has been performed, we no longer
1329 // preserve backwards compatibility, and the keybag will therefore be
1330 // encrypted with the current keystore key.
1331 Cryptographer temp_cryptographer(cryptographer.encryptor());
1332 KeyParams keystore_params = {"localhost", "dummy", keystore_key_};
1333 temp_cryptographer.AddKey(keystore_params);
1334 if (!temp_cryptographer.CanDecryptUsingDefaultKey(
1335 nigori.encryption_keybag())) {
1336 return true;
1339 return false;
1340 } else if (keystore_key_.empty()) {
1341 // If we haven't already migrated, we don't want to do anything unless
1342 // a keystore key is available (so that those clients without keystore
1343 // encryption enabled aren't forced into new states, e.g. frozen implicit
1344 // passphrase).
1345 return false;
1347 return true;
1350 bool SyncEncryptionHandlerImpl::AttemptToMigrateNigoriToKeystore(
1351 WriteTransaction* trans,
1352 WriteNode* nigori_node) {
1353 DCHECK(thread_checker_.CalledOnValidThread());
1354 const sync_pb::NigoriSpecifics& old_nigori =
1355 nigori_node->GetNigoriSpecifics();
1356 Cryptographer* cryptographer =
1357 &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
1359 if (!ShouldTriggerMigration(old_nigori, *cryptographer))
1360 return false;
1362 DVLOG(1) << "Starting nigori migration to keystore support.";
1363 sync_pb::NigoriSpecifics migrated_nigori(old_nigori);
1365 PassphraseType new_passphrase_type = passphrase_type_;
1366 bool new_encrypt_everything = encrypt_everything_;
1367 if (encrypt_everything_ && !IsExplicitPassphrase(passphrase_type_)) {
1368 DVLOG(1) << "Switching to frozen implicit passphrase due to already having "
1369 << "full encryption.";
1370 new_passphrase_type = FROZEN_IMPLICIT_PASSPHRASE;
1371 migrated_nigori.clear_keystore_decryptor_token();
1372 } else if (IsExplicitPassphrase(passphrase_type_)) {
1373 DVLOG_IF(1, !encrypt_everything_) << "Enabling encrypt everything due to "
1374 << "explicit passphrase";
1375 new_encrypt_everything = true;
1376 migrated_nigori.clear_keystore_decryptor_token();
1377 } else {
1378 DCHECK(!encrypt_everything_);
1379 new_passphrase_type = KEYSTORE_PASSPHRASE;
1380 DVLOG(1) << "Switching to keystore passphrase state.";
1382 migrated_nigori.set_encrypt_everything(new_encrypt_everything);
1383 migrated_nigori.set_passphrase_type(
1384 EnumPassphraseTypeToProto(new_passphrase_type));
1385 migrated_nigori.set_keybag_is_frozen(true);
1387 if (!keystore_key_.empty()) {
1388 KeyParams key_params = {"localhost", "dummy", keystore_key_};
1389 if ((old_keystore_keys_.size() > 0 &&
1390 new_passphrase_type == KEYSTORE_PASSPHRASE) ||
1391 !cryptographer->is_initialized()) {
1392 // Either at least one key rotation has been performed, so we no longer
1393 // care about backwards compatibility, or we're generating keystore-based
1394 // encryption keys without knowing the GAIA password (and therefore the
1395 // cryptographer is not initialized), so we can't support backwards
1396 // compatibility. Ensure the keystore key is the default key.
1397 DVLOG(1) << "Migrating keybag to keystore key.";
1398 bool cryptographer_was_ready = cryptographer->is_ready();
1399 if (!cryptographer->AddKey(key_params)) {
1400 LOG(ERROR) << "Failed to add keystore key as default key";
1401 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1402 FAILED_TO_SET_DEFAULT_KEYSTORE,
1403 MIGRATION_RESULT_SIZE);
1404 return false;
1406 if (!cryptographer_was_ready && cryptographer->is_ready()) {
1407 FOR_EACH_OBSERVER(
1408 SyncEncryptionHandler::Observer,
1409 observers_,
1410 OnPassphraseAccepted());
1412 } else {
1413 // We're in backwards compatible mode -- either the account has an
1414 // explicit passphrase, or we want to preserve the current GAIA-based key
1415 // as the default because we can (there have been no key rotations since
1416 // the migration).
1417 DVLOG(1) << "Migrating keybag while preserving old key";
1418 if (!cryptographer->AddNonDefaultKey(key_params)) {
1419 LOG(ERROR) << "Failed to add keystore key as non-default key.";
1420 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1421 FAILED_TO_SET_NONDEFAULT_KEYSTORE,
1422 MIGRATION_RESULT_SIZE);
1423 return false;
1427 if (!old_keystore_keys_.empty()) {
1428 // Go through and add all the old keystore keys as non default keys, so
1429 // they'll be preserved in the encryption_keybag when we next write the
1430 // nigori node.
1431 for (std::vector<std::string>::const_iterator iter =
1432 old_keystore_keys_.begin(); iter != old_keystore_keys_.end();
1433 ++iter) {
1434 KeyParams key_params = {"localhost", "dummy", *iter};
1435 cryptographer->AddNonDefaultKey(key_params);
1438 if (new_passphrase_type == KEYSTORE_PASSPHRASE &&
1439 !GetKeystoreDecryptor(
1440 *cryptographer,
1441 keystore_key_,
1442 migrated_nigori.mutable_keystore_decryptor_token())) {
1443 LOG(ERROR) << "Failed to extract keystore decryptor token.";
1444 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1445 FAILED_TO_EXTRACT_DECRYPTOR,
1446 MIGRATION_RESULT_SIZE);
1447 return false;
1449 if (!cryptographer->GetKeys(migrated_nigori.mutable_encryption_keybag())) {
1450 LOG(ERROR) << "Failed to extract encryption keybag.";
1451 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1452 FAILED_TO_EXTRACT_KEYBAG,
1453 MIGRATION_RESULT_SIZE);
1454 return false;
1457 if (migration_time_.is_null())
1458 migration_time_ = base::Time::Now();
1459 migrated_nigori.set_keystore_migration_time(TimeToProtoTime(migration_time_));
1461 if (!custom_passphrase_time_.is_null()) {
1462 migrated_nigori.set_custom_passphrase_time(
1463 TimeToProtoTime(custom_passphrase_time_));
1466 FOR_EACH_OBSERVER(
1467 SyncEncryptionHandler::Observer,
1468 observers_,
1469 OnCryptographerStateChanged(cryptographer));
1470 if (passphrase_type_ != new_passphrase_type) {
1471 passphrase_type_ = new_passphrase_type;
1472 FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1473 OnPassphraseTypeChanged(
1474 passphrase_type_,
1475 GetExplicitPassphraseTime()));
1478 if (new_encrypt_everything && !encrypt_everything_) {
1479 EnableEncryptEverythingImpl(trans->GetWrappedTrans());
1480 ReEncryptEverything(trans);
1481 } else if (!cryptographer->CanDecryptUsingDefaultKey(
1482 old_nigori.encryption_keybag())) {
1483 DVLOG(1) << "Rencrypting everything due to key rotation.";
1484 ReEncryptEverything(trans);
1487 DVLOG(1) << "Completing nigori migration to keystore support.";
1488 nigori_node->SetNigoriSpecifics(migrated_nigori);
1490 switch (new_passphrase_type) {
1491 case KEYSTORE_PASSPHRASE:
1492 if (old_keystore_keys_.size() > 0) {
1493 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1494 MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
1495 MIGRATION_RESULT_SIZE);
1496 } else {
1497 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1498 MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
1499 MIGRATION_RESULT_SIZE);
1501 break;
1502 case FROZEN_IMPLICIT_PASSPHRASE:
1503 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1504 MIGRATION_SUCCESS_FROZEN_IMPLICIT,
1505 MIGRATION_RESULT_SIZE);
1506 break;
1507 case CUSTOM_PASSPHRASE:
1508 UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1509 MIGRATION_SUCCESS_CUSTOM,
1510 MIGRATION_RESULT_SIZE);
1511 break;
1512 default:
1513 NOTREACHED();
1514 break;
1516 return true;
1519 bool SyncEncryptionHandlerImpl::GetKeystoreDecryptor(
1520 const Cryptographer& cryptographer,
1521 const std::string& keystore_key,
1522 sync_pb::EncryptedData* encrypted_blob) {
1523 DCHECK(thread_checker_.CalledOnValidThread());
1524 DCHECK(!keystore_key.empty());
1525 DCHECK(cryptographer.is_ready());
1526 std::string serialized_nigori;
1527 serialized_nigori = cryptographer.GetDefaultNigoriKeyData();
1528 if (serialized_nigori.empty()) {
1529 LOG(ERROR) << "Failed to get cryptographer bootstrap token.";
1530 return false;
1532 Cryptographer temp_cryptographer(cryptographer.encryptor());
1533 KeyParams key_params = {"localhost", "dummy", keystore_key};
1534 if (!temp_cryptographer.AddKey(key_params))
1535 return false;
1536 if (!temp_cryptographer.EncryptString(serialized_nigori, encrypted_blob))
1537 return false;
1538 return true;
1541 bool SyncEncryptionHandlerImpl::AttemptToInstallKeybag(
1542 const sync_pb::EncryptedData& keybag,
1543 bool update_default,
1544 Cryptographer* cryptographer) {
1545 if (!cryptographer->CanDecrypt(keybag))
1546 return false;
1547 cryptographer->InstallKeys(keybag);
1548 if (update_default)
1549 cryptographer->SetDefaultKey(keybag.key_name());
1550 return true;
1553 void SyncEncryptionHandlerImpl::EnableEncryptEverythingImpl(
1554 syncable::BaseTransaction* const trans) {
1555 ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
1556 if (encrypt_everything_) {
1557 DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1558 return;
1560 encrypt_everything_ = true;
1561 *encrypted_types = EncryptableUserTypes();
1562 FOR_EACH_OBSERVER(
1563 Observer, observers_,
1564 OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
1567 bool SyncEncryptionHandlerImpl::DecryptPendingKeysWithKeystoreKey(
1568 const std::string& keystore_key,
1569 const sync_pb::EncryptedData& keystore_decryptor_token,
1570 Cryptographer* cryptographer) {
1571 DCHECK(cryptographer->has_pending_keys());
1572 if (keystore_decryptor_token.blob().empty())
1573 return false;
1574 Cryptographer temp_cryptographer(cryptographer->encryptor());
1576 // First, go through and all all the old keystore keys to the temporary
1577 // cryptographer.
1578 for (size_t i = 0; i < old_keystore_keys_.size(); ++i) {
1579 KeyParams old_key_params = {"localhost", "dummy", old_keystore_keys_[i]};
1580 temp_cryptographer.AddKey(old_key_params);
1583 // Then add the current keystore key as the default key and see if we can
1584 // decrypt.
1585 KeyParams keystore_params = {"localhost", "dummy", keystore_key_};
1586 if (temp_cryptographer.AddKey(keystore_params) &&
1587 temp_cryptographer.CanDecrypt(keystore_decryptor_token)) {
1588 // Someone else migrated the nigori for us! How generous! Go ahead and
1589 // install both the keystore key and the new default encryption key
1590 // (i.e. the one provided by the keystore decryptor token) into the
1591 // cryptographer.
1592 // The keystore decryptor token is a keystore key encrypted blob containing
1593 // the current serialized default encryption key (and as such should be
1594 // able to decrypt the nigori node's encryption keybag).
1595 // Note: it's possible a key rotation has happened since the migration, and
1596 // we're decrypting using an old keystore key. In that case we need to
1597 // ensure we re-encrypt using the newest key.
1598 DVLOG(1) << "Attempting to decrypt pending keys using "
1599 << "keystore decryptor token.";
1600 std::string serialized_nigori =
1601 temp_cryptographer.DecryptToString(keystore_decryptor_token);
1603 // This will decrypt the pending keys and add them if possible. The key
1604 // within |serialized_nigori| will be the default after.
1605 cryptographer->ImportNigoriKey(serialized_nigori);
1607 if (!temp_cryptographer.CanDecryptUsingDefaultKey(
1608 keystore_decryptor_token)) {
1609 // The keystore decryptor token was derived from an old keystore key.
1610 // A key rotation is necessary, so set the current keystore key as the
1611 // default key (which will trigger a re-migration).
1612 DVLOG(1) << "Pending keys based on old keystore key. Setting newest "
1613 << "keystore key as default.";
1614 cryptographer->AddKey(keystore_params);
1615 } else {
1616 // Theoretically the encryption keybag should already contain the keystore
1617 // key. We explicitly add it as a safety measure.
1618 DVLOG(1) << "Pending keys based on newest keystore key.";
1619 cryptographer->AddNonDefaultKey(keystore_params);
1621 if (cryptographer->is_ready()) {
1622 std::string bootstrap_token;
1623 cryptographer->GetBootstrapToken(&bootstrap_token);
1624 DVLOG(1) << "Keystore decryptor token decrypted pending keys.";
1625 FOR_EACH_OBSERVER(
1626 SyncEncryptionHandler::Observer,
1627 observers_,
1628 OnPassphraseAccepted());
1629 FOR_EACH_OBSERVER(
1630 SyncEncryptionHandler::Observer,
1631 observers_,
1632 OnBootstrapTokenUpdated(bootstrap_token,
1633 PASSPHRASE_BOOTSTRAP_TOKEN));
1634 FOR_EACH_OBSERVER(
1635 SyncEncryptionHandler::Observer,
1636 observers_,
1637 OnCryptographerStateChanged(cryptographer));
1638 return true;
1641 return false;
1644 base::Time SyncEncryptionHandlerImpl::GetExplicitPassphraseTime() const {
1645 if (passphrase_type_ == FROZEN_IMPLICIT_PASSPHRASE)
1646 return migration_time();
1647 else if (passphrase_type_ == CUSTOM_PASSPHRASE)
1648 return custom_passphrase_time();
1649 return base::Time();
1652 } // namespace browser_sync