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