Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / sync / internal_api / sync_encryption_handler_impl.h
blob2db4c478496b2f907554b57b6ff2b6dc05555f3c
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef SYNC_INTERNAL_API_SYNC_ENCRYPTION_HANDLER_IMPL_H_
6 #define SYNC_INTERNAL_API_SYNC_ENCRYPTION_HANDLER_IMPL_H_
8 #include <string>
10 #include "base/compiler_specific.h"
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/observer_list.h"
15 #include "base/threading/thread_checker.h"
16 #include "base/time/time.h"
17 #include "sync/base/sync_export.h"
18 #include "sync/internal_api/public/sync_encryption_handler.h"
19 #include "sync/syncable/nigori_handler.h"
20 #include "sync/util/cryptographer.h"
22 namespace syncer {
24 class Encryptor;
25 struct UserShare;
26 class WriteNode;
27 class WriteTransaction;
29 // Sync encryption handler implementation.
31 // This class acts as the respository of all sync encryption state, and handles
32 // encryption related changes/queries coming from both the chrome side and
33 // the sync side (via NigoriHandler). It is capable of modifying all sync data
34 // (re-encryption), updating the encrypted types, changing the encryption keys,
35 // and creating/receiving nigori node updates.
37 // The class should live as long as the directory itself in order to ensure
38 // any data read/written is properly decrypted/encrypted.
40 // Note: See sync_encryption_handler.h for a description of the chrome visible
41 // methods and what they do, and nigori_handler.h for a description of the
42 // sync methods.
43 // All methods are non-thread-safe and should only be called from the sync
44 // thread unless explicitly noted otherwise.
45 class SYNC_EXPORT_PRIVATE SyncEncryptionHandlerImpl
46 : public SyncEncryptionHandler,
47 public syncable::NigoriHandler {
48 public:
49 SyncEncryptionHandlerImpl(
50 UserShare* user_share,
51 Encryptor* encryptor,
52 const std::string& restored_key_for_bootstrapping,
53 const std::string& restored_keystore_key_for_bootstrapping);
54 ~SyncEncryptionHandlerImpl() override;
56 // SyncEncryptionHandler implementation.
57 void AddObserver(Observer* observer) override;
58 void RemoveObserver(Observer* observer) override;
59 void Init() override;
60 void SetEncryptionPassphrase(const std::string& passphrase,
61 bool is_explicit) override;
62 void SetDecryptionPassphrase(const std::string& passphrase) override;
63 void EnableEncryptEverything() override;
64 bool EncryptEverythingEnabled() const override;
65 PassphraseType GetPassphraseType() const override;
67 // NigoriHandler implementation.
68 // Note: all methods are invoked while the caller holds a transaction.
69 void ApplyNigoriUpdate(const sync_pb::NigoriSpecifics& nigori,
70 syncable::BaseTransaction* const trans) override;
71 void UpdateNigoriFromEncryptedTypes(
72 sync_pb::NigoriSpecifics* nigori,
73 syncable::BaseTransaction* const trans) const override;
74 bool NeedKeystoreKey(syncable::BaseTransaction* const trans) const override;
75 bool SetKeystoreKeys(
76 const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys,
77 syncable::BaseTransaction* const trans) override;
78 // Can be called from any thread.
79 ModelTypeSet GetEncryptedTypes(
80 syncable::BaseTransaction* const trans) const override;
82 // Unsafe getters. Use only if sync is not up and running and there is no risk
83 // of other threads calling this.
84 Cryptographer* GetCryptographerUnsafe();
85 ModelTypeSet GetEncryptedTypesUnsafe();
87 bool MigratedToKeystore();
88 base::Time migration_time() const;
89 base::Time custom_passphrase_time() const;
91 private:
92 friend class SyncEncryptionHandlerImplTest;
93 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
94 NigoriEncryptionTypes);
95 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
96 EncryptEverythingExplicit);
97 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
98 EncryptEverythingImplicit);
99 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
100 UnknownSensitiveTypes);
101 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
102 GetKeystoreDecryptor);
103 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
104 ReceiveMigratedNigoriKeystorePass);
105 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
106 ReceiveUmigratedNigoriAfterMigration);
107 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
108 ReceiveOldMigratedNigori);
109 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
110 SetKeystoreAfterReceivingMigratedNigori);
111 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
112 SetCustomPassAfterMigration);
113 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
114 SetCustomPassAfterMigrationNoKeystoreKey);
115 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
116 SetImplicitPassAfterMigrationNoKeystoreKey);
117 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
118 MigrateOnEncryptEverythingKeystorePassphrase);
119 FRIEND_TEST_ALL_PREFIXES(SyncEncryptionHandlerImplTest,
120 ReceiveMigratedNigoriWithOldPassphrase);
122 // Container for members that require thread safety protection. All members
123 // that can be accessed from more than one thread should be held here and
124 // accessed via UnlockVault(..) and UnlockVaultMutable(..), which enforce
125 // that a transaction is held.
126 struct Vault {
127 Vault(Encryptor* encryptor, ModelTypeSet encrypted_types);
128 ~Vault();
130 // Sync's cryptographer. Used for encrypting and decrypting sync data.
131 Cryptographer cryptographer;
132 // The set of types that require encryption.
133 ModelTypeSet encrypted_types;
135 private:
136 DISALLOW_COPY_AND_ASSIGN(Vault);
139 // Iterate over all encrypted types ensuring each entry is properly encrypted.
140 void ReEncryptEverything(WriteTransaction* trans);
142 // Apply a nigori update. Updates internal and cryptographer state.
143 // Returns true on success, false if |nigori| was incompatible, and the
144 // nigori node must be corrected.
145 // Note: must be called from within a transaction.
146 bool ApplyNigoriUpdateImpl(const sync_pb::NigoriSpecifics& nigori,
147 syncable::BaseTransaction* const trans);
149 // Wrapper around WriteEncryptionStateToNigori that creates a new write
150 // transaction.
151 void RewriteNigori();
153 // Write the current encryption state into the nigori node. This includes
154 // the encrypted types/encrypt everything state, as well as the keybag/
155 // explicit passphrase state (if the cryptographer is ready).
156 void WriteEncryptionStateToNigori(WriteTransaction* trans);
158 // Updates local encrypted types from |nigori|.
159 // Returns true if the local set of encrypted types either matched or was
160 // a subset of that in |nigori|. Returns false if the local state already
161 // had stricter encryption than |nigori|, and the nigori node needs to be
162 // updated with the newer encryption state.
163 // Note: must be called from within a transaction.
164 bool UpdateEncryptedTypesFromNigori(
165 const sync_pb::NigoriSpecifics& nigori,
166 syncable::BaseTransaction* const trans);
168 // TODO(zea): make these public and have them replace SetEncryptionPassphrase
169 // and SetDecryptionPassphrase.
170 // Helper methods for handling passphrases once keystore migration has taken
171 // place.
173 // Sets a new custom passphrase. Should only be called if a custom passphrase
174 // is not already set.
175 // Triggers OnPassphraseAccepted on success, OnPassphraseRequired if a custom
176 // passphrase already existed.
177 void SetCustomPassphrase(const std::string& passphrase,
178 WriteTransaction* trans,
179 WriteNode* nigori_node);
180 // Decrypt the encryption keybag using a user provided passphrase.
181 // Should only be called if the current passphrase is a frozen implicit
182 // passphrase or a custom passphrase.
183 // Triggers OnPassphraseAccepted on success, OnPassphraseRequired on failure.
184 void DecryptPendingKeysWithExplicitPassphrase(const std::string& passphrase,
185 WriteTransaction* trans,
186 WriteNode* nigori_node);
188 // The final step of SetEncryptionPassphrase and SetDecryptionPassphrase that
189 // notifies observers of the result of the set passphrase operation, updates
190 // the nigori node, and does re-encryption.
191 // |success|: true if the operation was successful and false otherwise. If
192 // success == false, we send an OnPassphraseRequired notification.
193 // |bootstrap_token|: used to inform observers if the cryptographer's
194 // bootstrap token was updated.
195 // |is_explicit|: used to differentiate between a custom passphrase (true) and
196 // a GAIA passphrase that is implicitly used for encryption
197 // (false).
198 // |trans| and |nigori_node|: used to access data in the cryptographer.
199 void FinishSetPassphrase(bool success,
200 const std::string& bootstrap_token,
201 WriteTransaction* trans,
202 WriteNode* nigori_node);
204 // Merges the given set of encrypted types with the existing set and emits a
205 // notification if necessary.
206 // Note: must be called from within a transaction.
207 void MergeEncryptedTypes(ModelTypeSet new_encrypted_types,
208 syncable::BaseTransaction* const trans);
210 // Helper methods for ensuring transactions are held when accessing
211 // |vault_unsafe_|.
212 Vault* UnlockVaultMutable(syncable::BaseTransaction* const trans);
213 const Vault& UnlockVault(syncable::BaseTransaction* const trans) const;
215 // Helper method for determining if migration of a nigori node should be
216 // triggered or not.
217 // Conditions for triggering migration:
218 // 1. Cryptographer has no pending keys
219 // 2. Nigori node isn't already properly migrated or we need to rotate keys.
220 // 3. Keystore key is available.
221 // Note: if the nigori node is migrated but has an invalid state, will return
222 // true (e.g. node has KEYSTORE_PASSPHRASE, local is CUSTOM_PASSPHRASE).
223 bool ShouldTriggerMigration(const sync_pb::NigoriSpecifics& nigori,
224 const Cryptographer& cryptographer) const;
226 // Performs the actual migration of the |nigori_node| to support keystore
227 // encryption iff ShouldTriggerMigration(..) returns true.
228 bool AttemptToMigrateNigoriToKeystore(WriteTransaction* trans,
229 WriteNode* nigori_node);
231 // Fill |encrypted_blob| with the keystore decryptor token if
232 // |encrypted_blob|'s contents didn't already contain the key.
233 // The keystore decryptor token is the serialized current default encryption
234 // key, encrypted with the keystore key.
235 bool GetKeystoreDecryptor(
236 const Cryptographer& cryptographer,
237 const std::string& keystore_key,
238 sync_pb::EncryptedData* encrypted_blob);
240 // Helper method for installing the keys encrypted in |encryption_keybag|
241 // into |cryptographer|.
242 // Returns true on success, false if we were unable to install the keybag.
243 // Will not update the default key.
244 bool AttemptToInstallKeybag(const sync_pb::EncryptedData& keybag,
245 bool update_default,
246 Cryptographer* cryptographer);
248 // Helper method for decrypting pending keys with the keystore bootstrap.
249 // If successful, the default will become the key encrypted in the keystore
250 // bootstrap, and will return true. Else will return false.
251 bool DecryptPendingKeysWithKeystoreKey(
252 const std::string& keystore_key,
253 const sync_pb::EncryptedData& keystore_bootstrap,
254 Cryptographer* cryptographer);
256 // Helper to enable encrypt everything, notifying observers if necessary.
257 // Will not perform re-encryption.
258 void EnableEncryptEverythingImpl(syncable::BaseTransaction* const trans);
260 // If an explicit passphrase is in use, returns the time at which it was set
261 // (if known). Else return base::Time().
262 base::Time GetExplicitPassphraseTime() const;
264 base::ThreadChecker thread_checker_;
266 ObserverList<SyncEncryptionHandler::Observer> observers_;
268 // The current user share (for creating transactions).
269 UserShare* user_share_;
271 // Container for all data that can be accessed from multiple threads. Do not
272 // access this object directly. Instead access it via UnlockVault(..) and
273 // UnlockVaultMutable(..).
274 Vault vault_unsafe_;
276 // Sync encryption state that is only modified and accessed from the sync
277 // thread.
278 // Whether all current and future types should be encrypted.
279 bool encrypt_everything_;
280 // The current state of the passphrase required to decrypt the encryption
281 // keys stored in the nigori node.
282 PassphraseType passphrase_type_;
284 // The current keystore key provided by the server.
285 std::string keystore_key_;
287 // The set of old keystore keys. Every time a key rotation occurs, the server
288 // sends down all previous keystore keys as well as the new key. We preserve
289 // the old keys so that when we re-encrypt we can ensure they're all added to
290 // the keybag (and to detect that a key rotation has occurred).
291 std::vector<std::string> old_keystore_keys_;
293 // The number of times we've automatically (i.e. not via SetPassphrase or
294 // conflict resolver) updated the nigori's encryption keys in this chrome
295 // instantiation.
296 int nigori_overwrite_count_;
298 // The time the nigori was migrated to support keystore encryption.
299 base::Time migration_time_;
301 // The time the custom passphrase was set for this account. Not valid
302 // if there is no custom passphrase or the custom passphrase was set
303 // before support for this field was added.
304 base::Time custom_passphrase_time_;
306 base::WeakPtrFactory<SyncEncryptionHandlerImpl> weak_ptr_factory_;
308 DISALLOW_COPY_AND_ASSIGN(SyncEncryptionHandlerImpl);
311 } // namespace syncer
313 #endif // SYNC_INTERNAL_API_PUBLIC_SYNC_ENCRYPTION_HANDLER_IMPL_H_