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