os_crypt_win.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Copyright 2014 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 <windows.h>
  5. #include "base/base64.h"
  6. #include "base/logging.h"
  7. #include "base/memory/singleton.h"
  8. #include "base/metrics/histogram_functions.h"
  9. #include "base/metrics/histogram_macros.h"
  10. #include "base/strings/string_util.h"
  11. #include "base/strings/utf_string_conversions.h"
  12. #include "base/win/wincrypt_shim.h"
  13. #include "components/os_crypt/os_crypt.h"
  14. #include "components/prefs/pref_registry_simple.h"
  15. #include "components/prefs/pref_service.h"
  16. #include "crypto/aead.h"
  17. #include "crypto/hkdf.h"
  18. #include "crypto/random.h"
  19. namespace {
  20. // Contains base64 random key encrypted with DPAPI.
  21. constexpr char kOsCryptEncryptedKeyPrefName[] = "os_crypt.encrypted_key";
  22. // AEAD key length in bytes.
  23. constexpr size_t kKeyLength = 256 / 8;
  24. // AEAD nonce length in bytes.
  25. constexpr size_t kNonceLength = 96 / 8;
  26. // Version prefix for data encrypted with profile bound key.
  27. constexpr char kEncryptionVersionPrefix[] = "v10";
  28. // Key prefix for a key encrypted with DPAPI.
  29. constexpr char kDPAPIKeyPrefix[] = "DPAPI";
  30. bool EncryptStringWithDPAPI(const std::string& plaintext,
  31. std::string* ciphertext) {
  32. DATA_BLOB input;
  33. input.pbData =
  34. const_cast<BYTE*>(reinterpret_cast<const BYTE*>(plaintext.data()));
  35. input.cbData = static_cast<DWORD>(plaintext.length());
  36. BOOL result = FALSE;
  37. DATA_BLOB output;
  38. {
  39. SCOPED_UMA_HISTOGRAM_TIMER("OSCrypt.Win.Encrypt.Time");
  40. result =
  41. CryptProtectData(&input, L"", nullptr, nullptr, nullptr, 0, &output);
  42. }
  43. base::UmaHistogramBoolean("OSCrypt.Win.Encrypt.Result", result);
  44. if (!result) {
  45. PLOG(ERROR) << "Failed to encrypt";
  46. return false;
  47. }
  48. // this does a copy
  49. ciphertext->assign(reinterpret_cast<std::string::value_type*>(output.pbData),
  50. output.cbData);
  51. LocalFree(output.pbData);
  52. return true;
  53. }
  54. bool DecryptStringWithDPAPI(const std::string& ciphertext,
  55. std::string* plaintext) {
  56. DATA_BLOB input;
  57. input.pbData =
  58. const_cast<BYTE*>(reinterpret_cast<const BYTE*>(ciphertext.data()));
  59. input.cbData = static_cast<DWORD>(ciphertext.length());
  60. BOOL result = FALSE;
  61. DATA_BLOB output;
  62. {
  63. SCOPED_UMA_HISTOGRAM_TIMER("OSCrypt.Win.Decrypt.Time");
  64. result = CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr, 0,
  65. &output);
  66. }
  67. base::UmaHistogramBoolean("OSCrypt.Win.Decrypt.Result", result);
  68. if (!result) {
  69. PLOG(ERROR) << "Failed to decrypt";
  70. return false;
  71. }
  72. plaintext->assign(reinterpret_cast<char*>(output.pbData), output.cbData);
  73. LocalFree(output.pbData);
  74. return true;
  75. }
  76. } // namespace
  77. namespace OSCrypt {
  78. bool EncryptString16(const std::u16string& plaintext, std::string* ciphertext) {
  79. return OSCryptImpl::GetInstance()->EncryptString16(plaintext, ciphertext);
  80. }
  81. bool DecryptString16(const std::string& ciphertext, std::u16string* plaintext) {
  82. return OSCryptImpl::GetInstance()->DecryptString16(ciphertext, plaintext);
  83. }
  84. bool EncryptString(const std::string& plaintext, std::string* ciphertext) {
  85. return OSCryptImpl::GetInstance()->EncryptString(plaintext, ciphertext);
  86. }
  87. bool DecryptString(const std::string& ciphertext, std::string* plaintext) {
  88. return OSCryptImpl::GetInstance()->DecryptString(ciphertext, plaintext);
  89. }
  90. void RegisterLocalPrefs(PrefRegistrySimple* registry) {
  91. OSCryptImpl::RegisterLocalPrefs(registry);
  92. }
  93. InitResult InitWithExistingKey(PrefService* local_state) {
  94. return OSCryptImpl::GetInstance()->InitWithExistingKey(local_state);
  95. }
  96. bool Init(PrefService* local_state) {
  97. return OSCryptImpl::GetInstance()->Init(local_state);
  98. }
  99. std::string GetRawEncryptionKey() {
  100. return OSCryptImpl::GetInstance()->GetRawEncryptionKey();
  101. }
  102. void SetRawEncryptionKey(const std::string& key) {
  103. OSCryptImpl::GetInstance()->SetRawEncryptionKey(key);
  104. }
  105. bool IsEncryptionAvailable() {
  106. return OSCryptImpl::GetInstance()->IsEncryptionAvailable();
  107. }
  108. void UseMockKeyForTesting(bool use_mock) {
  109. OSCryptImpl::GetInstance()->UseMockKeyForTesting(use_mock);
  110. }
  111. void SetLegacyEncryptionForTesting(bool legacy) {
  112. OSCryptImpl::GetInstance()->SetLegacyEncryptionForTesting(legacy);
  113. }
  114. void ResetStateForTesting() {
  115. OSCryptImpl::GetInstance()->ResetStateForTesting();
  116. }
  117. } // namespace OSCrypt
  118. OSCryptImpl::OSCryptImpl() = default;
  119. OSCryptImpl::~OSCryptImpl() = default;
  120. OSCryptImpl* OSCryptImpl::GetInstance() {
  121. return base::Singleton<OSCryptImpl,
  122. base::LeakySingletonTraits<OSCryptImpl>>::get();
  123. }
  124. bool OSCryptImpl::EncryptString16(const std::u16string& plaintext,
  125. std::string* ciphertext) {
  126. return EncryptString(base::UTF16ToUTF8(plaintext), ciphertext);
  127. }
  128. bool OSCryptImpl::DecryptString16(const std::string& ciphertext,
  129. std::u16string* plaintext) {
  130. std::string utf8;
  131. if (!DecryptString(ciphertext, &utf8))
  132. return false;
  133. *plaintext = base::UTF8ToUTF16(utf8);
  134. return true;
  135. }
  136. bool OSCryptImpl::EncryptString(const std::string& plaintext,
  137. std::string* ciphertext) {
  138. if (use_legacy_)
  139. return EncryptStringWithDPAPI(plaintext, ciphertext);
  140. crypto::Aead aead(crypto::Aead::AES_256_GCM);
  141. const auto key = GetRawEncryptionKey();
  142. aead.Init(&key);
  143. // Note: can only check these once AEAD is initialized.
  144. DCHECK_EQ(kKeyLength, aead.KeyLength());
  145. DCHECK_EQ(kNonceLength, aead.NonceLength());
  146. std::string nonce;
  147. crypto::RandBytes(base::WriteInto(&nonce, kNonceLength + 1), kNonceLength);
  148. if (!aead.Seal(plaintext, nonce, std::string(), ciphertext))
  149. return false;
  150. ciphertext->insert(0, nonce);
  151. ciphertext->insert(0, kEncryptionVersionPrefix);
  152. return true;
  153. }
  154. bool OSCryptImpl::DecryptString(const std::string& ciphertext,
  155. std::string* plaintext) {
  156. if (!base::StartsWith(ciphertext, kEncryptionVersionPrefix,
  157. base::CompareCase::SENSITIVE))
  158. return DecryptStringWithDPAPI(ciphertext, plaintext);
  159. crypto::Aead aead(crypto::Aead::AES_256_GCM);
  160. const auto key = GetRawEncryptionKey();
  161. aead.Init(&key);
  162. // Obtain the nonce.
  163. const std::string nonce =
  164. ciphertext.substr(sizeof(kEncryptionVersionPrefix) - 1, kNonceLength);
  165. // Strip off the versioning prefix before decrypting.
  166. const std::string raw_ciphertext =
  167. ciphertext.substr(kNonceLength + (sizeof(kEncryptionVersionPrefix) - 1));
  168. return aead.Open(raw_ciphertext, nonce, std::string(), plaintext);
  169. }
  170. // static
  171. void OSCryptImpl::RegisterLocalPrefs(PrefRegistrySimple* registry) {
  172. registry->RegisterStringPref(kOsCryptEncryptedKeyPrefName, "");
  173. }
  174. bool OSCryptImpl::Init(PrefService* local_state) {
  175. // Try to pull the key from the local state.
  176. switch (InitWithExistingKey(local_state)) {
  177. case OSCrypt::kSuccess:
  178. return true;
  179. case OSCrypt::kKeyDoesNotExist:
  180. break;
  181. case OSCrypt::kInvalidKeyFormat:
  182. return false;
  183. case OSCrypt::kDecryptionFailed:
  184. break;
  185. }
  186. // If there is no key in the local state, or if DPAPI decryption fails,
  187. // generate a new key.
  188. std::string key;
  189. crypto::RandBytes(base::WriteInto(&key, kKeyLength + 1), kKeyLength);
  190. std::string encrypted_key;
  191. if (!EncryptStringWithDPAPI(key, &encrypted_key))
  192. return false;
  193. // Add header indicating this key is encrypted with DPAPI.
  194. encrypted_key.insert(0, kDPAPIKeyPrefix);
  195. std::string base64_key;
  196. base::Base64Encode(encrypted_key, &base64_key);
  197. local_state->SetString(kOsCryptEncryptedKeyPrefName, base64_key);
  198. encryption_key_.assign(key);
  199. return true;
  200. }
  201. OSCrypt::InitResult OSCryptImpl::InitWithExistingKey(PrefService* local_state) {
  202. DCHECK(encryption_key_.empty()) << "Key already exists.";
  203. // Try and pull the key from the local state.
  204. if (!local_state->HasPrefPath(kOsCryptEncryptedKeyPrefName))
  205. return OSCrypt::kKeyDoesNotExist;
  206. const std::string base64_encrypted_key =
  207. local_state->GetString(kOsCryptEncryptedKeyPrefName);
  208. std::string encrypted_key_with_header;
  209. base::Base64Decode(base64_encrypted_key, &encrypted_key_with_header);
  210. if (!base::StartsWith(encrypted_key_with_header, kDPAPIKeyPrefix,
  211. base::CompareCase::SENSITIVE)) {
  212. NOTREACHED() << "Invalid key format.";
  213. return OSCrypt::kInvalidKeyFormat;
  214. }
  215. const std::string encrypted_key =
  216. encrypted_key_with_header.substr(sizeof(kDPAPIKeyPrefix) - 1);
  217. std::string key;
  218. // This DPAPI decryption can fail if the user's password has been reset
  219. // by an Administrator.
  220. if (!DecryptStringWithDPAPI(encrypted_key, &key)) {
  221. base::UmaHistogramSparse("OSCrypt.Win.KeyDecryptionError",
  222. ::GetLastError());
  223. return OSCrypt::kDecryptionFailed;
  224. }
  225. encryption_key_.assign(key);
  226. return OSCrypt::kSuccess;
  227. }
  228. void OSCryptImpl::SetRawEncryptionKey(const std::string& raw_key) {
  229. DCHECK(!use_mock_key_) << "Mock key in use.";
  230. DCHECK(!raw_key.empty()) << "Bad key.";
  231. DCHECK(encryption_key_.empty()) << "Key already set.";
  232. encryption_key_.assign(raw_key);
  233. }
  234. std::string OSCryptImpl::GetRawEncryptionKey() {
  235. if (use_mock_key_) {
  236. if (mock_encryption_key_.empty())
  237. mock_encryption_key_.assign(
  238. crypto::HkdfSha256("peanuts", "salt", "info", kKeyLength));
  239. DCHECK(!mock_encryption_key_.empty()) << "Failed to initialize mock key.";
  240. return mock_encryption_key_;
  241. }
  242. DCHECK(!encryption_key_.empty()) << "No key.";
  243. return encryption_key_;
  244. }
  245. bool OSCryptImpl::IsEncryptionAvailable() {
  246. return !encryption_key_.empty();
  247. }
  248. void OSCryptImpl::UseMockKeyForTesting(bool use_mock) {
  249. use_mock_key_ = use_mock;
  250. }
  251. void OSCryptImpl::SetLegacyEncryptionForTesting(bool legacy) {
  252. use_legacy_ = legacy;
  253. }
  254. void OSCryptImpl::ResetStateForTesting() {
  255. use_legacy_ = false;
  256. use_mock_key_ = false;
  257. encryption_key_.clear();
  258. mock_encryption_key_.clear();
  259. }