Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / sync / internal_api / sync_encryption_handler_impl.cc
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     : user_share_(user_share),
214       vault_unsafe_(encryptor, SensitiveTypes()),
215       encrypt_everything_(false),
216       passphrase_type_(IMPLICIT_PASSPHRASE),
217       nigori_overwrite_count_(0),
218       weak_ptr_factory_(this) {
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       // The user is setting a new implicit passphrase. At this point we don't
348       // care, so drop it on the floor. This is safe because if we have a
349       // migrated nigori node, then we don't need to create an initial
350       // encryption key.
351       LOG(WARNING) << "Ignoring new implicit passphrase. Keystore migration "
352                    << "already performed.";
353       return;
354     }
355     // Will fail if we already have an explicit passphrase or we have pending
356     // keys.
357     SetCustomPassphrase(passphrase, &trans, &node);
358
359     // When keystore migration occurs, the "CustomEncryption" UMA stat must be
360     // logged as true.
361     UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
362     return;
363   }
364
365   std::string bootstrap_token;
366   sync_pb::EncryptedData pending_keys;
367   if (cryptographer->has_pending_keys())
368     pending_keys = cryptographer->GetPendingKeys();
369   bool success = false;
370
371   // There are six cases to handle here:
372   // 1. The user has no pending keys and is setting their current GAIA password
373   //    as the encryption passphrase. This happens either during first time sync
374   //    with a clean profile, or after re-authenticating on a profile that was
375   //    already signed in with the cryptographer ready.
376   // 2. The user has no pending keys, and is overwriting an (already provided)
377   //    implicit passphrase with an explicit (custom) passphrase.
378   // 3. The user has pending keys for an explicit passphrase that is somehow set
379   //    to their current GAIA passphrase.
380   // 4. The user has pending keys encrypted with their current GAIA passphrase
381   //    and the caller passes in the current GAIA passphrase.
382   // 5. The user has pending keys encrypted with an older GAIA passphrase
383   //    and the caller passes in the current GAIA passphrase.
384   // 6. The user has previously done encryption with an explicit passphrase.
385   // Furthermore, we enforce the fact that the bootstrap encryption token will
386   // always be derived from the newest GAIA password if the account is using
387   // an implicit passphrase (even if the data is encrypted with an old GAIA
388   // password). If the account is using an explicit (custom) passphrase, the
389   // bootstrap token will be derived from the most recently provided explicit
390   // passphrase (that was able to decrypt the data).
391   if (!IsExplicitPassphrase(passphrase_type_)) {
392     if (!cryptographer->has_pending_keys()) {
393       if (cryptographer->AddKey(key_params)) {
394         // Case 1 and 2. We set a new GAIA passphrase when there are no pending
395         // keys (1), or overwriting an implicit passphrase with a new explicit
396         // one (2) when there are no pending keys.
397         if (is_explicit) {
398           DVLOG(1) << "Setting explicit passphrase for encryption.";
399           passphrase_type_ = CUSTOM_PASSPHRASE;
400           custom_passphrase_time_ = base::Time::Now();
401           FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
402                             OnPassphraseTypeChanged(
403                                 passphrase_type_,
404                                 GetExplicitPassphraseTime()));
405         } else {
406           DVLOG(1) << "Setting implicit passphrase for encryption.";
407         }
408         cryptographer->GetBootstrapToken(&bootstrap_token);
409
410         // With M26, sync accounts can be in only one of two encryption states:
411         // 1) Encrypt only passwords with an implicit passphrase.
412         // 2) Encrypt all sync datatypes with an explicit passphrase.
413         // We deprecate the "EncryptAllData" and "CustomPassphrase" histograms,
414         // and keep track of an account's encryption state via the
415         // "CustomEncryption" histogram. See http://crbug.com/131478.
416         UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", is_explicit);
417
418         success = true;
419       } else {
420         NOTREACHED() << "Failed to add key to cryptographer.";
421         success = false;
422       }
423     } else {  // cryptographer->has_pending_keys() == true
424       if (is_explicit) {
425         // This can only happen if the nigori node is updated with a new
426         // implicit passphrase while a client is attempting to set a new custom
427         // passphrase (race condition).
428         DVLOG(1) << "Failing because an implicit passphrase is already set.";
429         success = false;
430       } else {  // is_explicit == false
431         if (cryptographer->DecryptPendingKeys(key_params)) {
432           // Case 4. We successfully decrypted with the implicit GAIA passphrase
433           // passed in.
434           DVLOG(1) << "Implicit internal passphrase accepted for decryption.";
435           cryptographer->GetBootstrapToken(&bootstrap_token);
436           success = true;
437         } else {
438           // Case 5. Encryption was done with an old GAIA password, but we were
439           // provided with the current GAIA password. We need to generate a new
440           // bootstrap token to preserve it. We build a temporary cryptographer
441           // to allow us to extract these params without polluting our current
442           // cryptographer.
443           DVLOG(1) << "Implicit internal passphrase failed to decrypt, adding "
444                    << "anyways as default passphrase and persisting via "
445                    << "bootstrap token.";
446           Cryptographer temp_cryptographer(cryptographer->encryptor());
447           temp_cryptographer.AddKey(key_params);
448           temp_cryptographer.GetBootstrapToken(&bootstrap_token);
449           // We then set the new passphrase as the default passphrase of the
450           // real cryptographer, even though we have pending keys. This is safe,
451           // as although Cryptographer::is_initialized() will now be true,
452           // is_ready() will remain false due to having pending keys.
453           cryptographer->AddKey(key_params);
454           success = false;
455         }
456       }  // is_explicit
457     }  // cryptographer->has_pending_keys()
458   } else {  // IsExplicitPassphrase(passphrase_type_) == true.
459     // Case 6. We do not want to override a previously set explicit passphrase,
460     // so we return a failure.
461     DVLOG(1) << "Failing because an explicit passphrase is already set.";
462     success = false;
463   }
464
465   DVLOG_IF(1, !success)
466       << "Failure in SetEncryptionPassphrase; notifying and returning.";
467   DVLOG_IF(1, success)
468       << "Successfully set encryption passphrase; updating nigori and "
469          "reencrypting.";
470
471   FinishSetPassphrase(success, bootstrap_token, &trans, &node);
472 }
473
474 void SyncEncryptionHandlerImpl::SetDecryptionPassphrase(
475     const std::string& passphrase) {
476   DCHECK(thread_checker_.CalledOnValidThread());
477   // We do not accept empty passphrases.
478   if (passphrase.empty()) {
479     NOTREACHED() << "Cannot decrypt with an empty passphrase.";
480     return;
481   }
482
483   // All accesses to the cryptographer are protected by a transaction.
484   WriteTransaction trans(FROM_HERE, user_share_);
485   KeyParams key_params = {"localhost", "dummy", passphrase};
486   WriteNode node(&trans);
487   if (node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK) {
488     NOTREACHED();
489     return;
490   }
491
492   // Once we've migrated to keystore, we're only ever decrypting keys derived
493   // from an explicit passphrase. But, for clients without a keystore key yet
494   // (either not on by default or failed to download one), we still support
495   // decrypting with a gaia passphrase, and therefore bypass the
496   // DecryptPendingKeysWithExplicitPassphrase logic.
497   if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics()) &&
498       IsExplicitPassphrase(passphrase_type_)) {
499     DecryptPendingKeysWithExplicitPassphrase(passphrase, &trans, &node);
500     return;
501   }
502
503   Cryptographer* cryptographer =
504       &UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
505   if (!cryptographer->has_pending_keys()) {
506     // Note that this *can* happen in a rare situation where data is
507     // re-encrypted on another client while a SetDecryptionPassphrase() call is
508     // in-flight on this client. It is rare enough that we choose to do nothing.
509     NOTREACHED() << "Attempt to set decryption passphrase failed because there "
510                  << "were no pending keys.";
511     return;
512   }
513
514   std::string bootstrap_token;
515   sync_pb::EncryptedData pending_keys;
516   pending_keys = cryptographer->GetPendingKeys();
517   bool success = false;
518
519   // There are three cases to handle here:
520   // 7. We're using the current GAIA password to decrypt the pending keys. This
521   //    happens when signing in to an account with a previously set implicit
522   //    passphrase, where the data is already encrypted with the newest GAIA
523   //    password.
524   // 8. The user is providing an old GAIA password to decrypt the pending keys.
525   //    In this case, the user is using an implicit passphrase, but has changed
526   //    their password since they last encrypted their data, and therefore
527   //    their current GAIA password was unable to decrypt the data. This will
528   //    happen when the user is setting up a new profile with a previously
529   //    encrypted account (after changing passwords).
530   // 9. The user is providing a previously set explicit passphrase to decrypt
531   //    the pending keys.
532   if (!IsExplicitPassphrase(passphrase_type_)) {
533     if (cryptographer->is_initialized()) {
534       // We only want to change the default encryption key to the pending
535       // one if the pending keybag already contains the current default.
536       // This covers the case where a different client re-encrypted
537       // everything with a newer gaia passphrase (and hence the keybag
538       // contains keys from all previously used gaia passphrases).
539       // Otherwise, we're in a situation where the pending keys are
540       // encrypted with an old gaia passphrase, while the default is the
541       // current gaia passphrase. In that case, we preserve the default.
542       Cryptographer temp_cryptographer(cryptographer->encryptor());
543       temp_cryptographer.SetPendingKeys(cryptographer->GetPendingKeys());
544       if (temp_cryptographer.DecryptPendingKeys(key_params)) {
545         // Check to see if the pending bag of keys contains the current
546         // default key.
547         sync_pb::EncryptedData encrypted;
548         cryptographer->GetKeys(&encrypted);
549         if (temp_cryptographer.CanDecrypt(encrypted)) {
550           DVLOG(1) << "Implicit user provided passphrase accepted for "
551                    << "decryption, overwriting default.";
552           // Case 7. The pending keybag contains the current default. Go ahead
553           // and update the cryptographer, letting the default change.
554           cryptographer->DecryptPendingKeys(key_params);
555           cryptographer->GetBootstrapToken(&bootstrap_token);
556           success = true;
557         } else {
558           // Case 8. The pending keybag does not contain the current default
559           // encryption key. We decrypt the pending keys here, and in
560           // FinishSetPassphrase, re-encrypt everything with the current GAIA
561           // passphrase instead of the passphrase just provided by the user.
562           DVLOG(1) << "Implicit user provided passphrase accepted for "
563                    << "decryption, restoring implicit internal passphrase "
564                    << "as default.";
565           std::string bootstrap_token_from_current_key;
566           cryptographer->GetBootstrapToken(
567               &bootstrap_token_from_current_key);
568           cryptographer->DecryptPendingKeys(key_params);
569           // Overwrite the default from the pending keys.
570           cryptographer->AddKeyFromBootstrapToken(
571               bootstrap_token_from_current_key);
572           success = true;
573         }
574       } else {  // !temp_cryptographer.DecryptPendingKeys(..)
575         DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
576         success = false;
577       }  // temp_cryptographer.DecryptPendingKeys(...)
578     } else {  // cryptographer->is_initialized() == false
579       if (cryptographer->DecryptPendingKeys(key_params)) {
580         // This can happpen in two cases:
581         // - First time sync on android, where we'll never have a
582         //   !user_provided passphrase.
583         // - This is a restart for a client that lost their bootstrap token.
584         // In both cases, we should go ahead and initialize the cryptographer
585         // and persist the new bootstrap token.
586         //
587         // Note: at this point, we cannot distinguish between cases 7 and 8
588         // above. This user provided passphrase could be the current or the
589         // old. But, as long as we persist the token, there's nothing more
590         // we can do.
591         cryptographer->GetBootstrapToken(&bootstrap_token);
592         DVLOG(1) << "Implicit user provided passphrase accepted, initializing"
593                  << " cryptographer.";
594         success = true;
595       } else {
596         DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
597         success = false;
598       }
599     }  // cryptographer->is_initialized()
600   } else {  // nigori_has_explicit_passphrase == true
601     // Case 9. Encryption was done with an explicit passphrase, and we decrypt
602     // with the passphrase provided by the user.
603     if (cryptographer->DecryptPendingKeys(key_params)) {
604       DVLOG(1) << "Explicit passphrase accepted for decryption.";
605       cryptographer->GetBootstrapToken(&bootstrap_token);
606       success = true;
607     } else {
608       DVLOG(1) << "Explicit passphrase failed to decrypt.";
609       success = false;
610     }
611   }  // nigori_has_explicit_passphrase
612
613   DVLOG_IF(1, !success)
614       << "Failure in SetDecryptionPassphrase; notifying and returning.";
615   DVLOG_IF(1, success)
616       << "Successfully set decryption passphrase; updating nigori and "
617          "reencrypting.";
618
619   FinishSetPassphrase(success, bootstrap_token, &trans, &node);
620 }
621
622 void SyncEncryptionHandlerImpl::EnableEncryptEverything() {
623   DCHECK(thread_checker_.CalledOnValidThread());
624   WriteTransaction trans(FROM_HERE, user_share_);
625   DVLOG(1) << "Enabling encrypt everything.";
626   if (encrypt_everything_)
627     return;
628   EnableEncryptEverythingImpl(trans.GetWrappedTrans());
629   WriteEncryptionStateToNigori(&trans);
630   if (UnlockVault(trans.GetWrappedTrans()).cryptographer.is_ready())
631     ReEncryptEverything(&trans);
632 }
633
634 bool SyncEncryptionHandlerImpl::EncryptEverythingEnabled() const {
635   DCHECK(thread_checker_.CalledOnValidThread());
636   return encrypt_everything_;
637 }
638
639 PassphraseType SyncEncryptionHandlerImpl::GetPassphraseType() const {
640   DCHECK(thread_checker_.CalledOnValidThread());
641   return passphrase_type_;
642 }
643
644 // Note: this is called from within a syncable transaction, so we need to post
645 // tasks if we want to do any work that creates a new sync_api transaction.
646 void SyncEncryptionHandlerImpl::ApplyNigoriUpdate(
647     const sync_pb::NigoriSpecifics& nigori,
648     syncable::BaseTransaction* const trans) {
649   DCHECK(thread_checker_.CalledOnValidThread());
650   DCHECK(trans);
651   if (!ApplyNigoriUpdateImpl(nigori, trans)) {
652     base::MessageLoop::current()->PostTask(
653         FROM_HERE,
654         base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori,
655                    weak_ptr_factory_.GetWeakPtr()));
656   }
657
658   FOR_EACH_OBSERVER(
659       SyncEncryptionHandler::Observer,
660       observers_,
661       OnCryptographerStateChanged(
662           &UnlockVaultMutable(trans)->cryptographer));
663 }
664
665 void SyncEncryptionHandlerImpl::UpdateNigoriFromEncryptedTypes(
666     sync_pb::NigoriSpecifics* nigori,
667     syncable::BaseTransaction* const trans) const {
668   DCHECK(thread_checker_.CalledOnValidThread());
669   syncable::UpdateNigoriFromEncryptedTypes(UnlockVault(trans).encrypted_types,
670                                            encrypt_everything_,
671                                            nigori);
672 }
673
674 bool SyncEncryptionHandlerImpl::NeedKeystoreKey(
675     syncable::BaseTransaction* const trans) const {
676   DCHECK(thread_checker_.CalledOnValidThread());
677   return keystore_key_.empty();
678 }
679
680 bool SyncEncryptionHandlerImpl::SetKeystoreKeys(
681     const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys,
682     syncable::BaseTransaction* const trans) {
683   DCHECK(thread_checker_.CalledOnValidThread());
684   if (keys.size() == 0)
685     return false;
686   // The last key in the vector is the current keystore key. The others are kept
687   // around for decryption only.
688   const std::string& raw_keystore_key = keys.Get(keys.size() - 1);
689   if (raw_keystore_key.empty())
690     return false;
691
692   // Note: in order to Pack the keys, they must all be base64 encoded (else
693   // JSON serialization fails).
694   base::Base64Encode(raw_keystore_key, &keystore_key_);
695
696   // Go through and save the old keystore keys. We always persist all keystore
697   // keys the server sends us.
698   old_keystore_keys_.resize(keys.size() - 1);
699   for (int i = 0; i < keys.size() - 1; ++i)
700     base::Base64Encode(keys.Get(i), &old_keystore_keys_[i]);
701
702   Cryptographer* cryptographer = &UnlockVaultMutable(trans)->cryptographer;
703
704   // Update the bootstrap token. If this fails, we persist an empty string,
705   // which will force us to download the keystore keys again on the next
706   // restart.
707   std::string keystore_bootstrap = PackKeystoreBootstrapToken(
708       old_keystore_keys_,
709       keystore_key_,
710       cryptographer->encryptor());
711   DCHECK_EQ(keystore_bootstrap.empty(), keystore_key_.empty());
712   FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
713                     OnBootstrapTokenUpdated(keystore_bootstrap,
714                                             KEYSTORE_BOOTSTRAP_TOKEN));
715   DVLOG(1) << "Keystore bootstrap token updated.";
716
717   // If this is a first time sync, we get the encryption keys before we process
718   // the nigori node. Just return for now, ApplyNigoriUpdate will be invoked
719   // once we have the nigori node.
720   syncable::Entry entry(trans, syncable::GET_BY_SERVER_TAG, kNigoriTag);
721   if (!entry.good())
722     return true;
723
724   const sync_pb::NigoriSpecifics& nigori =
725       entry.GetSpecifics().nigori();
726   if (cryptographer->has_pending_keys() &&
727       IsNigoriMigratedToKeystore(nigori) &&
728       !nigori.keystore_decryptor_token().blob().empty()) {
729     // If the nigori is already migrated and we have pending keys, we might
730     // be able to decrypt them using either the keystore decryptor token
731     // or the existing keystore keys.
732     DecryptPendingKeysWithKeystoreKey(keystore_key_,
733                                       nigori.keystore_decryptor_token(),
734                                       cryptographer);
735   }
736
737   // Note that triggering migration will have no effect if we're already
738   // properly migrated with the newest keystore keys.
739   if (ShouldTriggerMigration(nigori, *cryptographer)) {
740     base::MessageLoop::current()->PostTask(
741         FROM_HERE,
742         base::Bind(&SyncEncryptionHandlerImpl::RewriteNigori,
743                    weak_ptr_factory_.GetWeakPtr()));
744   }
745
746   return true;
747 }
748
749 ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypes(
750     syncable::BaseTransaction* const trans) const {
751   return UnlockVault(trans).encrypted_types;
752 }
753
754 Cryptographer* SyncEncryptionHandlerImpl::GetCryptographerUnsafe() {
755   DCHECK(thread_checker_.CalledOnValidThread());
756   return &vault_unsafe_.cryptographer;
757 }
758
759 ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypesUnsafe() {
760   DCHECK(thread_checker_.CalledOnValidThread());
761   return vault_unsafe_.encrypted_types;
762 }
763
764 bool SyncEncryptionHandlerImpl::MigratedToKeystore() {
765   DCHECK(thread_checker_.CalledOnValidThread());
766   ReadTransaction trans(FROM_HERE, user_share_);
767   ReadNode nigori_node(&trans);
768   if (nigori_node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK)
769     return false;
770   return IsNigoriMigratedToKeystore(nigori_node.GetNigoriSpecifics());
771 }
772
773 base::Time SyncEncryptionHandlerImpl::migration_time() const {
774   return migration_time_;
775 }
776
777 base::Time SyncEncryptionHandlerImpl::custom_passphrase_time() const {
778   return custom_passphrase_time_;
779 }
780
781 // This function iterates over all encrypted types.  There are many scenarios in
782 // which data for some or all types is not currently available.  In that case,
783 // the lookup of the root node will fail and we will skip encryption for that
784 // type.
785 void SyncEncryptionHandlerImpl::ReEncryptEverything(
786     WriteTransaction* trans) {
787   DCHECK(thread_checker_.CalledOnValidThread());
788   DCHECK(UnlockVault(trans->GetWrappedTrans()).cryptographer.is_ready());
789   for (ModelTypeSet::Iterator iter =
790            UnlockVault(trans->GetWrappedTrans()).encrypted_types.First();
791        iter.Good(); iter.Inc()) {
792     if (iter.Get() == PASSWORDS || IsControlType(iter.Get()))
793       continue; // These types handle encryption differently.
794
795     ReadNode type_root(trans);
796     std::string tag = ModelTypeToRootTag(iter.Get());
797     if (type_root.InitByTagLookup(tag) != BaseNode::INIT_OK)
798       continue; // Don't try to reencrypt if the type's data is unavailable.
799
800     // Iterate through all children of this datatype.
801     std::queue<int64> to_visit;
802     int64 child_id = type_root.GetFirstChildId();
803     to_visit.push(child_id);
804     while (!to_visit.empty()) {
805       child_id = to_visit.front();
806       to_visit.pop();
807       if (child_id == kInvalidId)
808         continue;
809
810       WriteNode child(trans);
811       if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
812         continue;  // Possible for locally deleted items.
813       if (child.GetIsFolder()) {
814         to_visit.push(child.GetFirstChildId());
815       }
816       if (child.GetEntry()->GetUniqueServerTag().empty()) {
817       // Rewrite the specifics of the node with encrypted data if necessary
818       // (only rewrite the non-unique folders).
819         child.ResetFromSpecifics();
820       }
821       to_visit.push(child.GetSuccessorId());
822     }
823   }
824
825   // Passwords are encrypted with their own legacy scheme.  Passwords are always
826   // encrypted so we don't need to check GetEncryptedTypes() here.
827   ReadNode passwords_root(trans);
828   std::string passwords_tag = ModelTypeToRootTag(PASSWORDS);
829   if (passwords_root.InitByTagLookup(passwords_tag) ==
830           BaseNode::INIT_OK) {
831     int64 child_id = passwords_root.GetFirstChildId();
832     while (child_id != kInvalidId) {
833       WriteNode child(trans);
834       if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK) {
835         NOTREACHED();
836         return;
837       }
838       child.SetPasswordSpecifics(child.GetPasswordSpecifics());
839       child_id = child.GetSuccessorId();
840     }
841   }
842
843   DVLOG(1) << "Re-encrypt everything complete.";
844
845   // NOTE: We notify from within a transaction.
846   FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
847                     OnEncryptionComplete());
848 }
849
850 bool SyncEncryptionHandlerImpl::ApplyNigoriUpdateImpl(
851     const sync_pb::NigoriSpecifics& nigori,
852     syncable::BaseTransaction* const trans) {
853   DCHECK(thread_checker_.CalledOnValidThread());
854   DVLOG(1) << "Applying nigori node update.";
855   bool nigori_types_need_update = !UpdateEncryptedTypesFromNigori(nigori,
856                                                                   trans);
857
858   if (nigori.custom_passphrase_time() != 0) {
859     custom_passphrase_time_ =
860         ProtoTimeToTime(nigori.custom_passphrase_time());
861   }
862   bool is_nigori_migrated = IsNigoriMigratedToKeystore(nigori);
863   if (is_nigori_migrated) {
864     DCHECK(nigori.has_keystore_migration_time());
865     migration_time_ = ProtoTimeToTime(nigori.keystore_migration_time());
866     PassphraseType nigori_passphrase_type =
867         ProtoPassphraseTypeToEnum(nigori.passphrase_type());
868
869     // Only update the local passphrase state if it's a valid transition:
870     // - implicit -> keystore
871     // - implicit -> frozen implicit
872     // - implicit -> custom
873     // - keystore -> custom
874     // Note: frozen implicit -> custom is not technically a valid transition,
875     // but we let it through here as well in case future versions do add support
876     // for this transition.
877     if (passphrase_type_ != nigori_passphrase_type &&
878         nigori_passphrase_type != IMPLICIT_PASSPHRASE &&
879         (passphrase_type_ == IMPLICIT_PASSPHRASE ||
880          nigori_passphrase_type == CUSTOM_PASSPHRASE)) {
881       DVLOG(1) << "Changing passphrase state from "
882                << PassphraseTypeToString(passphrase_type_)
883                << " to "
884                << PassphraseTypeToString(nigori_passphrase_type);
885       passphrase_type_ = nigori_passphrase_type;
886       FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
887                             OnPassphraseTypeChanged(
888                                 passphrase_type_,
889                                 GetExplicitPassphraseTime()));
890     }
891     if (passphrase_type_ == KEYSTORE_PASSPHRASE && encrypt_everything_) {
892       // This is the case where another client that didn't support keystore
893       // encryption attempted to enable full encryption. We detect it
894       // and switch the passphrase type to frozen implicit passphrase instead
895       // due to full encryption not being compatible with keystore passphrase.
896       // Because the local passphrase type will not match the nigori passphrase
897       // type, we will trigger a rewrite and subsequently a re-migration.
898       DVLOG(1) << "Changing passphrase state to FROZEN_IMPLICIT_PASSPHRASE "
899                << "due to full encryption.";
900       passphrase_type_ = FROZEN_IMPLICIT_PASSPHRASE;
901       FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
902                             OnPassphraseTypeChanged(
903                                 passphrase_type_,
904                                 GetExplicitPassphraseTime()));
905     }
906   } else {
907     // It's possible that while we're waiting for migration a client that does
908     // not have keystore encryption enabled switches to a custom passphrase.
909     if (nigori.keybag_is_frozen() &&
910         passphrase_type_ != CUSTOM_PASSPHRASE) {
911       passphrase_type_ = CUSTOM_PASSPHRASE;
912       FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
913                             OnPassphraseTypeChanged(
914                                 passphrase_type_,
915                                 GetExplicitPassphraseTime()));
916     }
917   }
918
919   Cryptographer* cryptographer = &UnlockVaultMutable(trans)->cryptographer;
920   bool nigori_needs_new_keys = false;
921   if (!nigori.encryption_keybag().blob().empty()) {
922     // We only update the default key if this was a new explicit passphrase.
923     // Else, since it was decryptable, it must not have been a new key.
924     bool need_new_default_key = false;
925     if (is_nigori_migrated) {
926       need_new_default_key = IsExplicitPassphrase(
927           ProtoPassphraseTypeToEnum(nigori.passphrase_type()));
928     } else {
929       need_new_default_key = nigori.keybag_is_frozen();
930     }
931     if (!AttemptToInstallKeybag(nigori.encryption_keybag(),
932                                 need_new_default_key,
933                                 cryptographer)) {
934       // Check to see if we can decrypt the keybag using the keystore decryptor
935       // token.
936       cryptographer->SetPendingKeys(nigori.encryption_keybag());
937       if (!nigori.keystore_decryptor_token().blob().empty() &&
938           !keystore_key_.empty()) {
939         if (DecryptPendingKeysWithKeystoreKey(keystore_key_,
940                                               nigori.keystore_decryptor_token(),
941                                               cryptographer)) {
942           nigori_needs_new_keys =
943               cryptographer->KeybagIsStale(nigori.encryption_keybag());
944         } else {
945           LOG(ERROR) << "Failed to decrypt pending keys using keystore "
946                      << "bootstrap key.";
947         }
948       }
949     } else {
950       // Keybag was installed. We write back our local keybag into the nigori
951       // node if the nigori node's keybag either contains less keys or
952       // has a different default key.
953       nigori_needs_new_keys =
954           cryptographer->KeybagIsStale(nigori.encryption_keybag());
955     }
956   } else {
957     // The nigori node has an empty encryption keybag. Attempt to write our
958     // local encryption keys into it.
959     LOG(WARNING) << "Nigori had empty encryption keybag.";
960     nigori_needs_new_keys = true;
961   }
962
963   // If we've completed a sync cycle and the cryptographer isn't ready
964   // yet or has pending keys, prompt the user for a passphrase.
965   if (cryptographer->has_pending_keys()) {
966     DVLOG(1) << "OnPassphraseRequired Sent";
967     sync_pb::EncryptedData pending_keys = cryptographer->GetPendingKeys();
968     FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
969                       OnPassphraseRequired(REASON_DECRYPTION,
970                                            pending_keys));
971   } else if (!cryptographer->is_ready()) {
972     DVLOG(1) << "OnPassphraseRequired sent because cryptographer is not "
973              << "ready";
974     FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
975                       OnPassphraseRequired(REASON_ENCRYPTION,
976                                            sync_pb::EncryptedData()));
977   }
978
979   // Check if the current local encryption state is stricter/newer than the
980   // nigori state. If so, we need to overwrite the nigori node with the local
981   // state.
982   bool passphrase_type_matches = true;
983   if (!is_nigori_migrated) {
984     DCHECK(passphrase_type_ == CUSTOM_PASSPHRASE ||
985            passphrase_type_ == IMPLICIT_PASSPHRASE);
986     passphrase_type_matches =
987         nigori.keybag_is_frozen() == IsExplicitPassphrase(passphrase_type_);
988   } else {
989     passphrase_type_matches =
990         (ProtoPassphraseTypeToEnum(nigori.passphrase_type()) ==
991              passphrase_type_);
992   }
993   if (!passphrase_type_matches ||
994       nigori.encrypt_everything() != encrypt_everything_ ||
995       nigori_types_need_update ||
996       nigori_needs_new_keys) {
997     DVLOG(1) << "Triggering nigori rewrite.";
998     return false;
999   }
1000   return true;
1001 }
1002
1003 void SyncEncryptionHandlerImpl::RewriteNigori() {
1004   DVLOG(1) << "Writing local encryption state into nigori.";
1005   DCHECK(thread_checker_.CalledOnValidThread());
1006   WriteTransaction trans(FROM_HERE, user_share_);
1007   WriteEncryptionStateToNigori(&trans);
1008 }
1009
1010 void SyncEncryptionHandlerImpl::WriteEncryptionStateToNigori(
1011     WriteTransaction* trans) {
1012   DCHECK(thread_checker_.CalledOnValidThread());
1013   WriteNode nigori_node(trans);
1014   // This can happen in tests that don't have nigori nodes.
1015   if (nigori_node.InitByTagLookup(kNigoriTag) != BaseNode::INIT_OK)
1016     return;
1017
1018   sync_pb::NigoriSpecifics nigori = nigori_node.GetNigoriSpecifics();
1019   const Cryptographer& cryptographer =
1020       UnlockVault(trans->GetWrappedTrans()).cryptographer;
1021
1022   // Will not do anything if we shouldn't or can't migrate. Otherwise
1023   // migrates, writing the full encryption state as it does.
1024   if (!AttemptToMigrateNigoriToKeystore(trans, &nigori_node)) {
1025     if (cryptographer.is_ready() &&
1026         nigori_overwrite_count_ < kNigoriOverwriteLimit) {
1027       // Does not modify the encrypted blob if the unencrypted data already
1028       // matches what is about to be written.
1029       sync_pb::EncryptedData original_keys = nigori.encryption_keybag();
1030       if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
1031         NOTREACHED();
1032
1033       if (nigori.encryption_keybag().SerializeAsString() !=
1034           original_keys.SerializeAsString()) {
1035         // We've updated the nigori node's encryption keys. In order to prevent
1036         // a possible looping of two clients constantly overwriting each other,
1037         // we limit the absolute number of overwrites per client instantiation.
1038         nigori_overwrite_count_++;
1039         UMA_HISTOGRAM_COUNTS("Sync.AutoNigoriOverwrites",
1040                              nigori_overwrite_count_);
1041       }
1042
1043       // Note: we don't try to set keybag_is_frozen here since if that
1044       // is lost the user can always set it again (and we don't want to clobber
1045       // any migration state). The main goal at this point is to preserve
1046       // the encryption keys so all data remains decryptable.
1047     }
1048     syncable::UpdateNigoriFromEncryptedTypes(
1049         UnlockVault(trans->GetWrappedTrans()).encrypted_types,
1050         encrypt_everything_,
1051         &nigori);
1052     if (!custom_passphrase_time_.is_null()) {
1053       nigori.set_custom_passphrase_time(
1054           TimeToProtoTime(custom_passphrase_time_));
1055     }
1056
1057     // If nothing has changed, this is a no-op.
1058     nigori_node.SetNigoriSpecifics(nigori);
1059   }
1060 }
1061
1062 bool SyncEncryptionHandlerImpl::UpdateEncryptedTypesFromNigori(
1063     const sync_pb::NigoriSpecifics& nigori,
1064     syncable::BaseTransaction* const trans) {
1065   DCHECK(thread_checker_.CalledOnValidThread());
1066   ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
1067   if (nigori.encrypt_everything()) {
1068     EnableEncryptEverythingImpl(trans);
1069     DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1070     return true;
1071   } else if (encrypt_everything_) {
1072     DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1073     return false;
1074   }
1075
1076   ModelTypeSet nigori_encrypted_types;
1077   nigori_encrypted_types = syncable::GetEncryptedTypesFromNigori(nigori);
1078   nigori_encrypted_types.PutAll(SensitiveTypes());
1079
1080   // If anything more than the sensitive types were encrypted, and
1081   // encrypt_everything is not explicitly set to false, we assume it means
1082   // a client intended to enable encrypt everything.
1083   if (!nigori.has_encrypt_everything() &&
1084       !Difference(nigori_encrypted_types, SensitiveTypes()).Empty()) {
1085     if (!encrypt_everything_) {
1086       encrypt_everything_ = true;
1087       *encrypted_types = EncryptableUserTypes();
1088       FOR_EACH_OBSERVER(
1089           Observer, observers_,
1090           OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
1091     }
1092     DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1093     return false;
1094   }
1095
1096   MergeEncryptedTypes(nigori_encrypted_types, trans);
1097   return encrypted_types->Equals(nigori_encrypted_types);
1098 }
1099
1100 void SyncEncryptionHandlerImpl::SetCustomPassphrase(
1101     const std::string& passphrase,
1102     WriteTransaction* trans,
1103     WriteNode* nigori_node) {
1104   DCHECK(thread_checker_.CalledOnValidThread());
1105   DCHECK(IsNigoriMigratedToKeystore(nigori_node->GetNigoriSpecifics()));
1106   KeyParams key_params = {"localhost", "dummy", passphrase};
1107
1108   if (passphrase_type_ != KEYSTORE_PASSPHRASE) {
1109     DVLOG(1) << "Failing to set a custom passphrase because one has already "
1110              << "been set.";
1111     FinishSetPassphrase(false, std::string(), trans, nigori_node);
1112     return;
1113   }
1114
1115   Cryptographer* cryptographer =
1116       &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
1117   if (cryptographer->has_pending_keys()) {
1118     // This theoretically shouldn't happen, because the only way to have pending
1119     // keys after migrating to keystore support is if a custom passphrase was
1120     // set, which should update passpshrase_state_ and should be caught by the
1121     // if statement above. For the sake of safety though, we check for it in
1122     // case a client is misbehaving.
1123     LOG(ERROR) << "Failing to set custom passphrase because of pending keys.";
1124     FinishSetPassphrase(false, std::string(), trans, nigori_node);
1125     return;
1126   }
1127
1128   std::string bootstrap_token;
1129   if (cryptographer->AddKey(key_params)) {
1130     DVLOG(1) << "Setting custom passphrase.";
1131     cryptographer->GetBootstrapToken(&bootstrap_token);
1132     passphrase_type_ = CUSTOM_PASSPHRASE;
1133     custom_passphrase_time_ = base::Time::Now();
1134     FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1135                             OnPassphraseTypeChanged(
1136                                 passphrase_type_,
1137                                 GetExplicitPassphraseTime()));
1138   } else {
1139     NOTREACHED() << "Failed to add key to cryptographer.";
1140     return;
1141   }
1142   FinishSetPassphrase(true, bootstrap_token, trans, nigori_node);
1143 }
1144
1145 void SyncEncryptionHandlerImpl::DecryptPendingKeysWithExplicitPassphrase(
1146     const std::string& passphrase,
1147     WriteTransaction* trans,
1148     WriteNode* nigori_node) {
1149   DCHECK(thread_checker_.CalledOnValidThread());
1150   DCHECK(IsExplicitPassphrase(passphrase_type_));
1151   KeyParams key_params = {"localhost", "dummy", passphrase};
1152
1153   Cryptographer* cryptographer =
1154       &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
1155   if (!cryptographer->has_pending_keys()) {
1156     // Note that this *can* happen in a rare situation where data is
1157     // re-encrypted on another client while a SetDecryptionPassphrase() call is
1158     // in-flight on this client. It is rare enough that we choose to do nothing.
1159     NOTREACHED() << "Attempt to set decryption passphrase failed because there "
1160                  << "were no pending keys.";
1161     return;
1162   }
1163
1164   DCHECK(IsExplicitPassphrase(passphrase_type_));
1165   bool success = false;
1166   std::string bootstrap_token;
1167   if (cryptographer->DecryptPendingKeys(key_params)) {
1168     DVLOG(1) << "Explicit passphrase accepted for decryption.";
1169     cryptographer->GetBootstrapToken(&bootstrap_token);
1170     success = true;
1171   } else {
1172     DVLOG(1) << "Explicit passphrase failed to decrypt.";
1173     success = false;
1174   }
1175   if (success && !keystore_key_.empty()) {
1176     // Should already be part of the encryption keybag, but we add it just
1177     // in case.
1178     KeyParams key_params = {"localhost", "dummy", keystore_key_};
1179     cryptographer->AddNonDefaultKey(key_params);
1180   }
1181   FinishSetPassphrase(success, bootstrap_token, trans, nigori_node);
1182 }
1183
1184 void SyncEncryptionHandlerImpl::FinishSetPassphrase(
1185     bool success,
1186     const std::string& bootstrap_token,
1187     WriteTransaction* trans,
1188     WriteNode* nigori_node) {
1189   DCHECK(thread_checker_.CalledOnValidThread());
1190   FOR_EACH_OBSERVER(
1191       SyncEncryptionHandler::Observer,
1192       observers_,
1193       OnCryptographerStateChanged(
1194           &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer));
1195
1196   // It's possible we need to change the bootstrap token even if we failed to
1197   // set the passphrase (for example if we need to preserve the new GAIA
1198   // passphrase).
1199   if (!bootstrap_token.empty()) {
1200     DVLOG(1) << "Passphrase bootstrap token updated.";
1201     FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1202                       OnBootstrapTokenUpdated(bootstrap_token,
1203                                               PASSPHRASE_BOOTSTRAP_TOKEN));
1204   }
1205
1206   const Cryptographer& cryptographer =
1207       UnlockVault(trans->GetWrappedTrans()).cryptographer;
1208   if (!success) {
1209     if (cryptographer.is_ready()) {
1210       LOG(ERROR) << "Attempt to change passphrase failed while cryptographer "
1211                  << "was ready.";
1212     } else if (cryptographer.has_pending_keys()) {
1213       FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1214                         OnPassphraseRequired(REASON_DECRYPTION,
1215                                              cryptographer.GetPendingKeys()));
1216     } else {
1217       FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1218                         OnPassphraseRequired(REASON_ENCRYPTION,
1219                                              sync_pb::EncryptedData()));
1220     }
1221     return;
1222   }
1223   DCHECK(success);
1224   DCHECK(cryptographer.is_ready());
1225
1226   // Will do nothing if we're already properly migrated or unable to migrate
1227   // (in otherwords, if ShouldTriggerMigration is false).
1228   // Otherwise will update the nigori node with the current migrated state,
1229   // writing all encryption state as it does.
1230   if (!AttemptToMigrateNigoriToKeystore(trans, nigori_node)) {
1231     sync_pb::NigoriSpecifics nigori(nigori_node->GetNigoriSpecifics());
1232     // Does not modify nigori.encryption_keybag() if the original decrypted
1233     // data was the same.
1234     if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
1235       NOTREACHED();
1236     if (IsNigoriMigratedToKeystore(nigori)) {
1237       DCHECK(keystore_key_.empty() || IsExplicitPassphrase(passphrase_type_));
1238       DVLOG(1) << "Leaving nigori migration state untouched after setting"
1239                << " passphrase.";
1240     } else {
1241       nigori.set_keybag_is_frozen(
1242           IsExplicitPassphrase(passphrase_type_));
1243     }
1244     // If we set a new custom passphrase, store the timestamp.
1245     if (!custom_passphrase_time_.is_null()) {
1246       nigori.set_custom_passphrase_time(
1247           TimeToProtoTime(custom_passphrase_time_));
1248     }
1249     nigori_node->SetNigoriSpecifics(nigori);
1250   }
1251
1252   // Must do this after OnPassphraseTypeChanged, in order to ensure the PSS
1253   // checks the passphrase state after it has been set.
1254   FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1255                     OnPassphraseAccepted());
1256
1257   // Does nothing if everything is already encrypted.
1258   // TODO(zea): If we just migrated and enabled encryption, this will be
1259   // redundant. Figure out a way to not do this unnecessarily.
1260   ReEncryptEverything(trans);
1261 }
1262
1263 void SyncEncryptionHandlerImpl::MergeEncryptedTypes(
1264     ModelTypeSet new_encrypted_types,
1265     syncable::BaseTransaction* const trans) {
1266   DCHECK(thread_checker_.CalledOnValidThread());
1267
1268   // Only UserTypes may be encrypted.
1269   DCHECK(EncryptableUserTypes().HasAll(new_encrypted_types));
1270
1271   ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
1272   if (!encrypted_types->HasAll(new_encrypted_types)) {
1273     *encrypted_types = new_encrypted_types;
1274     FOR_EACH_OBSERVER(
1275         Observer, observers_,
1276         OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
1277   }
1278 }
1279
1280 SyncEncryptionHandlerImpl::Vault* SyncEncryptionHandlerImpl::UnlockVaultMutable(
1281     syncable::BaseTransaction* const trans) {
1282   DCHECK_EQ(user_share_->directory.get(), trans->directory());
1283   return &vault_unsafe_;
1284 }
1285
1286 const SyncEncryptionHandlerImpl::Vault& SyncEncryptionHandlerImpl::UnlockVault(
1287     syncable::BaseTransaction* const trans) const {
1288   DCHECK_EQ(user_share_->directory.get(), trans->directory());
1289   return vault_unsafe_;
1290 }
1291
1292 bool SyncEncryptionHandlerImpl::ShouldTriggerMigration(
1293     const sync_pb::NigoriSpecifics& nigori,
1294     const Cryptographer& cryptographer) const {
1295   DCHECK(thread_checker_.CalledOnValidThread());
1296   // Don't migrate if there are pending encryption keys (because data
1297   // encrypted with the pending keys will not be decryptable).
1298   if (cryptographer.has_pending_keys())
1299     return false;
1300   if (IsNigoriMigratedToKeystore(nigori)) {
1301     // If the nigori is already migrated but does not reflect the explicit
1302     // passphrase state, remigrate. Similarly, if the nigori has an explicit
1303     // passphrase but does not have full encryption, or the nigori has an
1304     // implicit passphrase but does have full encryption, re-migrate.
1305     // Note that this is to defend against other clients without keystore
1306     // encryption enabled transitioning to states that are no longer valid.
1307     if (passphrase_type_ != KEYSTORE_PASSPHRASE &&
1308         nigori.passphrase_type() ==
1309             sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE) {
1310       return true;
1311     } else if (IsExplicitPassphrase(passphrase_type_) &&
1312                !encrypt_everything_) {
1313       return true;
1314     } else if (passphrase_type_ == KEYSTORE_PASSPHRASE &&
1315                encrypt_everything_) {
1316       return true;
1317     } else if (
1318         cryptographer.is_ready() &&
1319         !cryptographer.CanDecryptUsingDefaultKey(nigori.encryption_keybag())) {
1320       // We need to overwrite the keybag. This might involve overwriting the
1321       // keystore decryptor too.
1322       return true;
1323     } else if (old_keystore_keys_.size() > 0 && !keystore_key_.empty()) {
1324       // Check to see if a server key rotation has happened, but the nigori
1325       // node's keys haven't been rotated yet, and hence we should re-migrate.
1326       // Note that once a key rotation has been performed, we no longer
1327       // preserve backwards compatibility, and the keybag will therefore be
1328       // encrypted with the current keystore key.
1329       Cryptographer temp_cryptographer(cryptographer.encryptor());
1330       KeyParams keystore_params = {"localhost", "dummy", keystore_key_};
1331       temp_cryptographer.AddKey(keystore_params);
1332       if (!temp_cryptographer.CanDecryptUsingDefaultKey(
1333               nigori.encryption_keybag())) {
1334         return true;
1335       }
1336     }
1337     return false;
1338   } else if (keystore_key_.empty()) {
1339     // If we haven't already migrated, we don't want to do anything unless
1340     // a keystore key is available (so that those clients without keystore
1341     // encryption enabled aren't forced into new states, e.g. frozen implicit
1342     // passphrase).
1343     return false;
1344   }
1345   return true;
1346 }
1347
1348 bool SyncEncryptionHandlerImpl::AttemptToMigrateNigoriToKeystore(
1349     WriteTransaction* trans,
1350     WriteNode* nigori_node) {
1351   DCHECK(thread_checker_.CalledOnValidThread());
1352   const sync_pb::NigoriSpecifics& old_nigori =
1353       nigori_node->GetNigoriSpecifics();
1354   Cryptographer* cryptographer =
1355       &UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
1356
1357   if (!ShouldTriggerMigration(old_nigori, *cryptographer))
1358     return false;
1359
1360   DVLOG(1) << "Starting nigori migration to keystore support.";
1361   sync_pb::NigoriSpecifics migrated_nigori(old_nigori);
1362
1363   PassphraseType new_passphrase_type = passphrase_type_;
1364   bool new_encrypt_everything = encrypt_everything_;
1365   if (encrypt_everything_ && !IsExplicitPassphrase(passphrase_type_)) {
1366     DVLOG(1) << "Switching to frozen implicit passphrase due to already having "
1367              << "full encryption.";
1368     new_passphrase_type = FROZEN_IMPLICIT_PASSPHRASE;
1369     migrated_nigori.clear_keystore_decryptor_token();
1370   } else if (IsExplicitPassphrase(passphrase_type_)) {
1371     DVLOG_IF(1, !encrypt_everything_) << "Enabling encrypt everything due to "
1372                                       << "explicit passphrase";
1373     new_encrypt_everything = true;
1374     migrated_nigori.clear_keystore_decryptor_token();
1375   } else {
1376     DCHECK(!encrypt_everything_);
1377     new_passphrase_type = KEYSTORE_PASSPHRASE;
1378     DVLOG(1) << "Switching to keystore passphrase state.";
1379   }
1380   migrated_nigori.set_encrypt_everything(new_encrypt_everything);
1381   migrated_nigori.set_passphrase_type(
1382       EnumPassphraseTypeToProto(new_passphrase_type));
1383   migrated_nigori.set_keybag_is_frozen(true);
1384
1385   if (!keystore_key_.empty()) {
1386     KeyParams key_params = {"localhost", "dummy", keystore_key_};
1387     if ((old_keystore_keys_.size() > 0 &&
1388          new_passphrase_type == KEYSTORE_PASSPHRASE) ||
1389         !cryptographer->is_initialized()) {
1390       // Either at least one key rotation has been performed, so we no longer
1391       // care about backwards compatibility, or we're generating keystore-based
1392       // encryption keys without knowing the GAIA password (and therefore the
1393       // cryptographer is not initialized), so we can't support backwards
1394       // compatibility. Ensure the keystore key is the default key.
1395       DVLOG(1) << "Migrating keybag to keystore key.";
1396       bool cryptographer_was_ready = cryptographer->is_ready();
1397       if (!cryptographer->AddKey(key_params)) {
1398         LOG(ERROR) << "Failed to add keystore key as default key";
1399         UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1400                                   FAILED_TO_SET_DEFAULT_KEYSTORE,
1401                                   MIGRATION_RESULT_SIZE);
1402         return false;
1403       }
1404       if (!cryptographer_was_ready && cryptographer->is_ready()) {
1405         FOR_EACH_OBSERVER(
1406             SyncEncryptionHandler::Observer,
1407             observers_,
1408             OnPassphraseAccepted());
1409       }
1410     } else {
1411       // We're in backwards compatible mode -- either the account has an
1412       // explicit passphrase, or we want to preserve the current GAIA-based key
1413       // as the default because we can (there have been no key rotations since
1414       // the migration).
1415       DVLOG(1) << "Migrating keybag while preserving old key";
1416       if (!cryptographer->AddNonDefaultKey(key_params)) {
1417         LOG(ERROR) << "Failed to add keystore key as non-default key.";
1418         UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1419                                   FAILED_TO_SET_NONDEFAULT_KEYSTORE,
1420                                   MIGRATION_RESULT_SIZE);
1421         return false;
1422       }
1423     }
1424   }
1425   if (!old_keystore_keys_.empty()) {
1426     // Go through and add all the old keystore keys as non default keys, so
1427     // they'll be preserved in the encryption_keybag when we next write the
1428     // nigori node.
1429     for (std::vector<std::string>::const_iterator iter =
1430              old_keystore_keys_.begin(); iter != old_keystore_keys_.end();
1431          ++iter) {
1432       KeyParams key_params = {"localhost", "dummy", *iter};
1433       cryptographer->AddNonDefaultKey(key_params);
1434     }
1435   }
1436   if (new_passphrase_type == KEYSTORE_PASSPHRASE &&
1437       !GetKeystoreDecryptor(
1438           *cryptographer,
1439           keystore_key_,
1440           migrated_nigori.mutable_keystore_decryptor_token())) {
1441     LOG(ERROR) << "Failed to extract keystore decryptor token.";
1442     UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1443                               FAILED_TO_EXTRACT_DECRYPTOR,
1444                               MIGRATION_RESULT_SIZE);
1445     return false;
1446   }
1447   if (!cryptographer->GetKeys(migrated_nigori.mutable_encryption_keybag())) {
1448     LOG(ERROR) << "Failed to extract encryption keybag.";
1449     UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1450                               FAILED_TO_EXTRACT_KEYBAG,
1451                               MIGRATION_RESULT_SIZE);
1452     return false;
1453   }
1454
1455   if (migration_time_.is_null())
1456     migration_time_ = base::Time::Now();
1457   migrated_nigori.set_keystore_migration_time(TimeToProtoTime(migration_time_));
1458
1459   if (!custom_passphrase_time_.is_null()) {
1460     migrated_nigori.set_custom_passphrase_time(
1461         TimeToProtoTime(custom_passphrase_time_));
1462   }
1463
1464   FOR_EACH_OBSERVER(
1465       SyncEncryptionHandler::Observer,
1466       observers_,
1467       OnCryptographerStateChanged(cryptographer));
1468   if (passphrase_type_ != new_passphrase_type) {
1469     passphrase_type_ = new_passphrase_type;
1470     FOR_EACH_OBSERVER(SyncEncryptionHandler::Observer, observers_,
1471                             OnPassphraseTypeChanged(
1472                                 passphrase_type_,
1473                                 GetExplicitPassphraseTime()));
1474   }
1475
1476   if (new_encrypt_everything && !encrypt_everything_) {
1477     EnableEncryptEverythingImpl(trans->GetWrappedTrans());
1478     ReEncryptEverything(trans);
1479   } else if (!cryptographer->CanDecryptUsingDefaultKey(
1480                  old_nigori.encryption_keybag())) {
1481     DVLOG(1) << "Rencrypting everything due to key rotation.";
1482     ReEncryptEverything(trans);
1483   }
1484
1485   DVLOG(1) << "Completing nigori migration to keystore support.";
1486   nigori_node->SetNigoriSpecifics(migrated_nigori);
1487
1488   switch (new_passphrase_type) {
1489     case KEYSTORE_PASSPHRASE:
1490       if (old_keystore_keys_.size() > 0) {
1491         UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1492                                   MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
1493                                   MIGRATION_RESULT_SIZE);
1494       } else {
1495         UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1496                                   MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
1497                                   MIGRATION_RESULT_SIZE);
1498       }
1499       break;
1500     case FROZEN_IMPLICIT_PASSPHRASE:
1501       UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1502                                 MIGRATION_SUCCESS_FROZEN_IMPLICIT,
1503                                 MIGRATION_RESULT_SIZE);
1504       break;
1505     case CUSTOM_PASSPHRASE:
1506       UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
1507                                 MIGRATION_SUCCESS_CUSTOM,
1508                                 MIGRATION_RESULT_SIZE);
1509       break;
1510     default:
1511       NOTREACHED();
1512       break;
1513   }
1514   return true;
1515 }
1516
1517 bool SyncEncryptionHandlerImpl::GetKeystoreDecryptor(
1518     const Cryptographer& cryptographer,
1519     const std::string& keystore_key,
1520     sync_pb::EncryptedData* encrypted_blob) {
1521   DCHECK(thread_checker_.CalledOnValidThread());
1522   DCHECK(!keystore_key.empty());
1523   DCHECK(cryptographer.is_ready());
1524   std::string serialized_nigori;
1525   serialized_nigori = cryptographer.GetDefaultNigoriKey();
1526   if (serialized_nigori.empty()) {
1527     LOG(ERROR) << "Failed to get cryptographer bootstrap token.";
1528     return false;
1529   }
1530   Cryptographer temp_cryptographer(cryptographer.encryptor());
1531   KeyParams key_params = {"localhost", "dummy", keystore_key};
1532   if (!temp_cryptographer.AddKey(key_params))
1533     return false;
1534   if (!temp_cryptographer.EncryptString(serialized_nigori, encrypted_blob))
1535     return false;
1536   return true;
1537 }
1538
1539 bool SyncEncryptionHandlerImpl::AttemptToInstallKeybag(
1540     const sync_pb::EncryptedData& keybag,
1541     bool update_default,
1542     Cryptographer* cryptographer) {
1543   if (!cryptographer->CanDecrypt(keybag))
1544     return false;
1545   cryptographer->InstallKeys(keybag);
1546   if (update_default)
1547     cryptographer->SetDefaultKey(keybag.key_name());
1548   return true;
1549 }
1550
1551 void SyncEncryptionHandlerImpl::EnableEncryptEverythingImpl(
1552     syncable::BaseTransaction* const trans) {
1553   ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
1554   if (encrypt_everything_) {
1555     DCHECK(encrypted_types->Equals(EncryptableUserTypes()));
1556     return;
1557   }
1558   encrypt_everything_ = true;
1559   *encrypted_types = EncryptableUserTypes();
1560   FOR_EACH_OBSERVER(
1561       Observer, observers_,
1562       OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_));
1563 }
1564
1565 bool SyncEncryptionHandlerImpl::DecryptPendingKeysWithKeystoreKey(
1566     const std::string& keystore_key,
1567     const sync_pb::EncryptedData& keystore_decryptor_token,
1568     Cryptographer* cryptographer) {
1569   DCHECK(cryptographer->has_pending_keys());
1570   if (keystore_decryptor_token.blob().empty())
1571     return false;
1572   Cryptographer temp_cryptographer(cryptographer->encryptor());
1573
1574   // First, go through and all all the old keystore keys to the temporary
1575   // cryptographer.
1576   for (size_t i = 0; i < old_keystore_keys_.size(); ++i) {
1577     KeyParams old_key_params = {"localhost", "dummy", old_keystore_keys_[i]};
1578     temp_cryptographer.AddKey(old_key_params);
1579   }
1580
1581   // Then add the current keystore key as the default key and see if we can
1582   // decrypt.
1583   KeyParams keystore_params = {"localhost", "dummy", keystore_key_};
1584   if (temp_cryptographer.AddKey(keystore_params) &&
1585       temp_cryptographer.CanDecrypt(keystore_decryptor_token)) {
1586     // Someone else migrated the nigori for us! How generous! Go ahead and
1587     // install both the keystore key and the new default encryption key
1588     // (i.e. the one provided by the keystore decryptor token) into the
1589     // cryptographer.
1590     // The keystore decryptor token is a keystore key encrypted blob containing
1591     // the current serialized default encryption key (and as such should be
1592     // able to decrypt the nigori node's encryption keybag).
1593     // Note: it's possible a key rotation has happened since the migration, and
1594     // we're decrypting using an old keystore key. In that case we need to
1595     // ensure we re-encrypt using the newest key.
1596     DVLOG(1) << "Attempting to decrypt pending keys using "
1597              << "keystore decryptor token.";
1598     std::string serialized_nigori =
1599         temp_cryptographer.DecryptToString(keystore_decryptor_token);
1600
1601     // This will decrypt the pending keys and add them if possible. The key
1602     // within |serialized_nigori| will be the default after.
1603     cryptographer->ImportNigoriKey(serialized_nigori);
1604
1605     if (!temp_cryptographer.CanDecryptUsingDefaultKey(
1606             keystore_decryptor_token)) {
1607       // The keystore decryptor token was derived from an old keystore key.
1608       // A key rotation is necessary, so set the current keystore key as the
1609       // default key (which will trigger a re-migration).
1610       DVLOG(1) << "Pending keys based on old keystore key. Setting newest "
1611                << "keystore key as default.";
1612       cryptographer->AddKey(keystore_params);
1613     } else {
1614       // Theoretically the encryption keybag should already contain the keystore
1615       // key. We explicitly add it as a safety measure.
1616       DVLOG(1) << "Pending keys based on newest keystore key.";
1617       cryptographer->AddNonDefaultKey(keystore_params);
1618     }
1619     if (cryptographer->is_ready()) {
1620       std::string bootstrap_token;
1621       cryptographer->GetBootstrapToken(&bootstrap_token);
1622       DVLOG(1) << "Keystore decryptor token decrypted pending keys.";
1623       FOR_EACH_OBSERVER(
1624           SyncEncryptionHandler::Observer,
1625           observers_,
1626           OnPassphraseAccepted());
1627       FOR_EACH_OBSERVER(
1628           SyncEncryptionHandler::Observer,
1629           observers_,
1630           OnBootstrapTokenUpdated(bootstrap_token,
1631                                   PASSPHRASE_BOOTSTRAP_TOKEN));
1632       FOR_EACH_OBSERVER(
1633           SyncEncryptionHandler::Observer,
1634           observers_,
1635           OnCryptographerStateChanged(cryptographer));
1636       return true;
1637     }
1638   }
1639   return false;
1640 }
1641
1642 base::Time SyncEncryptionHandlerImpl::GetExplicitPassphraseTime() const {
1643   if (passphrase_type_ == FROZEN_IMPLICIT_PASSPHRASE)
1644     return migration_time();
1645   else if (passphrase_type_ == CUSTOM_PASSPHRASE)
1646     return custom_passphrase_time();
1647   return base::Time();
1648 }
1649
1650 }  // namespace browser_sync