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"
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"
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
) {
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();
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()) {
57 std::string serialized_nigori_key
=
58 UnpackBootstrapToken(restored_bootstrap_token
);
59 if (serialized_nigori_key
.empty())
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 {
78 if (default_nigori_name_
.empty()) {
79 LOG(ERROR
) << "Cryptographer not ready, failed to encrypt.";
83 std::string serialized
;
84 if (!message
.SerializeToString(&serialized
)) {
85 LOG(ERROR
) << "Message is invalid/missing a required field.";
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.";
103 NigoriMap::const_iterator default_nigori
=
104 nigoris_
.find(default_nigori_name_
);
105 if (default_nigori
== nigoris_
.end()) {
106 LOG(ERROR
) << "Corrupt default key.";
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.";
119 bool Cryptographer::Decrypt(const sync_pb::EncryptedData
& encrypted
,
120 ::google::protobuf::MessageLite
* message
) const {
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
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();
144 bool Cryptographer::GetKeys(sync_pb::EncryptedData
* encrypted
) const {
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();
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
,
170 NOTREACHED(); // Invalid username or password.
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
,
183 NOTREACHED(); // Invalid username or password.
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
) {
200 if (!initialized_nigori
->Permute(Nigori::Password
, kNigoriKeyName
, &name
)) {
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
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
);
222 void Cryptographer::InstallKeys(const sync_pb::EncryptedData
& encrypted
) {
223 DCHECK(CanDecrypt(encrypted
));
225 sync_pb::NigoriKeyBag bag
;
226 if (!Decrypt(encrypted
, &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
) {
249 if (!nigori
.InitByDerivation(params
.hostname
,
256 std::string plaintext
;
257 if (!nigori
.Decrypt(pending_keys_
->blob(), &plaintext
))
260 sync_pb::NigoriKeyBag bag
;
261 if (!bag
.ParseFromString(plaintext
)) {
266 const std::string
& new_default_key_name
= pending_keys_
->key_name();
267 SetDefaultKey(new_default_key_name
);
268 pending_keys_
.reset();
272 bool Cryptographer::GetBootstrapToken(std::string
* token
) const {
274 std::string unencrypted_token
= GetDefaultNigoriKeyData();
275 if (unencrypted_token
.empty())
278 std::string encrypted_token
;
279 if (!encryptor_
->EncryptString(unencrypted_token
, &encrypted_token
)) {
283 base::Base64Encode(encrypted_token
, token
);
288 std::string
Cryptographer::UnpackBootstrapToken(
289 const std::string
& token
) const {
291 return std::string();
293 std::string encrypted_data
;
294 if (!base::Base64Decode(token
, &encrypted_data
)) {
295 DLOG(WARNING
) << "Could not decode token.";
296 return std::string();
299 std::string unencrypted_token
;
300 if (!encryptor_
->DecryptString(encrypted_data
, &unencrypted_token
)) {
301 DLOG(WARNING
) << "Decryption of bootstrap token failed.";
302 return std::string();
304 return unencrypted_token
;
307 void Cryptographer::InstallKeyBag(const sync_pb::NigoriKeyBag
& bag
) {
308 int key_size
= bag
.key_size();
309 for (int i
= 0; i
< key_size
; ++i
) {
310 const sync_pb::NigoriKey key
= bag
.key(i
);
311 // Only use this key if we don't already know about it.
312 if (nigoris_
.end() == nigoris_
.find(key
.name())) {
313 scoped_ptr
<Nigori
> new_nigori(new Nigori
);
314 if (!new_nigori
->InitByImport(key
.user_key(),
315 key
.encryption_key(),
320 nigoris_
[key
.name()] = make_linked_ptr(new_nigori
.release());
325 bool Cryptographer::KeybagIsStale(
326 const sync_pb::EncryptedData
& encrypted_bag
) const {
329 if (encrypted_bag
.blob().empty())
331 if (!CanDecrypt(encrypted_bag
))
333 if (!CanDecryptUsingDefaultKey(encrypted_bag
))
335 sync_pb::NigoriKeyBag bag
;
336 if (!Decrypt(encrypted_bag
, &bag
)) {
337 LOG(ERROR
) << "Failed to decrypt keybag for stale check. "
338 << "Assuming keybag is corrupted.";
341 if (static_cast<size_t>(bag
.key_size()) < nigoris_
.size())
346 std::string
Cryptographer::GetDefaultNigoriKeyName() const {
347 return default_nigori_name_
;
350 std::string
Cryptographer::GetDefaultNigoriKeyData() const {
351 if (!is_initialized())
352 return std::string();
353 NigoriMap::const_iterator iter
= nigoris_
.find(default_nigori_name_
);
354 if (iter
== nigoris_
.end())
355 return std::string();
356 sync_pb::NigoriKey key
;
357 if (!iter
->second
->ExportKeys(key
.mutable_user_key(),
358 key
.mutable_encryption_key(),
359 key
.mutable_mac_key()))
360 return std::string();
361 return key
.SerializeAsString();
364 bool Cryptographer::ImportNigoriKey(const std::string serialized_nigori_key
) {
365 if (serialized_nigori_key
.empty())
368 sync_pb::NigoriKey key
;
369 if (!key
.ParseFromString(serialized_nigori_key
))
372 scoped_ptr
<Nigori
> nigori(new Nigori
);
373 if (!nigori
->InitByImport(key
.user_key(), key
.encryption_key(),
379 if (!AddKeyImpl(nigori
.Pass(), true))
384 } // namespace syncer