KeyStorage.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /*
  2. * Copyright (C) 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "KeyStorage.h"
  17. #include "Keymaster.h"
  18. #include "ScryptParameters.h"
  19. #include "Utils.h"
  20. #include "Checkpoint.h"
  21. #include <thread>
  22. #include <vector>
  23. #include <errno.h>
  24. #include <stdio.h>
  25. #include <sys/stat.h>
  26. #include <sys/types.h>
  27. #include <sys/wait.h>
  28. #include <unistd.h>
  29. #include <openssl/err.h>
  30. #include <openssl/evp.h>
  31. #include <openssl/sha.h>
  32. #include <android-base/file.h>
  33. #include <android-base/logging.h>
  34. #include <android-base/unique_fd.h>
  35. #include <android-base/properties.h>
  36. #include <cutils/properties.h>
  37. #include <hardware/hw_auth_token.h>
  38. #include <keymasterV4_0/authorization_set.h>
  39. #include <keymasterV4_0/keymaster_utils.h>
  40. extern "C" {
  41. #include "crypto_scrypt.h"
  42. }
  43. namespace android {
  44. namespace vold {
  45. const KeyAuthentication kEmptyAuthentication{"", ""};
  46. static constexpr size_t AES_KEY_BYTES = 32;
  47. static constexpr size_t GCM_NONCE_BYTES = 12;
  48. static constexpr size_t GCM_MAC_BYTES = 16;
  49. static constexpr size_t SALT_BYTES = 1 << 4;
  50. static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
  51. static constexpr size_t STRETCHED_BYTES = 1 << 6;
  52. static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
  53. static const char* kCurrentVersion = "1";
  54. static const char* kRmPath = "/system/bin/rm";
  55. static const char* kSecdiscardPath = "/system/bin/secdiscard";
  56. static const char* kStretch_none = "none";
  57. static const char* kStretch_nopassword = "nopassword";
  58. static const std::string kStretchPrefix_scrypt = "scrypt ";
  59. static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
  60. static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
  61. static const char* kFn_encrypted_key = "encrypted_key";
  62. static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
  63. static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
  64. static const char* kFn_salt = "salt";
  65. static const char* kFn_secdiscardable = "secdiscardable";
  66. static const char* kFn_stretching = "stretching";
  67. static const char* kFn_version = "version";
  68. static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
  69. if (actual != expected) {
  70. LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
  71. << actual;
  72. return false;
  73. }
  74. return true;
  75. }
  76. static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
  77. SHA512_CTX c;
  78. SHA512_Init(&c);
  79. // Personalise the hashing by introducing a fixed prefix.
  80. // Hashing applications should use personalization except when there is a
  81. // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
  82. std::string hashingPrefix = prefix;
  83. hashingPrefix.resize(SHA512_CBLOCK);
  84. SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
  85. SHA512_Update(&c, tohash.data(), tohash.size());
  86. res->assign(SHA512_DIGEST_LENGTH, '\0');
  87. SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
  88. }
  89. static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
  90. const std::string& appId, std::string* key) {
  91. auto paramBuilder = km::AuthorizationSetBuilder()
  92. .AesEncryptionKey(AES_KEY_BYTES * 8)
  93. .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
  94. .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
  95. if (auth.token.empty()) {
  96. LOG(DEBUG) << "Creating key that doesn't need auth token";
  97. paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
  98. } else {
  99. LOG(DEBUG) << "Auth token required for key";
  100. if (auth.token.size() != sizeof(hw_auth_token_t)) {
  101. LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
  102. << auth.token.size() << " bytes";
  103. return false;
  104. }
  105. const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
  106. paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
  107. paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
  108. paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
  109. }
  110. return keymaster.generateKey(paramBuilder, key);
  111. }
  112. static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
  113. const KeyAuthentication& auth, const std::string& appId) {
  114. auto paramBuilder = km::AuthorizationSetBuilder()
  115. .GcmModeMacLen(GCM_MAC_BYTES * 8)
  116. .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
  117. km::HardwareAuthToken authToken;
  118. if (!auth.token.empty()) {
  119. LOG(DEBUG) << "Supplying auth token to Keymaster";
  120. authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
  121. }
  122. return {paramBuilder, authToken};
  123. }
  124. static bool readFileToString(const std::string& filename, std::string* result) {
  125. if (!android::base::ReadFileToString(filename, result)) {
  126. PLOG(ERROR) << "Failed to read from " << filename;
  127. return false;
  128. }
  129. return true;
  130. }
  131. static bool readRandomBytesOrLog(size_t count, std::string* out) {
  132. auto status = ReadRandomBytes(count, *out);
  133. if (status != OK) {
  134. LOG(ERROR) << "Random read failed with status: " << status;
  135. return false;
  136. }
  137. return true;
  138. }
  139. bool createSecdiscardable(const std::string& filename, std::string* hash) {
  140. std::string secdiscardable;
  141. if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
  142. if (!writeStringToFile(secdiscardable, filename)) return false;
  143. hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
  144. return true;
  145. }
  146. bool readSecdiscardable(const std::string& filename, std::string* hash) {
  147. std::string secdiscardable;
  148. if (!readFileToString(filename, &secdiscardable)) return false;
  149. hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
  150. return true;
  151. }
  152. static void deferedKmDeleteKey(const std::string& kmkey) {
  153. while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
  154. LOG(ERROR) << "Wait for boot timed out";
  155. }
  156. Keymaster keymaster;
  157. if (!keymaster || !keymaster.deleteKey(kmkey)) {
  158. LOG(ERROR) << "Defered Key deletion failed during upgrade";
  159. }
  160. }
  161. bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
  162. bool needs_cp = cp_needsCheckpoint();
  163. if (needs_cp) {
  164. std::thread(deferedKmDeleteKey, kmKey).detach();
  165. LOG(INFO) << "Deferring Key deletion during upgrade";
  166. return true;
  167. } else {
  168. return keymaster.deleteKey(kmKey);
  169. }
  170. }
  171. static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
  172. km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
  173. const km::AuthorizationSet& opParams,
  174. const km::HardwareAuthToken& authToken,
  175. km::AuthorizationSet* outParams, bool keepOld) {
  176. auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
  177. std::string kmKey;
  178. if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
  179. km::AuthorizationSet inParams(keyParams);
  180. inParams.append(opParams.begin(), opParams.end());
  181. for (;;) {
  182. auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
  183. if (opHandle) {
  184. return opHandle;
  185. }
  186. if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
  187. LOG(DEBUG) << "Upgrading key: " << dir;
  188. std::string newKey;
  189. if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
  190. auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
  191. if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
  192. if (!keepOld) {
  193. if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
  194. PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
  195. return KeymasterOperation();
  196. }
  197. if (!android::vold::FsyncDirectory(dir)) {
  198. LOG(ERROR) << "Key dir sync failed: " << dir;
  199. return KeymasterOperation();
  200. }
  201. if (!kmDeleteKey(keymaster, kmKey)) {
  202. LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
  203. }
  204. }
  205. kmKey = newKey;
  206. LOG(INFO) << "Key upgraded: " << dir;
  207. }
  208. }
  209. static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
  210. const km::AuthorizationSet& keyParams,
  211. const km::HardwareAuthToken& authToken, const KeyBuffer& message,
  212. std::string* ciphertext, bool keepOld) {
  213. km::AuthorizationSet opParams;
  214. km::AuthorizationSet outParams;
  215. auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
  216. &outParams, keepOld);
  217. if (!opHandle) return false;
  218. auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
  219. if (!nonceBlob.isOk()) {
  220. LOG(ERROR) << "GCM encryption but no nonce generated";
  221. return false;
  222. }
  223. // nonceBlob here is just a pointer into existing data, must not be freed
  224. std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
  225. nonceBlob.value().size());
  226. if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
  227. std::string body;
  228. if (!opHandle.updateCompletely(message, &body)) return false;
  229. std::string mac;
  230. if (!opHandle.finish(&mac)) return false;
  231. if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
  232. *ciphertext = nonce + body + mac;
  233. return true;
  234. }
  235. static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
  236. const km::AuthorizationSet& keyParams,
  237. const km::HardwareAuthToken& authToken,
  238. const std::string& ciphertext, KeyBuffer* message,
  239. bool keepOld) {
  240. auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
  241. auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
  242. auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
  243. km::support::blob2hidlVec(nonce));
  244. auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
  245. nullptr, keepOld);
  246. if (!opHandle) return false;
  247. if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
  248. if (!opHandle.finish(nullptr)) return false;
  249. return true;
  250. }
  251. static std::string getStretching(const KeyAuthentication& auth) {
  252. if (!auth.usesKeymaster()) {
  253. return kStretch_none;
  254. } else if (auth.secret.empty()) {
  255. return kStretch_nopassword;
  256. } else {
  257. char paramstr[PROPERTY_VALUE_MAX];
  258. property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
  259. return std::string() + kStretchPrefix_scrypt + paramstr;
  260. }
  261. }
  262. static bool stretchingNeedsSalt(const std::string& stretching) {
  263. return stretching != kStretch_nopassword && stretching != kStretch_none;
  264. }
  265. static bool stretchSecret(const std::string& stretching, const std::string& secret,
  266. const std::string& salt, std::string* stretched) {
  267. if (stretching == kStretch_nopassword) {
  268. if (!secret.empty()) {
  269. LOG(WARNING) << "Password present but stretching is nopassword";
  270. // Continue anyway
  271. }
  272. stretched->clear();
  273. } else if (stretching == kStretch_none) {
  274. *stretched = secret;
  275. } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
  276. stretching.begin())) {
  277. int Nf, rf, pf;
  278. if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
  279. &rf, &pf)) {
  280. LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
  281. return false;
  282. }
  283. stretched->assign(STRETCHED_BYTES, '\0');
  284. if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
  285. reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
  286. 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
  287. stretched->size()) != 0) {
  288. LOG(ERROR) << "scrypt failed with params: " << stretching;
  289. return false;
  290. }
  291. } else {
  292. LOG(ERROR) << "Unknown stretching type: " << stretching;
  293. return false;
  294. }
  295. return true;
  296. }
  297. static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
  298. const std::string& salt, const std::string& secdiscardable_hash,
  299. std::string* appId) {
  300. std::string stretched;
  301. if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
  302. *appId = secdiscardable_hash + stretched;
  303. return true;
  304. }
  305. static void logOpensslError() {
  306. LOG(ERROR) << "Openssl error: " << ERR_get_error();
  307. }
  308. static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
  309. std::string* ciphertext) {
  310. std::string key;
  311. hashWithPrefix(kHashPrefix_keygen, preKey, &key);
  312. key.resize(AES_KEY_BYTES);
  313. if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
  314. auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
  315. EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
  316. if (!ctx) {
  317. logOpensslError();
  318. return false;
  319. }
  320. if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
  321. reinterpret_cast<const uint8_t*>(key.data()),
  322. reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
  323. logOpensslError();
  324. return false;
  325. }
  326. ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
  327. int outlen;
  328. if (1 != EVP_EncryptUpdate(
  329. ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
  330. &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
  331. logOpensslError();
  332. return false;
  333. }
  334. if (outlen != static_cast<int>(plaintext.size())) {
  335. LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
  336. return false;
  337. }
  338. if (1 != EVP_EncryptFinal_ex(
  339. ctx.get(),
  340. reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
  341. &outlen)) {
  342. logOpensslError();
  343. return false;
  344. }
  345. if (outlen != 0) {
  346. LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
  347. return false;
  348. }
  349. if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
  350. reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
  351. plaintext.size()))) {
  352. logOpensslError();
  353. return false;
  354. }
  355. return true;
  356. }
  357. static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
  358. KeyBuffer* plaintext) {
  359. if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
  360. LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
  361. return false;
  362. }
  363. std::string key;
  364. hashWithPrefix(kHashPrefix_keygen, preKey, &key);
  365. key.resize(AES_KEY_BYTES);
  366. auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
  367. EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
  368. if (!ctx) {
  369. logOpensslError();
  370. return false;
  371. }
  372. if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
  373. reinterpret_cast<const uint8_t*>(key.data()),
  374. reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
  375. logOpensslError();
  376. return false;
  377. }
  378. *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
  379. int outlen;
  380. if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
  381. reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
  382. plaintext->size())) {
  383. logOpensslError();
  384. return false;
  385. }
  386. if (outlen != static_cast<int>(plaintext->size())) {
  387. LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
  388. return false;
  389. }
  390. if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
  391. const_cast<void*>(reinterpret_cast<const void*>(
  392. ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
  393. logOpensslError();
  394. return false;
  395. }
  396. if (1 != EVP_DecryptFinal_ex(ctx.get(),
  397. reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
  398. &outlen)) {
  399. logOpensslError();
  400. return false;
  401. }
  402. if (outlen != 0) {
  403. LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
  404. return false;
  405. }
  406. return true;
  407. }
  408. bool pathExists(const std::string& path) {
  409. return access(path.c_str(), F_OK) == 0;
  410. }
  411. bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
  412. if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
  413. PLOG(ERROR) << "key mkdir " << dir;
  414. return false;
  415. }
  416. if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
  417. std::string secdiscardable_hash;
  418. if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
  419. std::string stretching = getStretching(auth);
  420. if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
  421. std::string salt;
  422. if (stretchingNeedsSalt(stretching)) {
  423. if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
  424. LOG(ERROR) << "Random read failed";
  425. return false;
  426. }
  427. if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
  428. }
  429. std::string appId;
  430. if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
  431. std::string encryptedKey;
  432. if (auth.usesKeymaster()) {
  433. Keymaster keymaster;
  434. if (!keymaster) return false;
  435. std::string kmKey;
  436. if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
  437. if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
  438. km::AuthorizationSet keyParams;
  439. km::HardwareAuthToken authToken;
  440. std::tie(keyParams, authToken) = beginParams(auth, appId);
  441. if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
  442. false))
  443. return false;
  444. } else {
  445. if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
  446. }
  447. if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
  448. if (!FsyncDirectory(dir)) return false;
  449. return true;
  450. }
  451. bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
  452. const KeyAuthentication& auth, const KeyBuffer& key) {
  453. if (pathExists(key_path)) {
  454. LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
  455. return false;
  456. }
  457. if (pathExists(tmp_path)) {
  458. LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
  459. destroyKey(tmp_path); // May be partially created so ignore errors
  460. }
  461. if (!storeKey(tmp_path, auth, key)) return false;
  462. if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
  463. PLOG(ERROR) << "Unable to move new key to location: " << key_path;
  464. return false;
  465. }
  466. LOG(DEBUG) << "Created key: " << key_path;
  467. return true;
  468. }
  469. bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
  470. bool keepOld) {
  471. std::string version;
  472. if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
  473. if (version != kCurrentVersion) {
  474. LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
  475. return false;
  476. }
  477. std::string secdiscardable_hash;
  478. if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
  479. std::string stretching;
  480. if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
  481. std::string salt;
  482. if (stretchingNeedsSalt(stretching)) {
  483. if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
  484. }
  485. std::string appId;
  486. if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
  487. std::string encryptedMessage;
  488. if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
  489. if (auth.usesKeymaster()) {
  490. Keymaster keymaster;
  491. if (!keymaster) return false;
  492. km::AuthorizationSet keyParams;
  493. km::HardwareAuthToken authToken;
  494. std::tie(keyParams, authToken) = beginParams(auth, appId);
  495. if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
  496. keepOld))
  497. return false;
  498. } else {
  499. if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
  500. }
  501. return true;
  502. }
  503. static bool deleteKey(const std::string& dir) {
  504. std::string kmKey;
  505. if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
  506. Keymaster keymaster;
  507. if (!keymaster) return false;
  508. if (!keymaster.deleteKey(kmKey)) return false;
  509. return true;
  510. }
  511. bool runSecdiscardSingle(const std::string& file) {
  512. if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
  513. LOG(ERROR) << "secdiscard failed";
  514. return false;
  515. }
  516. return true;
  517. }
  518. static bool recursiveDeleteKey(const std::string& dir) {
  519. if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
  520. LOG(ERROR) << "recursive delete failed";
  521. return false;
  522. }
  523. return true;
  524. }
  525. bool destroyKey(const std::string& dir) {
  526. bool success = true;
  527. // Try each thing, even if previous things failed.
  528. bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
  529. if (uses_km) {
  530. success &= deleteKey(dir);
  531. }
  532. auto secdiscard_cmd = std::vector<std::string>{
  533. kSecdiscardPath,
  534. "--",
  535. dir + "/" + kFn_encrypted_key,
  536. dir + "/" + kFn_secdiscardable,
  537. };
  538. if (uses_km) {
  539. secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
  540. }
  541. if (ForkExecvp(secdiscard_cmd) != 0) {
  542. LOG(ERROR) << "secdiscard failed";
  543. success = false;
  544. }
  545. success &= recursiveDeleteKey(dir);
  546. return success;
  547. }
  548. } // namespace vold
  549. } // namespace android