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