Home | History | Annotate | Download | only in internal_api
      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.
      4 
      5 #include "sync/internal_api/sync_encryption_handler_impl.h"
      6 
      7 #include <queue>
      8 #include <string>
      9 
     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"
     34 
     35 namespace syncer {
     36 
     37 namespace {
     38 
     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;
     45 
     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,
     57 };
     58 
     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,
     65 };
     66 
     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;
     91 }
     92 
     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;
    107   };
    108 }
    109 
    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;
    124   };
    125 }
    126 
    127 bool IsExplicitPassphrase(PassphraseType type) {
    128   return type == CUSTOM_PASSPHRASE || type == FROZEN_IMPLICIT_PASSPHRASE;
    129 }
    130 
    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();
    140 
    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);
    145 
    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;
    158 }
    159 
    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;
    171   }
    172   std::string decrypted_keystore_bootstrap;
    173   if (!encryptor->DecryptString(base64_decoded_keystore_bootstrap,
    174                                 &decrypted_keystore_bootstrap)) {
    175     return false;
    176   }
    177   JSONStringValueSerializer json(&decrypted_keystore_bootstrap);
    178   scoped_ptr<base::Value> deserialized_keystore_keys(
    179       json.Deserialize(NULL, NULL));
    180   if (!deserialized_keystore_keys)
    181     return false;
    182   base::ListValue* internal_list_value = NULL;
    183   if (!deserialized_keystore_keys->GetAsList(&internal_list_value))
    184     return false;
    185   int number_of_keystore_keys = internal_list_value->GetSize();
    186   if (!internal_list_value->GetString(number_of_keystore_keys - 1,
    187                                       current_keystore_key)) {
    188     return false;
    189   }
    190   old_keystore_keys->resize(number_of_keystore_keys - 1);
    191   for (int i = 0; i < number_of_keystore_keys - 1; ++i)
    192     internal_list_value->GetString(i, &(*old_keystore_keys)[i]);
    193   return true;
    194 }
    195 
    196 }  // namespace
    197 
    198 SyncEncryptionHandlerImpl::Vault::Vault(
    199     Encryptor* encryptor,
    200     ModelTypeSet encrypted_types)
    201     : cryptographer(encryptor),
    202       encrypted_types(encrypted_types) {
    203 }
    204 
    205 SyncEncryptionHandlerImpl::Vault::~Vault() {
    206 }
    207 
    208 SyncEncryptionHandlerImpl::SyncEncryptionHandlerImpl(
    209     UserShare* user_share,
    210     Encryptor* encryptor,
    211     const std::string& restored_key_for_bootstrapping,
    212     const std::string& restored_keystore_key_for_bootstrapping)
    213     : weak_ptr_factory_(this),
    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   // Restore the cryptographer's previous keys. Note that we don't add the
    220   // keystore keys into the cryptographer here, in case a migration was pending.
    221   vault_unsafe_.cryptographer.Bootstrap(restored_key_for_bootstrapping);
    222 
    223   // If this fails, we won't have a valid keystore key, and will simply request
    224   // new ones from the server on the next DownloadUpdates.
    225   UnpackKeystoreBootstrapToken(
    226       restored_keystore_key_for_bootstrapping,
    227       encryptor,
    228       &old_keystore_keys_,
    229       &keystore_key_);
    230 }
    231 
    232 SyncEncryptionHandlerImpl::~SyncEncryptionHandlerImpl() {}
    233 
    234 void SyncEncryptionHandlerImpl::AddObserver(Observer* observer) {
    235   DCHECK(thread_checker_.CalledOnValidThread());
    236   DCHECK(!observers_.HasObserver(observer));
    237   observers_.AddObserver(observer);
    238 }
    239 
    240 void SyncEncryptionHandlerImpl::RemoveObserver(Observer* observer) {
    241   DCHECK(thread_checker_.CalledOnValidThread());
    242   DCHECK(observers_.HasObserver(observer));
    243   observers_.RemoveObserver(observer);
    244 }
    245 
    246 void SyncEncryptionHandlerImpl::Init() {
    247   DCHECK(thread_checker_.CalledOnValidThread());
    248   WriteTransaction trans(FROM_HERE, user_share_);
    249   WriteNode node(&trans);
    250 
    251   if (node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK)
    252     return;
    253   if (!ApplyNigoriUpdateImpl(node.GetNigoriSpecifics(),
    254                              trans.GetWrappedTrans())) {
    255     WriteEncryptionStateToNigori(&trans);
    256   }
    257 
    258   bool has_pending_keys = UnlockVault(
    259       trans.GetWrappedTrans()).cryptographer.has_pending_keys();
    260   bool is_ready = UnlockVault(
    261       trans.GetWrappedTrans()).cryptographer.is_ready();
    262   // Log the state of the cryptographer regardless of migration state.
    263   UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerReady", is_ready);
    264   UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerPendingKeys", has_pending_keys);
    265   if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics())) {
    266     // This account has a nigori node that has been migrated to support
    267     // keystore.
    268     UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
    269                               MIGRATED,
    270                               MIGRATION_STATE_SIZE);
    271     if (has_pending_keys && passphrase_type_ == KEYSTORE_PASSPHRASE) {
    272       // If this is happening, it means the keystore decryptor is either
    273       // undecryptable with the available keystore keys or does not match the
    274       // nigori keybag's encryption key. Otherwise we're simply missing the
    275       // keystore key.
    276       UMA_HISTOGRAM_BOOLEAN("Sync.KeystoreDecryptionFailed",
    277                             !keystore_key_.empty());
    278     }
    279   } else if (!is_ready) {
    280     // Migration cannot occur until the cryptographer is ready (initialized
    281     // with GAIA password and any pending keys resolved).
    282     UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
    283                               NOT_MIGRATED_CRYPTO_NOT_READY,
    284                               MIGRATION_STATE_SIZE);
    285   } else if (keystore_key_.empty()) {
    286     // The client has no keystore key, either because it is not yet enabled or
    287     // the server is not sending a valid keystore key.
    288     UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
    289                               NOT_MIGRATED_NO_KEYSTORE_KEY,
    290                               MIGRATION_STATE_SIZE);
    291   } else {
    292     // If the above conditions have been met and the nigori node is still not
    293     // migrated, something failed in the migration process.
    294     UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
    295                               NOT_MIGRATED_UNKNOWN_REASON,
    296                               MIGRATION_STATE_SIZE);
    297   }
    298 
    299 
    300   // Always trigger an encrypted types and cryptographer state change event at
    301   // init time so observers get the initial values.
    302   FOR_EACH_OBSERVER(
    303       Observer, observers_,
    304       OnEncryptedTypesChanged(
    305           UnlockVault(trans.GetWrappedTrans()).encrypted_types,
    306           encrypt_everything_));
    307   FOR_EACH_OBSERVER(
    308       SyncEncryptionHandler::Observer,
    309       observers_,
    310       OnCryptographerStateChanged(
    311           &UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer));
    312 
    313   // If the cryptographer is not ready (either it has pending keys or we
    314   // failed to initialize it), we don't want to try and re-encrypt the data.
    315   // If we had encrypted types, the DataTypeManager will block, preventing
    316   // sync from happening until the the passphrase is provided.
    317   if (UnlockVault(trans.GetWrappedTrans()).cryptographer.is_ready())
    318     ReEncryptEverything(&trans);
    319 }
    320 
    321 void SyncEncryptionHandlerImpl::SetEncryptionPassphrase(
    322     const std::string& passphrase,
    323     bool is_explicit) {
    324   DCHECK(thread_checker_.CalledOnValidThread());
    325   // We do not accept empty passphrases.
    326   if (passphrase.empty()) {
    327     NOTREACHED() << "Cannot encrypt with an empty passphrase.";
    328     return;
    329   }
    330 
    331   // All accesses to the cryptographer are protected by a transaction.
    332   WriteTransaction trans(FROM_HERE, user_share_);
    333   KeyParams key_params = {"localhost", "dummy", passphrase};
    334   WriteNode node(&trans);
    335   if (node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK) {
    336     NOTREACHED();
    337     return;
    338   }
    339 
    340   Cryptographer* cryptographer =
    341       &UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
    342 
    343   // Once we've migrated to keystore, the only way to set a passphrase for
    344   // encryption is to set a custom passphrase.
    345   if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics())) {
    346     if (!is_explicit) {
    347       DCHECK(cryptographer->is_ready());
    348       // The user is setting a new implicit passphrase. At this point we don't
    349       // care, so drop it on the floor. This is safe because if we have a
    350       // migrated nigori node, then we don't need to create an initial
    351       // encryption key.
    352       LOG(WARNING) << "Ignoring new implicit passphrase. Keystore migration "
    353                    << "already performed.";
    354       return;
    355     }
    356     // Will fail if we already have an explicit passphrase or we have pending
    357     // keys.
    358     SetCustomPassphrase(passphrase, &trans, &node);
    359 
    360     // When keystore migration occurs, the "CustomEncryption" UMA stat must be
    361     // logged as true.
    362     UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
    363     return;
    364   }
    365 
    366   std::string bootstrap_token;
    367   sync_pb::EncryptedData pending_keys;
    368   if (cryptographer->has_pending_keys())
    369     pending_keys = cryptographer->GetPendingKeys();
    370   bool success = false;
    371 
    372   // There are six cases to handle here:
    373   // 1. The user has no pending keys and is setting their current GAIA password
    374   //    as the encryption passphrase. This happens either during first time sync
    375   //    with a clean profile, or after re-authenticating on a profile that was
    376   //    already signed in with the cryptographer ready.
    377   // 2. The user has no pending keys, and is overwriting an (already provided)
    378   //    implicit passphrase with an explicit (custom) passphrase.
    379   // 3. The user has pending keys for an explicit passphrase that is somehow set
    380   //    to their current GAIA passphrase.
    381   // 4. The user has pending keys encrypted with their current GAIA passphrase
    382   //    and the caller passes in the current GAIA passphrase.
    383   // 5. The user has pending keys encrypted with an older GAIA passphrase
    384   //    and the caller passes in the current GAIA passphrase.
    385   // 6. The user has previously done encryption with an explicit passphrase.
    386   // Furthermore, we enforce the fact that the bootstrap encryption token will
    387   // always be derived from the newest GAIA password if the account is using
    388   // an implicit passphrase (even if the data is encrypted with an old GAIA
    389   // password). If the account is using an explicit (custom) passphrase, the
    390   // bootstrap token will be derived from the most recently provided explicit
    391   // passphrase (that was able to decrypt the data).
    392   if (!IsExplicitPassphrase(passphrase_type_)) {
    393     if (!cryptographer->has_pending_keys()) {
    394       if (cryptographer->AddKey(key_params)) {
    395         // Case 1 and 2. We set a new GAIA passphrase when there are no pending
    396         // keys (1), or overwriting an implicit passphrase with a new explicit
    397         // one (2) when there are no pending keys.
    398         if (is_explicit) {
    399           DVLOG(1) << "Setting explicit passphrase for encryption.";
    400           passphrase_type_ = CUSTOM_PASSPHRASE;
    401           custom_passphrase_time_ = base::Time::Now();
    402           FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
    403                             OnPassphraseTypeChanged(
    404                                 passphrase_type_,
    405                                 GetExplicitPassphraseTime()));
    406         } else {
    407           DVLOG(1) << "Setting implicit passphrase for encryption.";
    408         }
    409         cryptographer->GetBootstrapToken(&bootstrap_token);
    410 
    411         // With M26, sync accounts can be in only one of two encryption states:
    412         // 1) Encrypt only passwords with an implicit passphrase.
    413         // 2) Encrypt all sync datatypes with an explicit passphrase.
    414         // We deprecate the "EncryptAllData" and "CustomPassphrase" histograms,
    415         // and keep track of an account's encryption state via the
    416         // "CustomEncryption" histogram. See http://crbug.com/131478.
    417         UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", is_explicit);
    418 
    419         success = true;
    420       } else {
    421         NOTREACHED() << "Failed to add key to cryptographer.";
    422         success = false;
    423       }
    424     } else {  // cryptographer->has_pending_keys() == true
    425       if (is_explicit) {
    426         // This can only happen if the nigori node is updated with a new
    427         // implicit passphrase while a client is attempting to set a new custom
    428         // passphrase (race condition).
    429         DVLOG(1) << "Failing because an implicit passphrase is already set.";
    430         success = false;
    431       } else {  // is_explicit == false
    432         if (cryptographer->DecryptPendingKeys(key_params)) {
    433           // Case 4. We successfully decrypted with the implicit GAIA passphrase
    434           // passed in.
    435           DVLOG(1) << "Implicit internal passphrase accepted for decryption.";
    436           cryptographer->GetBootstrapToken(&bootstrap_token);
    437           success = true;
    438         } else {
    439           // Case 5. Encryption was done with an old GAIA password, but we were
    440           // provided with the current GAIA password. We need to generate a new
    441           // bootstrap token to preserve it. We build a temporary cryptographer
    442           // to allow us to extract these params without polluting our current
    443           // cryptographer.
    444           DVLOG(1) << "Implicit internal passphrase failed to decrypt, adding "
    445                    << "anyways as default passphrase and persisting via "
    446                    << "bootstrap token.";
    447           Cryptographer temp_cryptographer(cryptographer->encryptor());
    448           temp_cryptographer.AddKey(key_params);
    449           temp_cryptographer.GetBootstrapToken(&bootstrap_token);
    450           // We then set the new passphrase as the default passphrase of the
    451           // real cryptographer, even though we have pending keys. This is safe,
    452           // as although Cryptographer::is_initialized() will now be true,
    453           // is_ready() will remain false due to having pending keys.
    454           cryptographer->AddKey(key_params);
    455           success = false;
    456         }
    457       }  // is_explicit
    458     }  // cryptographer->has_pending_keys()
    459   } else {  // IsExplicitPassphrase(passphrase_type_) == true.
    460     // Case 6. We do not want to override a previously set explicit passphrase,
    461     // so we return a failure.
    462     DVLOG(1) << "Failing because an explicit passphrase is already set.";
    463     success = false;
    464   }
    465 
    466   DVLOG_IF(1, !success)
    467       << "Failure in SetEncryptionPassphrase; notifying and returning.";
    468   DVLOG_IF(1, success)
    469       << "Successfully set encryption passphrase; updating nigori and "
    470          "reencrypting.";
    471 
    472   FinishSetPassphrase(success, bootstrap_token, &trans, &node);
    473 }
    474 
    475 void SyncEncryptionHandlerImpl::SetDecryptionPassphrase(
    476     const std::string& passphrase) {
    477   DCHECK(thread_checker_.CalledOnValidThread());
    478   // We do not accept empty passphrases.
    479   if (passphrase.empty()) {
    480     NOTREACHED() << "Cannot decrypt with an empty passphrase.";
    481     return;
    482   }
    483 
    484   // All accesses to the cryptographer are protected by a transaction.
    485   WriteTransaction trans(FROM_HERE, user_share_);
    486   KeyParams key_params = {"localhost", "dummy", passphrase};
    487   WriteNode node(&trans);
    488   if (node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK) {
    489     NOTREACHED();
    490     return;
    491   }
    492 
    493   // Once we've migrated to keystore, we're only ever decrypting keys derived
    494   // from an explicit passphrase. But, for clients without a keystore key yet
    495   // (either not on by default or failed to download one), we still support
    496   // decrypting with a gaia passphrase, and therefore bypass the
    497   // DecryptPendingKeysWithExplicitPassphrase logic.
    498   if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics()) &&
    499       IsExplicitPassphrase(passphrase_type_)) {
    500     DecryptPendingKeysWithExplicitPassphrase(passphrase, &trans, &node);
    501     return;
    502   }
    503 
    504   Cryptographer* cryptographer =
    505       &UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
    506   if (!cryptographer->has_pending_keys()) {
    507     // Note that this *can* happen in a rare situation where data is
    508     // re-encrypted on another client while a SetDecryptionPassphrase() call is
    509     // in-flight on this client. It is rare enough that we choose to do nothing.
    510     NOTREACHED() << "Attempt to set decryption passphrase failed because there "
    511                  << "were no pending keys.";
    512     return;
    513   }
    514 
    515   std::string bootstrap_token;
    516   sync_pb::EncryptedData pending_keys;
    517   pending_keys = cryptographer->GetPendingKeys();
    518   bool success = false;
    519 
    520   // There are three cases to handle here:
    521   // 7. We're using the current GAIA password to decrypt the pending keys. This
    522   //    happens when signing in to an account with a previously set implicit
    523   //    passphrase, where the data is already encrypted with the newest GAIA
    524   //    password.
    525   // 8. The user is providing an old GAIA password to decrypt the pending keys.
    526   //    In this case, the user is using an implicit passphrase, but has changed
    527   //    their password since they last encrypted their data, and therefore
    528   //    their current GAIA password was unable to decrypt the data. This will
    529   //    happen when the user is setting up a new profile with a previously
    530   //    encrypted account (after changing passwords).
    531   // 9. The user is providing a previously set explicit passphrase to decrypt
    532   //    the pending keys.
    533   if (!IsExplicitPassphrase(passphrase_type_)) {
    534     if (cryptographer->is_initialized()) {
    535       // We only want to change the default encryption key to the pending
    536       // one if the pending keybag already contains the current default.
    537       // This covers the case where a different client re-encrypted
    538       // everything with a newer gaia passphrase (and hence the keybag
    539       // contains keys from all previously used gaia passphrases).
    540       // Otherwise, we're in a situation where the pending keys are
    541       // encrypted with an old gaia passphrase, while the default is the
    542       // current gaia passphrase. In that case, we preserve the default.
    543       Cryptographer temp_cryptographer(cryptographer->encryptor());
    544       temp_cryptographer.SetPendingKeys(cryptographer->GetPendingKeys());
    545       if (temp_cryptographer.DecryptPendingKeys(key_params)) {
    546         // Check to see if the pending bag of keys contains the current
    547         // default key.
    548         sync_pb::EncryptedData encrypted;
    549         cryptographer->GetKeys(&encrypted);
    550         if (temp_cryptographer.CanDecrypt(encrypted)) {
    551           DVLOG(1) << "Implicit user provided passphrase accepted for "
    552                    << "decryption, overwriting default.";
    553           // Case 7. The pending keybag contains the current default. Go ahead
    554           // and update the cryptographer, letting the default change.
    555           cryptographer->DecryptPendingKeys(key_params);
    556           cryptographer->GetBootstrapToken(&bootstrap_token);
    557           success = true;
    558         } else {
    559           // Case 8. The pending keybag does not contain the current default
    560           // encryption key. We decrypt the pending keys here, and in
    561           // FinishSetPassphrase, re-encrypt everything with the current GAIA
    562           // passphrase instead of the passphrase just provided by the user.
    563           DVLOG(1) << "Implicit user provided passphrase accepted for "
    564                    << "decryption, restoring implicit internal passphrase "
    565                    << "as default.";
    566           std::string bootstrap_token_from_current_key;
    567           cryptographer->GetBootstrapToken(
    568               &bootstrap_token_from_current_key);
    569           cryptographer->DecryptPendingKeys(key_params);
    570           // Overwrite the default from the pending keys.
    571           cryptographer->AddKeyFromBootstrapToken(
    572               bootstrap_token_from_current_key);
    573           success = true;
    574         }
    575       } else {  // !temp_cryptographer.DecryptPendingKeys(..)
    576         DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
    577         success = false;
    578       }  // temp_cryptographer.DecryptPendingKeys(...)
    579     } else {  // cryptographer->is_initialized() == false
    580       if (cryptographer->DecryptPendingKeys(key_params)) {
    581         // This can happpen in two cases:
    582         // - First time sync on android, where we'll never have a
    583         //   !user_provided passphrase.
    584         // - This is a restart for a client that lost their bootstrap token.
    585         // In both cases, we should go ahead and initialize the cryptographer
    586         // and persist the new bootstrap token.
    587         //
    588         // Note: at this point, we cannot distinguish between cases 7 and 8
    589         // above. This user provided passphrase could be the current or the
    590         // old. But, as long as we persist the token, there's nothing more
    591         // we can do.
    592         cryptographer->GetBootstrapToken(&bootstrap_token);
    593         DVLOG(1) << "Implicit user provided passphrase accepted, initializing"
    594                  << " cryptographer.";
    595         success = true;
    596       } else {
    597         DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
    598         success = false;
    599       }
    600     }  // cryptographer->is_initialized()
    601   } else {  // nigori_has_explicit_passphrase == true
    602     // Case 9. Encryption was done with an explicit passphrase, and we decrypt
    603     // with the passphrase provided by the user.
    604     if (cryptographer->DecryptPendingKeys(key_params)) {
    605       DVLOG(1) << "Explicit passphrase accepted for decryption.";
    606       cryptographer->GetBootstrapToken(&bootstrap_token);
    607       success = true;
    608     } else {
    609       DVLOG(1) << "Explicit passphrase failed to decrypt.";
    610       success = false;
    611     }
    612   }  // nigori_has_explicit_passphrase
    613 
    614   DVLOG_IF(1, !success)
    615       << "Failure in SetDecryptionPassphrase; notifying and returning.";
    616   DVLOG_IF(1, success)
    617       << "Successfully set decryption passphrase; updating nigori and "
    618          "reencrypting.";
    619 
    620   FinishSetPassphrase(success, bootstrap_token, &trans, &node);
    621 }
    622 
    623 void SyncEncryptionHandlerImpl::EnableEncryptEverything() {
    624   DCHECK(thread_checker_.CalledOnValidThread());
    625   WriteTransaction trans(FROM_HERE, user_share_);
    626   DVLOG(1) << "Enabling encrypt everything.";
    627   if (encrypt_everything_)
    628     return;
    629   EnableEncryptEverythingImpl(trans.GetWrappedTrans());
    630   WriteEncryptionStateToNigori(&trans);
    631   if (UnlockVault(trans.GetWrappedTrans()).cryptographer.is_ready())
    632     ReEncryptEverything(&trans);
    633 }
    634 
    635 bool SyncEncryptionHandlerImpl::EncryptEverythingEnabled() const {
    636   DCHECK(thread_checker_.CalledOnValidThread());
    637   return encrypt_everything_;
    638 }
    639 
    640 PassphraseType SyncEncryptionHandlerImpl::GetPassphraseType() const {
    641   DCHECK(thread_checker_.CalledOnValidThread());
    642   return passphrase_type_;
    643 }
    644 
    645 // Note: this is called from within a syncable transaction, so we need to post
    646 // tasks if we want to do any work that creates a new sync_api transaction.
    647 void SyncEncryptionHandlerImpl::ApplyNigoriUpdate(
    648     const sync_pb::NigoriSpecifics& nigori,
    649     syncable::BaseTransaction* const trans) {
    650   DCHECK(thread_checker_.CalledOnValidThread());
    651   DCHECK(trans);
    652   if (!ApplyNigoriUpdateImpl(nigori, trans)) {
    653     base::MessageLoop::current()->PostTask(
    654         FROM_HERE,
    655         base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori,
    656                    weak_ptr_factory_.GetWeakPtr()));
    657   }
    658 
    659   FOR_EACH_OBSERVER(
    660       SyncEncryptionHandler::Observer,
    661       observers_,
    662       OnCryptographerStateChanged(
    663           &UnlockVaultMutable(trans)->cryptographer));
    664 }
    665 
    666 void SyncEncryptionHandlerImpl::UpdateNigoriFromEncryptedTypes(
    667     sync_pb::NigoriSpecifics* nigori,
    668     syncable::BaseTransaction* const trans) const {
    669   DCHECK(thread_checker_.CalledOnValidThread());
    670   syncable::UpdateNigoriFromEncryptedTypes(UnlockVault(trans).encrypted_types,
    671                                            encrypt_everything_,
    672                                            nigori);
    673 }
    674 
    675 bool SyncEncryptionHandlerImpl::NeedKeystoreKey(
    676     syncable::BaseTransaction* const trans) const {
    677   DCHECK(thread_checker_.CalledOnValidThread());
    678   return keystore_key_.empty();
    679 }
    680 
    681 bool SyncEncryptionHandlerImpl::SetKeystoreKeys(
    682     const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys,
    683     syncable::BaseTransaction* const trans) {
    684   DCHECK(thread_checker_.CalledOnValidThread());
    685   if (keys.size() == 0)
    686     return false;
    687   // The last key in the vector is the current keystore key. The others are kept
    688   // around for decryption only.
    689   const std::string& raw_keystore_key = keys.Get(keys.size() - 1);
    690   if (raw_keystore_key.empty())
    691     return false;
    692 
    693   // Note: in order to Pack the keys, they must all be base64 encoded (else
    694   // JSON serialization fails).
    695   if (!base::Base64Encode(raw_keystore_key, &keystore_key_))
    696     return false;
    697 
    698   // Go through and save the old keystore keys. We always persist all keystore
    699   // keys the server sends us.
    700   old_keystore_keys_.resize(keys.size() - 1);
    701   for (int i = 0; i < keys.size() - 1; ++i)
    702     base::Base64Encode(keys.Get(i), &old_keystore_keys_[i]);
    703 
    704   Cryptographer* cryptographer = &UnlockVaultMutable(trans)->cryptographer;
    705 
    706   // Update the bootstrap token. If this fails, we persist an empty string,
    707   // which will force us to download the keystore keys again on the next
    708   // restart.
    709   std::string keystore_bootstrap = PackKeystoreBootstrapToken(
    710       old_keystore_keys_,
    711       keystore_key_,
    712       cryptographer->encryptor());
    713   DCHECK_EQ(keystore_bootstrap.empty(), keystore_key_.empty());
    714   FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
    715                     OnBootstrapTokenUpdated(keystore_bootstrap,
    716                                             KEYSTORE_BOOTSTRAP_TOKEN));
    717   DVLOG(1) << "Keystore bootstrap token updated.";
    718 
    719   // If this is a first time sync, we get the encryption keys before we process
    720   // the nigori node. Just return for now, ApplyNigoriUpdate will be invoked
    721   // once we have the nigori node.
    722   syncable::Entry entry(trans, syncable::GET_BY_SERVER_TAG, kNigoriTag);
    723   if (!entry.good())
    724     return true;
    725 
    726   const sync_pb::NigoriSpecifics& nigori =
    727       entry.Get(syncable::SPECIFICS).nigori();
    728   if (cryptographer->has_pending_keys() &&
    729       IsNigoriMigratedToKeystore(nigori) &&
    730       !nigori.keystore_decryptor_token().blob().empty()) {
    731     // If the nigori is already migrated and we have pending keys, we might
    732     // be able to decrypt them using either the keystore decryptor token
    733     // or the existing keystore keys.
    734     DecryptPendingKeysWithKeystoreKey(keystore_key_,
    735                                       nigori.keystore_decryptor_token(),
    736                                       cryptographer);
    737   }
    738 
    739   // Note that triggering migration will have no effect if we're already
    740   // properly migrated with the newest keystore keys.
    741   if (ShouldTriggerMigration(nigori, *cryptographer)) {
    742     base::MessageLoop::current()->PostTask(
    743         FROM_HERE,
    744         base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori,
    745                    weak_ptr_factory_.GetWeakPtr()));
    746   }
    747 
    748   return true;
    749 }
    750 
    751 ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypes(
    752     syncable::BaseTransaction* const trans) const {
    753   return UnlockVault(trans).encrypted_types;
    754 }
    755 
    756 Cryptographer* SyncEncryptionHandlerImpl::GetCryptographerUnsafe() {
    757   DCHECK(thread_checker_.CalledOnValidThread());
    758   return &vault_unsafe_.cryptographer;
    759 }
    760 
    761 ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypesUnsafe() {
    762   DCHECK(thread_checker_.CalledOnValidThread());
    763   return vault_unsafe_.encrypted_types;
    764 }
    765 
    766 bool SyncEncryptionHandlerImpl::MigratedToKeystore() {
    767   DCHECK(thread_checker_.CalledOnValidThread());
    768   ReadTransaction trans(FROM_HERE, user_share_);
    769   ReadNode nigori_node(&trans);
    770   if (nigori_node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK)
    771     return false;
    772   return IsNigoriMigratedToKeystore(nigori_node.GetNigoriSpecifics());
    773 }
    774 
    775 base::Time SyncEncryptionHandlerImpl::migration_time() const {
    776   return migration_time_;
    777 }
    778 
    779 base::Time SyncEncryptionHandlerImpl::custom_passphrase_time() const {
    780   return custom_passphrase_time_;
    781 }
    782 
    783 // This function iterates over all encrypted types.  There are many scenarios in
    784 // which data for some or all types is not currently available.  In that case,
    785 // the lookup of the root node will fail and we will skip encryption for that
    786 // type.
    787 void SyncEncryptionHandlerImpl::ReEncryptEverything(
    788     WriteTransaction* trans) {
    789   DCHECK(thread_checker_.CalledOnValidThread());
    790   DCHECK(UnlockVault(trans->GetWrappedTrans()).cryptographer.is_ready());
    791   for (ModelTypeSet::Iterator iter =
    792            UnlockVault(trans->GetWrappedTrans()).encrypted_types.First();
    793        iter.Good(); iter.Inc()) {
    794     if (iter.Get() == PASSWORDS || IsControlType(iter.Get()))
    795       continue; // These types handle encryption differently.
    796 
    797     ReadNode type_root(trans);
    798     std::string tag = ModelTypeToRootTag(iter.Get());
    799     if (type_root.InitByTagLookup(tag) != BaseNode::INIT_OK)
    800       continue; // Don't try to reencrypt if the type's data is unavailable.
    801 
    802     // Iterate through all children of this datatype.
    803     std::queue<int64> to_visit;
    804     int64 child_id = type_root.GetFirstChildId();
    805     to_visit.push(child_id);
    806     while (!to_visit.empty()) {
    807       child_id = to_visit.front();
    808       to_visit.pop();
    809       if (child_id == kInvalidId)
    810         continue;
    811 
    812       WriteNode child(trans);
    813       if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
    814         continue;  // Possible for locally deleted items.
    815       if (child.GetIsFolder()) {
    816         to_visit.push(child.GetFirstChildId());
    817       }
    818       if (child.GetEntry()->Get(syncable::UNIQUE_SERVER_TAG).empty()) {
    819       // Rewrite the specifics of the node with encrypted data if necessary
    820       // (only rewrite the non-unique folders).
    821         child.ResetFromSpecifics();
    822       }
    823       to_visit.push(child.GetSuccessorId());
    824     }
    825   }
    826 
    827   // Passwords are encrypted with their own legacy scheme.  Passwords are always
    828   // encrypted so we don't need to check GetEncryptedTypes() here.
    829   ReadNode passwords_root(trans);
    830   std::string passwords_tag = ModelTypeToRootTag(PASSWORDS);
    831   if (passwords_root.InitByTagLookup(passwords_tag) ==
    832           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;
    839       }
    840       child.SetPasswordSpecifics(child.GetPasswordSpecifics());
    841       child_id = child.GetSuccessorId();
    842     }
    843   }
    844 
    845   DVLOG(1) << "Re-encrypt everything complete.";
    846 
    847   // NOTE: We notify from within a transaction.
    848   FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
    849                     OnEncryptionComplete());
    850 }
    851 
    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);
    859 
    860   if (nigori.custom_passphrase_time() != 0) {
    861     custom_passphrase_time_ =
    862         ProtoTimeToTime(nigori.custom_passphrase_time());
    863   }
    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());
    870 
    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()));
    892     }
    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()));
    907     }
    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()));
    918     }
    919   }
    920 
    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();
    932     }
    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.";
    949         }
    950       }
    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());
    957     }
    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;
    963   }
    964 
    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()));
    979   }
    980 
    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_);
    994   }
    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;
   1001   }
   1002   return true;
   1003 }
   1004 
   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);
   1010 }
   1011 
   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.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK)
   1018     return;
   1019 
   1020   sync_pb::NigoriSpecifics nigori = nigori_node.GetNigoriSpecifics();
   1021   const Cryptographer& cryptographer =
   1022       UnlockVault(trans->GetWrappedTrans()).cryptographer;
   1023 
   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();
   1034 
   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_);
   1043       }
   1044 
   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.
   1049     }
   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_));
   1057     }
   1058 
   1059     // If nothing has changed, this is a no-op.
   1060     nigori_node.SetNigoriSpecifics(nigori);
   1061   }
   1062 }
   1063 
   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;
   1076   }
   1077 
   1078   ModelTypeSet nigori_encrypted_types;
   1079   nigori_encrypted_types = syncable::GetEncryptedTypesFromNigori(nigori);
   1080   nigori_encrypted_types.PutAll(SensitiveTypes());
   1081 
   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_));
   1093     }
   1094     DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
   1095     return false;
   1096   }
   1097 
   1098   MergeEncryptedTypes(nigori_encrypted_types, trans);
   1099   return encrypted_types->Equals(nigori_encrypted_types);
   1100 }
   1101 
   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};
   1109 
   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;
   1115   }
   1116 
   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;
   1128   }
   1129 
   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;
   1143   }
   1144   FinishSetPassphrase(true, bootstrap_token, trans, nigori_node);
   1145 }
   1146 
   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};
   1154 
   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;
   1164   }
   1165 
   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;
   1176   }
   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);
   1182   }
   1183   FinishSetPassphrase(success, bootstrap_token, trans, nigori_node);
   1184 }
   1185 
   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));
   1197 
   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));
   1206   }
   1207 
   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()));
   1222     }
   1223     return;
   1224   }
   1225   DCHECK(success);
   1226   DCHECK(cryptographer.is_ready());
   1227 
   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_));
   1245     }
   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_));
   1250     }
   1251     nigori_node->SetNigoriSpecifics(nigori);
   1252   }
   1253 
   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());
   1258 
   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);
   1263 }
   1264 
   1265 void SyncEncryptionHandlerImpl::MergeEncryptedTypes(
   1266     ModelTypeSet new_encrypted_types,
   1267     syncable::BaseTransaction* const trans) {
   1268   DCHECK(thread_checker_.CalledOnValidThread());
   1269 
   1270   // Only UserTypes may be encrypted.
   1271   DCHECK(EncryptableUserTypes().HasAll(new_encrypted_types));
   1272 
   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_));
   1279   }
   1280 }
   1281 
   1282 SyncEncryptionHandlerImpl::Vault* SyncEncryptionHandlerImpl::UnlockVaultMutable(
   1283     syncable::BaseTransaction* const trans) {
   1284   DCHECK_EQ(user_share_->directory.get(), trans->directory());
   1285   return &vault_unsafe_;
   1286 }
   1287 
   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_;
   1292 }
   1293 
   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;
   1337       }
   1338     }
   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;
   1346   }
   1347   return true;
   1348 }
   1349 
   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;
   1358 
   1359   if (!ShouldTriggerMigration(old_nigori, *cryptographer))
   1360     return false;
   1361 
   1362   DVLOG(1) << "Starting nigori migration to keystore support.";
   1363   sync_pb::NigoriSpecifics migrated_nigori(old_nigori);
   1364 
   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.";
   1381   }
   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);
   1386 
   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;
   1405       }
   1406       if (!cryptographer_was_ready && cryptographer->is_ready()) {
   1407         FOR_EACH_OBSERVER(
   1408             SyncEncryptionHandler::Observer,
   1409             observers_,
   1410             OnPassphraseAccepted());
   1411       }
   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;
   1424       }
   1425     }
   1426   }
   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);
   1436     }
   1437   }
   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;
   1448   }
   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;
   1455   }
   1456 
   1457   if (migration_time_.is_null())
   1458     migration_time_ = base::Time::Now();
   1459   migrated_nigori.set_keystore_migration_time(TimeToProtoTime(migration_time_));
   1460 
   1461   if (!custom_passphrase_time_.is_null()) {
   1462     migrated_nigori.set_custom_passphrase_time(
   1463         TimeToProtoTime(custom_passphrase_time_));
   1464   }
   1465 
   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()));
   1476   }
   1477 
   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);
   1485   }
   1486 
   1487   DVLOG(1) << "Completing nigori migration to keystore support.";
   1488   nigori_node->SetNigoriSpecifics(migrated_nigori);
   1489 
   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);
   1500       }
   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;
   1515   }
   1516   return true;
   1517 }
   1518 
   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.GetDefaultNigoriKey();
   1528   if (serialized_nigori.empty()) {
   1529     LOG(ERROR) << "Failed to get cryptographer bootstrap token.";
   1530     return false;
   1531   }
   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;
   1539 }
   1540 
   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;
   1551 }
   1552 
   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;
   1559   }
   1560   encrypt_everything_ = true;
   1561   *encrypted_types = EncryptableUserTypes();
   1562   FOR_EACH_OBSERVER(
   1563       Observer, observers_,
   1564       OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
   1565 }
   1566 
   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());
   1575 
   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);
   1581   }
   1582 
   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);
   1602 
   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);
   1606 
   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);
   1620     }
   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;
   1639     }
   1640   }
   1641   return false;
   1642 }
   1643 
   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();
   1650 }
   1651 
   1652 }  // namespace browser_sync
   1653