os_crypt_linux.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright 2016 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. #include "components/os_crypt/os_crypt.h"
  5. #include <stddef.h>
  6. #include <algorithm>
  7. #include <iterator>
  8. #include <memory>
  9. #include "base/cxx17_backports.h"
  10. #include "base/logging.h"
  11. #include "base/memory/singleton.h"
  12. #include "base/no_destructor.h"
  13. #include "base/strings/string_util.h"
  14. #include "base/strings/utf_string_conversions.h"
  15. #include "base/synchronization/lock.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "components/os_crypt/key_storage_config_linux.h"
  18. #include "components/os_crypt/key_storage_linux.h"
  19. #include "crypto/encryptor.h"
  20. #include "crypto/symmetric_key.h"
  21. namespace {
  22. // Salt for Symmetric key derivation.
  23. constexpr char kSalt[] = "saltysalt";
  24. // Key size required for 128 bit AES.
  25. constexpr size_t kDerivedKeySizeInBits = 128;
  26. // Constant for Symmetric key derivation.
  27. constexpr size_t kEncryptionIterations = 1;
  28. // Size of initialization vector for AES 128-bit.
  29. constexpr size_t kIVBlockSizeAES128 = 16;
  30. // Prefixes for cypher text returned by obfuscation version. We prefix the
  31. // ciphertext with this string so that future data migration can detect
  32. // this and migrate to full encryption without data loss. kObfuscationPrefixV10
  33. // means that the hardcoded password will be used. kObfuscationPrefixV11 means
  34. // that a password is/will be stored using an OS-level library (e.g Libsecret).
  35. // V11 will not be used if such a library is not available.
  36. constexpr char kObfuscationPrefixV10[] = "v10";
  37. constexpr char kObfuscationPrefixV11[] = "v11";
  38. // Generates a newly allocated SymmetricKey object based on a password.
  39. // Ownership of the key is passed to the caller. Returns null key if a key
  40. // generation error occurs.
  41. std::unique_ptr<crypto::SymmetricKey> GenerateEncryptionKey(
  42. const std::string& password) {
  43. const std::string salt(kSalt);
  44. // Create an encryption key from our password and salt.
  45. std::unique_ptr<crypto::SymmetricKey> encryption_key(
  46. crypto::SymmetricKey::DeriveKeyFromPasswordUsingPbkdf2(
  47. crypto::SymmetricKey::AES, password, salt, kEncryptionIterations,
  48. kDerivedKeySizeInBits));
  49. DCHECK(encryption_key);
  50. return encryption_key;
  51. }
  52. } // namespace
  53. namespace OSCrypt {
  54. void SetConfig(std::unique_ptr<os_crypt::Config> config) {
  55. OSCryptImpl::GetInstance()->SetConfig(std::move(config));
  56. }
  57. bool EncryptString16(const std::u16string& plaintext, std::string* ciphertext) {
  58. return OSCryptImpl::GetInstance()->EncryptString16(plaintext, ciphertext);
  59. }
  60. bool DecryptString16(const std::string& ciphertext, std::u16string* plaintext) {
  61. return OSCryptImpl::GetInstance()->DecryptString16(ciphertext, plaintext);
  62. }
  63. bool EncryptString(const std::string& plaintext, std::string* ciphertext) {
  64. return OSCryptImpl::GetInstance()->EncryptString(plaintext, ciphertext);
  65. }
  66. bool DecryptString(const std::string& ciphertext, std::string* plaintext) {
  67. return OSCryptImpl::GetInstance()->DecryptString(ciphertext, plaintext);
  68. }
  69. std::string GetRawEncryptionKey() {
  70. return OSCryptImpl::GetInstance()->GetRawEncryptionKey();
  71. }
  72. void SetRawEncryptionKey(const std::string& key) {
  73. OSCryptImpl::GetInstance()->SetRawEncryptionKey(key);
  74. }
  75. bool IsEncryptionAvailable() {
  76. return OSCryptImpl::GetInstance()->IsEncryptionAvailable();
  77. }
  78. void UseMockKeyStorageForTesting(
  79. base::OnceCallback<std::unique_ptr<KeyStorageLinux>()>
  80. storage_provider_factory) {
  81. OSCryptImpl::GetInstance()->UseMockKeyStorageForTesting(
  82. std::move(storage_provider_factory));
  83. }
  84. void ClearCacheForTesting() {
  85. OSCryptImpl::GetInstance()->ClearCacheForTesting();
  86. }
  87. void SetEncryptionPasswordForTesting(const std::string& password) {
  88. OSCryptImpl::GetInstance()->SetEncryptionPasswordForTesting(password);
  89. }
  90. } // namespace OSCrypt
  91. OSCryptImpl* OSCryptImpl::GetInstance() {
  92. return base::Singleton<OSCryptImpl,
  93. base::LeakySingletonTraits<OSCryptImpl>>::get();
  94. }
  95. OSCryptImpl::OSCryptImpl()
  96. : storage_provider_factory_(base::BindOnce(&OSCryptImpl::CreateKeyStorage,
  97. base::Unretained(this))) {}
  98. OSCryptImpl::~OSCryptImpl() = default;
  99. bool OSCryptImpl::EncryptString16(const std::u16string& plaintext,
  100. std::string* ciphertext) {
  101. return EncryptString(base::UTF16ToUTF8(plaintext), ciphertext);
  102. }
  103. bool OSCryptImpl::DecryptString16(const std::string& ciphertext,
  104. std::u16string* plaintext) {
  105. std::string utf8;
  106. if (!DecryptString(ciphertext, &utf8))
  107. return false;
  108. *plaintext = base::UTF8ToUTF16(utf8);
  109. return true;
  110. }
  111. bool OSCryptImpl::EncryptString(const std::string& plaintext,
  112. std::string* ciphertext) {
  113. if (plaintext.empty()) {
  114. ciphertext->clear();
  115. return true;
  116. }
  117. // If we are able to create a V11 key (i.e. a KeyStorage was available), then
  118. // we'll use it. If not, we'll use V10.
  119. crypto::SymmetricKey* encryption_key = GetPasswordV11();
  120. std::string obfuscation_prefix = kObfuscationPrefixV11;
  121. if (!encryption_key) {
  122. encryption_key = GetPasswordV10();
  123. obfuscation_prefix = kObfuscationPrefixV10;
  124. }
  125. if (!encryption_key)
  126. return false;
  127. const std::string iv(kIVBlockSizeAES128, ' ');
  128. crypto::Encryptor encryptor;
  129. if (!encryptor.Init(encryption_key, crypto::Encryptor::CBC, iv))
  130. return false;
  131. if (!encryptor.Encrypt(plaintext, ciphertext))
  132. return false;
  133. // Prefix the cipher text with version information.
  134. ciphertext->insert(0, obfuscation_prefix);
  135. return true;
  136. }
  137. bool OSCryptImpl::DecryptString(const std::string& ciphertext,
  138. std::string* plaintext) {
  139. if (ciphertext.empty()) {
  140. plaintext->clear();
  141. return true;
  142. }
  143. // Check that the incoming ciphertext was encrypted and with what version.
  144. // Credit card numbers are current legacy unencrypted data, so false match
  145. // with prefix won't happen.
  146. crypto::SymmetricKey* encryption_key = nullptr;
  147. std::string obfuscation_prefix;
  148. if (base::StartsWith(ciphertext, kObfuscationPrefixV10,
  149. base::CompareCase::SENSITIVE)) {
  150. encryption_key = GetPasswordV10();
  151. obfuscation_prefix = kObfuscationPrefixV10;
  152. } else if (base::StartsWith(ciphertext, kObfuscationPrefixV11,
  153. base::CompareCase::SENSITIVE)) {
  154. encryption_key = GetPasswordV11();
  155. obfuscation_prefix = kObfuscationPrefixV11;
  156. } else {
  157. // If the prefix is not found then we'll assume we're dealing with
  158. // old data saved as clear text and we'll return it directly.
  159. *plaintext = ciphertext;
  160. return true;
  161. }
  162. if (!encryption_key) {
  163. VLOG(1) << "Decryption failed: could not get the key";
  164. return false;
  165. }
  166. const std::string iv(kIVBlockSizeAES128, ' ');
  167. crypto::Encryptor encryptor;
  168. if (!encryptor.Init(encryption_key, crypto::Encryptor::CBC, iv))
  169. return false;
  170. // Strip off the versioning prefix before decrypting.
  171. const std::string raw_ciphertext =
  172. ciphertext.substr(obfuscation_prefix.length());
  173. if (!encryptor.Decrypt(raw_ciphertext, plaintext)) {
  174. VLOG(1) << "Decryption failed";
  175. return false;
  176. }
  177. return true;
  178. }
  179. void OSCryptImpl::SetConfig(std::unique_ptr<os_crypt::Config> config) {
  180. // Setting initialisation parameters makes no sense after initializing.
  181. DCHECK(!is_password_v11_cached_);
  182. config_ = std::move(config);
  183. }
  184. bool OSCryptImpl::IsEncryptionAvailable() {
  185. return GetPasswordV11();
  186. }
  187. void OSCryptImpl::SetRawEncryptionKey(const std::string& raw_key) {
  188. base::AutoLock auto_lock(OSCryptImpl::GetLock());
  189. // Check if the v11 password is already cached. If it is, then data encrypted
  190. // with the old password might not be decryptable.
  191. DCHECK(!is_password_v11_cached_);
  192. // The config won't be used if this function is being called. Callers should
  193. // choose between setting a config and setting a raw encryption key.
  194. DCHECK(!config_);
  195. if (!raw_key.empty()) {
  196. password_v11_cache_ =
  197. crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, raw_key);
  198. }
  199. // Always set |is_password_v11_cached_|, even if given an empty string.
  200. // Note that |raw_key| can be an empty string if real V11 encryption is not
  201. // available, and setting |is_password_v11_cached_| causes GetPasswordV11() to
  202. // correctly return nullptr in that case.
  203. is_password_v11_cached_ = true;
  204. }
  205. std::string OSCryptImpl::GetRawEncryptionKey() {
  206. if (crypto::SymmetricKey* key = GetPasswordV11())
  207. return key->key();
  208. return std::string();
  209. }
  210. void OSCryptImpl::ClearCacheForTesting() {
  211. password_v10_cache_.reset();
  212. password_v11_cache_.reset();
  213. is_password_v11_cached_ = false;
  214. config_.reset();
  215. }
  216. void OSCryptImpl::UseMockKeyStorageForTesting(
  217. base::OnceCallback<std::unique_ptr<KeyStorageLinux>()>
  218. storage_provider_factory) {
  219. if (storage_provider_factory)
  220. storage_provider_factory_ = std::move(storage_provider_factory);
  221. else
  222. storage_provider_factory_ =
  223. base::BindOnce(&OSCryptImpl::CreateKeyStorage, base::Unretained(this));
  224. }
  225. // Create the KeyStorage. Will be null if no service is found. A Config must be
  226. // set before every call to this function.
  227. std::unique_ptr<KeyStorageLinux> OSCryptImpl::CreateKeyStorage() {
  228. CHECK(config_);
  229. std::unique_ptr<KeyStorageLinux> key_storage =
  230. KeyStorageLinux::CreateService(*config_);
  231. config_.reset();
  232. return key_storage;
  233. }
  234. void OSCryptImpl::SetEncryptionPasswordForTesting(const std::string& password) {
  235. ClearCacheForTesting(); // IN-TEST
  236. password_v11_cache_ = GenerateEncryptionKey(password);
  237. is_password_v11_cached_ = true;
  238. }
  239. // Returns a cached string of "peanuts". Is thread-safe.
  240. crypto::SymmetricKey* OSCryptImpl::GetPasswordV10() {
  241. base::AutoLock auto_lock(OSCryptImpl::GetLock());
  242. if (!password_v10_cache_.get()) {
  243. password_v10_cache_ = GenerateEncryptionKey("peanuts");
  244. }
  245. return password_v10_cache_.get();
  246. }
  247. // Caches and returns the password from the KeyStorage or null if there is no
  248. // service. Is thread-safe.
  249. crypto::SymmetricKey* OSCryptImpl::GetPasswordV11() {
  250. base::AutoLock auto_lock(OSCryptImpl::GetLock());
  251. if (!is_password_v11_cached_) {
  252. std::unique_ptr<KeyStorageLinux> key_storage =
  253. std::move(storage_provider_factory_).Run();
  254. if (key_storage) {
  255. absl::optional<std::string> key = key_storage->GetKey();
  256. if (key.has_value()) {
  257. password_v11_cache_ = GenerateEncryptionKey(*key);
  258. }
  259. }
  260. is_password_v11_cached_ = true;
  261. }
  262. return password_v11_cache_.get();
  263. }
  264. // static
  265. base::Lock& OSCryptImpl::GetLock() {
  266. static base::NoDestructor<base::Lock> os_crypt_lock;
  267. return *os_crypt_lock;
  268. }