Use single and correct URL to flot library homepage
[chromium-blink-merge.git] / sync / util / cryptographer.cc
blobbccf9a28bd8ebbb2b0f90e7cb5e518f6f3c6b5ae
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sync/util/cryptographer.h"
7 #include <algorithm>
9 #include "base/base64.h"
10 #include "base/basictypes.h"
11 #include "base/logging.h"
12 #include "sync/protocol/nigori_specifics.pb.h"
13 #include "sync/util/encryptor.h"
15 namespace syncer {
17 const char kNigoriTag[] = "google_chrome_nigori";
19 // We name a particular Nigori instance (ie. a triplet consisting of a hostname,
20 // a username, and a password) by calling Permute on this string. Since the
21 // output of Permute is always the same for a given triplet, clients will always
22 // assign the same name to a particular triplet.
23 const char kNigoriKeyName[] = "nigori-key";
25 Cryptographer::Cryptographer(Encryptor* encryptor)
26 : encryptor_(encryptor) {
27 DCHECK(encryptor);
30 Cryptographer::Cryptographer(const Cryptographer& other)
31 : encryptor_(other.encryptor_),
32 default_nigori_name_(other.default_nigori_name_) {
33 for (NigoriMap::const_iterator it = other.nigoris_.begin();
34 it != other.nigoris_.end();
35 ++it) {
36 std::string user_key, encryption_key, mac_key;
37 it->second->ExportKeys(&user_key, &encryption_key, &mac_key);
38 linked_ptr<Nigori> nigori_copy(new Nigori());
39 nigori_copy->InitByImport(user_key, encryption_key, mac_key);
40 nigoris_.insert(std::make_pair(it->first, nigori_copy));
43 if (other.pending_keys_) {
44 pending_keys_.reset(new sync_pb::EncryptedData(*(other.pending_keys_)));
48 Cryptographer::~Cryptographer() {}
51 void Cryptographer::Bootstrap(const std::string& restored_bootstrap_token) {
52 if (is_initialized()) {
53 NOTREACHED();
54 return;
57 std::string serialized_nigori_key =
58 UnpackBootstrapToken(restored_bootstrap_token);
59 if (serialized_nigori_key.empty())
60 return;
61 ImportNigoriKey(serialized_nigori_key);
64 bool Cryptographer::CanDecrypt(const sync_pb::EncryptedData& data) const {
65 return nigoris_.end() != nigoris_.find(data.key_name());
68 bool Cryptographer::CanDecryptUsingDefaultKey(
69 const sync_pb::EncryptedData& data) const {
70 return !default_nigori_name_.empty() &&
71 data.key_name() == default_nigori_name_;
74 bool Cryptographer::Encrypt(
75 const ::google::protobuf::MessageLite& message,
76 sync_pb::EncryptedData* encrypted) const {
77 DCHECK(encrypted);
78 if (default_nigori_name_.empty()) {
79 LOG(ERROR) << "Cryptographer not ready, failed to encrypt.";
80 return false;
83 std::string serialized;
84 if (!message.SerializeToString(&serialized)) {
85 LOG(ERROR) << "Message is invalid/missing a required field.";
86 return false;
89 return EncryptString(serialized, encrypted);
92 bool Cryptographer::EncryptString(
93 const std::string& serialized,
94 sync_pb::EncryptedData* encrypted) const {
95 if (CanDecryptUsingDefaultKey(*encrypted)) {
96 const std::string& original_serialized = DecryptToString(*encrypted);
97 if (original_serialized == serialized) {
98 DVLOG(2) << "Re-encryption unnecessary, encrypted data already matches.";
99 return true;
103 NigoriMap::const_iterator default_nigori =
104 nigoris_.find(default_nigori_name_);
105 if (default_nigori == nigoris_.end()) {
106 LOG(ERROR) << "Corrupt default key.";
107 return false;
110 encrypted->set_key_name(default_nigori_name_);
111 if (!default_nigori->second->Encrypt(serialized,
112 encrypted->mutable_blob())) {
113 LOG(ERROR) << "Failed to encrypt data.";
114 return false;
116 return true;
119 bool Cryptographer::Decrypt(const sync_pb::EncryptedData& encrypted,
120 ::google::protobuf::MessageLite* message) const {
121 DCHECK(message);
122 std::string plaintext = DecryptToString(encrypted);
123 return message->ParseFromString(plaintext);
126 std::string Cryptographer::DecryptToString(
127 const sync_pb::EncryptedData& encrypted) const {
128 NigoriMap::const_iterator it = nigoris_.find(encrypted.key_name());
129 if (nigoris_.end() == it) {
130 // The key used to encrypt the blob is not part of the set of installed
131 // nigoris.
132 LOG(ERROR) << "Cannot decrypt message";
133 return std::string();
136 std::string plaintext;
137 if (!it->second->Decrypt(encrypted.blob(), &plaintext)) {
138 return std::string();
141 return plaintext;
144 bool Cryptographer::GetKeys(sync_pb::EncryptedData* encrypted) const {
145 DCHECK(encrypted);
146 DCHECK(!nigoris_.empty());
148 // Create a bag of all the Nigori parameters we know about.
149 sync_pb::NigoriKeyBag bag;
150 for (NigoriMap::const_iterator it = nigoris_.begin(); it != nigoris_.end();
151 ++it) {
152 const Nigori& nigori = *it->second;
153 sync_pb::NigoriKey* key = bag.add_key();
154 key->set_name(it->first);
155 nigori.ExportKeys(key->mutable_user_key(),
156 key->mutable_encryption_key(),
157 key->mutable_mac_key());
160 // Encrypt the bag with the default Nigori.
161 return Encrypt(bag, encrypted);
164 bool Cryptographer::AddKey(const KeyParams& params) {
165 // Create the new Nigori and make it the default encryptor.
166 scoped_ptr<Nigori> nigori(new Nigori);
167 if (!nigori->InitByDerivation(params.hostname,
168 params.username,
169 params.password)) {
170 NOTREACHED(); // Invalid username or password.
171 return false;
173 return AddKeyImpl(nigori.Pass(), true);
176 bool Cryptographer::AddNonDefaultKey(const KeyParams& params) {
177 DCHECK(is_initialized());
178 // Create the new Nigori and add it to the keybag.
179 scoped_ptr<Nigori> nigori(new Nigori);
180 if (!nigori->InitByDerivation(params.hostname,
181 params.username,
182 params.password)) {
183 NOTREACHED(); // Invalid username or password.
184 return false;
186 return AddKeyImpl(nigori.Pass(), false);
189 bool Cryptographer::AddKeyFromBootstrapToken(
190 const std::string restored_bootstrap_token) {
191 // Create the new Nigori and make it the default encryptor.
192 std::string serialized_nigori_key = UnpackBootstrapToken(
193 restored_bootstrap_token);
194 return ImportNigoriKey(serialized_nigori_key);
197 bool Cryptographer::AddKeyImpl(scoped_ptr<Nigori> initialized_nigori,
198 bool set_as_default) {
199 std::string name;
200 if (!initialized_nigori->Permute(Nigori::Password, kNigoriKeyName, &name)) {
201 NOTREACHED();
202 return false;
205 nigoris_[name] = make_linked_ptr(initialized_nigori.release());
207 // Check if the key we just added can decrypt the pending keys and add them
208 // too if so.
209 if (pending_keys_.get() && CanDecrypt(*pending_keys_)) {
210 sync_pb::NigoriKeyBag pending_bag;
211 Decrypt(*pending_keys_, &pending_bag);
212 InstallKeyBag(pending_bag);
213 SetDefaultKey(pending_keys_->key_name());
214 pending_keys_.reset();
217 // The just-added key takes priority over the pending keys as default.
218 if (set_as_default) SetDefaultKey(name);
219 return true;
222 void Cryptographer::InstallKeys(const sync_pb::EncryptedData& encrypted) {
223 DCHECK(CanDecrypt(encrypted));
225 sync_pb::NigoriKeyBag bag;
226 if (!Decrypt(encrypted, &bag))
227 return;
228 InstallKeyBag(bag);
231 void Cryptographer::SetDefaultKey(const std::string& key_name) {
232 DCHECK(nigoris_.end() != nigoris_.find(key_name));
233 default_nigori_name_ = key_name;
236 void Cryptographer::SetPendingKeys(const sync_pb::EncryptedData& encrypted) {
237 DCHECK(!CanDecrypt(encrypted));
238 DCHECK(!encrypted.blob().empty());
239 pending_keys_.reset(new sync_pb::EncryptedData(encrypted));
242 const sync_pb::EncryptedData& Cryptographer::GetPendingKeys() const {
243 DCHECK(has_pending_keys());
244 return *(pending_keys_.get());
247 bool Cryptographer::DecryptPendingKeys(const KeyParams& params) {
248 Nigori nigori;
249 if (!nigori.InitByDerivation(params.hostname,
250 params.username,
251 params.password)) {
252 NOTREACHED();
253 return false;
256 std::string plaintext;
257 if (!nigori.Decrypt(pending_keys_->blob(), &plaintext))
258 return false;
260 sync_pb::NigoriKeyBag bag;
261 if (!bag.ParseFromString(plaintext)) {
262 NOTREACHED();
263 return false;
265 InstallKeyBag(bag);
266 const std::string& new_default_key_name = pending_keys_->key_name();
267 SetDefaultKey(new_default_key_name);
268 pending_keys_.reset();
269 return true;
272 bool Cryptographer::GetBootstrapToken(std::string* token) const {
273 DCHECK(token);
274 std::string unencrypted_token = GetDefaultNigoriKeyData();
275 if (unencrypted_token.empty())
276 return false;
278 std::string encrypted_token;
279 if (!encryptor_->EncryptString(unencrypted_token, &encrypted_token)) {
280 NOTREACHED();
281 return false;
284 base::Base64Encode(encrypted_token, token);
286 return true;
289 std::string Cryptographer::UnpackBootstrapToken(
290 const std::string& token) const {
291 if (token.empty())
292 return std::string();
294 std::string encrypted_data;
295 if (!base::Base64Decode(token, &encrypted_data)) {
296 DLOG(WARNING) << "Could not decode token.";
297 return std::string();
300 std::string unencrypted_token;
301 if (!encryptor_->DecryptString(encrypted_data, &unencrypted_token)) {
302 DLOG(WARNING) << "Decryption of bootstrap token failed.";
303 return std::string();
305 return unencrypted_token;
308 void Cryptographer::InstallKeyBag(const sync_pb::NigoriKeyBag& bag) {
309 int key_size = bag.key_size();
310 for (int i = 0; i < key_size; ++i) {
311 const sync_pb::NigoriKey key = bag.key(i);
312 // Only use this key if we don't already know about it.
313 if (nigoris_.end() == nigoris_.find(key.name())) {
314 scoped_ptr<Nigori> new_nigori(new Nigori);
315 if (!new_nigori->InitByImport(key.user_key(),
316 key.encryption_key(),
317 key.mac_key())) {
318 NOTREACHED();
319 continue;
321 nigoris_[key.name()] = make_linked_ptr(new_nigori.release());
326 bool Cryptographer::KeybagIsStale(
327 const sync_pb::EncryptedData& encrypted_bag) const {
328 if (!is_ready())
329 return false;
330 if (encrypted_bag.blob().empty())
331 return true;
332 if (!CanDecrypt(encrypted_bag))
333 return false;
334 if (!CanDecryptUsingDefaultKey(encrypted_bag))
335 return true;
336 sync_pb::NigoriKeyBag bag;
337 if (!Decrypt(encrypted_bag, &bag)) {
338 LOG(ERROR) << "Failed to decrypt keybag for stale check. "
339 << "Assuming keybag is corrupted.";
340 return true;
342 if (static_cast<size_t>(bag.key_size()) < nigoris_.size())
343 return true;
344 return false;
347 std::string Cryptographer::GetDefaultNigoriKeyName() const {
348 return default_nigori_name_;
351 std::string Cryptographer::GetDefaultNigoriKeyData() const {
352 if (!is_initialized())
353 return std::string();
354 NigoriMap::const_iterator iter = nigoris_.find(default_nigori_name_);
355 if (iter == nigoris_.end())
356 return std::string();
357 sync_pb::NigoriKey key;
358 if (!iter->second->ExportKeys(key.mutable_user_key(),
359 key.mutable_encryption_key(),
360 key.mutable_mac_key()))
361 return std::string();
362 return key.SerializeAsString();
365 bool Cryptographer::ImportNigoriKey(const std::string serialized_nigori_key) {
366 if (serialized_nigori_key.empty())
367 return false;
369 sync_pb::NigoriKey key;
370 if (!key.ParseFromString(serialized_nigori_key))
371 return false;
373 scoped_ptr<Nigori> nigori(new Nigori);
374 if (!nigori->InitByImport(key.user_key(), key.encryption_key(),
375 key.mac_key())) {
376 NOTREACHED();
377 return false;
380 if (!AddKeyImpl(nigori.Pass(), true))
381 return false;
382 return true;
385 } // namespace syncer