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