• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "Keystore.h"
21 #include "Utils.h"
22 
23 #include <algorithm>
24 #include <memory>
25 #include <mutex>
26 #include <thread>
27 #include <vector>
28 
29 #include <errno.h>
30 #include <stdio.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <unistd.h>
35 
36 #include <openssl/err.h>
37 #include <openssl/evp.h>
38 #include <openssl/sha.h>
39 
40 #include <android-base/file.h>
41 #include <android-base/logging.h>
42 #include <android-base/properties.h>
43 #include <android-base/unique_fd.h>
44 
45 #include <cutils/properties.h>
46 
47 namespace android {
48 namespace vold {
49 
50 const KeyAuthentication kEmptyAuthentication{""};
51 
52 static constexpr size_t AES_KEY_BYTES = 32;
53 static constexpr size_t GCM_NONCE_BYTES = 12;
54 static constexpr size_t GCM_MAC_BYTES = 16;
55 static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
56 
57 static const char* kCurrentVersion = "1";
58 static const char* kRmPath = "/system/bin/rm";
59 static const char* kSecdiscardPath = "/system/bin/secdiscard";
60 static const char* kStretch_none = "none";
61 static const char* kStretch_nopassword = "nopassword";
62 static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
63 static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
64 static const char* kFn_encrypted_key = "encrypted_key";
65 static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
66 static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
67 static const char* kFn_secdiscardable = "secdiscardable";
68 static const char* kFn_stretching = "stretching";
69 static const char* kFn_version = "version";
70 
71 namespace {
72 
73 // Storage binding info for ensuring key encryption keys include a
74 // platform-provided seed in their derivation.
75 struct StorageBindingInfo {
76     enum class State {
77         UNINITIALIZED,
78         IN_USE,    // key storage keys are bound to seed
79         NOT_USED,  // key storage keys are NOT bound to seed
80     };
81 
82     // Binding seed mixed into all key storage keys.
83     std::vector<uint8_t> seed;
84 
85     // State tracker for the key storage key binding.
86     State state = State::UNINITIALIZED;
87 
88     std::mutex guard;
89 };
90 
91 // Never freed as the dtor is non-trivial.
92 StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
93 
94 }  // namespace
95 
checkSize(const std::string & kind,size_t actual,size_t expected)96 static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
97     if (actual != expected) {
98         LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
99                    << actual;
100         return false;
101     }
102     return true;
103 }
104 
hashWithPrefix(char const * prefix,const std::string & tohash,std::string * res)105 static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
106     SHA512_CTX c;
107 
108     SHA512_Init(&c);
109     // Personalise the hashing by introducing a fixed prefix.
110     // Hashing applications should use personalization except when there is a
111     // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
112     std::string hashingPrefix = prefix;
113     hashingPrefix.resize(SHA512_CBLOCK);
114     SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
115     SHA512_Update(&c, tohash.data(), tohash.size());
116     res->assign(SHA512_DIGEST_LENGTH, '\0');
117     SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
118 }
119 
generateKeyStorageKey(Keystore & keystore,const std::string & appId,std::string * key)120 static bool generateKeyStorageKey(Keystore& keystore, const std::string& appId, std::string* key) {
121     auto paramBuilder = km::AuthorizationSetBuilder()
122                                 .AesEncryptionKey(AES_KEY_BYTES * 8)
123                                 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
124                                 .Authorization(km::TAG_APPLICATION_ID, appId)
125                                 .Authorization(km::TAG_NO_AUTH_REQUIRED);
126     LOG(DEBUG) << "Generating \"key storage\" key";
127     auto paramsWithRollback = paramBuilder;
128     paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
129 
130     if (!keystore.generateKey(paramsWithRollback, key)) {
131         LOG(WARNING) << "Failed to generate rollback-resistant key.  This is expected if keystore "
132                         "doesn't support rollback resistance.  Falling back to "
133                         "non-rollback-resistant key.";
134         if (!keystore.generateKey(paramBuilder, key)) return false;
135     }
136     return true;
137 }
138 
generateWrappedStorageKey(KeyBuffer * key)139 bool generateWrappedStorageKey(KeyBuffer* key) {
140     Keystore keystore;
141     if (!keystore) return false;
142     std::string key_temp;
143     auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
144     paramBuilder.Authorization(km::TAG_STORAGE_KEY);
145     if (!keystore.generateKey(paramBuilder, &key_temp)) return false;
146     *key = KeyBuffer(key_temp.size());
147     memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
148     return true;
149 }
150 
exportWrappedStorageKey(const KeyBuffer & ksKey,KeyBuffer * key)151 bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
152     Keystore keystore;
153     if (!keystore) return false;
154     std::string key_temp;
155 
156     if (!keystore.exportKey(ksKey, &key_temp)) return false;
157     *key = KeyBuffer(key_temp.size());
158     memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
159     return true;
160 }
161 
beginParams(const std::string & appId)162 static km::AuthorizationSet beginParams(const std::string& appId) {
163     return km::AuthorizationSetBuilder()
164             .GcmModeMacLen(GCM_MAC_BYTES * 8)
165             .Authorization(km::TAG_APPLICATION_ID, appId);
166 }
167 
readFileToString(const std::string & filename,std::string * result)168 static bool readFileToString(const std::string& filename, std::string* result) {
169     if (!android::base::ReadFileToString(filename, result)) {
170         PLOG(ERROR) << "Failed to read from " << filename;
171         return false;
172     }
173     return true;
174 }
175 
readRandomBytesOrLog(size_t count,std::string * out)176 static bool readRandomBytesOrLog(size_t count, std::string* out) {
177     auto status = ReadRandomBytes(count, *out);
178     if (status != OK) {
179         LOG(ERROR) << "Random read failed with status: " << status;
180         return false;
181     }
182     return true;
183 }
184 
createSecdiscardable(const std::string & filename,std::string * hash)185 bool createSecdiscardable(const std::string& filename, std::string* hash) {
186     std::string secdiscardable;
187     if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
188     if (!writeStringToFile(secdiscardable, filename)) return false;
189     hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
190     return true;
191 }
192 
readSecdiscardable(const std::string & filename,std::string * hash)193 bool readSecdiscardable(const std::string& filename, std::string* hash) {
194     std::string secdiscardable;
195     if (!readFileToString(filename, &secdiscardable)) return false;
196     hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
197     return true;
198 }
199 
200 static std::mutex key_upgrade_lock;
201 
202 // List of key directories that have had their Keystore key upgraded during
203 // this boot and written to "keymaster_key_blob_upgraded", but replacing the old
204 // key was delayed due to an active checkpoint.  Protected by key_upgrade_lock.
205 // A directory can be in this list at most once.
206 static std::vector<std::string> key_dirs_to_commit;
207 
208 // Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
209 // deletes the old key from Keystore.
CommitUpgradedKey(Keystore & keystore,const std::string & dir)210 static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
211     auto blob_file = dir + "/" + kFn_keymaster_key_blob;
212     auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
213 
214     std::string blob;
215     if (!readFileToString(blob_file, &blob)) return false;
216 
217     if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
218         PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
219         return false;
220     }
221     // Ensure that the rename is persisted before deleting the Keystore key.
222     if (!FsyncDirectory(dir)) return false;
223 
224     if (!keystore || !keystore.deleteKey(blob)) {
225         LOG(WARNING) << "Failed to delete old key " << blob_file
226                      << " from Keystore; continuing anyway";
227         // Continue on, but the space in Keystore used by the old key won't be freed.
228     }
229     return true;
230 }
231 
DeferredCommitKeys()232 static void DeferredCommitKeys() {
233     android::base::WaitForProperty("vold.checkpoint_committed", "1");
234     LOG(INFO) << "Committing upgraded keys";
235     Keystore keystore;
236     if (!keystore) {
237         LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
238         // Continue on, but the space in Keystore used by the old keys won't be freed.
239     }
240     std::lock_guard<std::mutex> lock(key_upgrade_lock);
241     for (auto& dir : key_dirs_to_commit) {
242         LOG(INFO) << "Committing upgraded key " << dir;
243         CommitUpgradedKey(keystore, dir);
244     }
245     key_dirs_to_commit.clear();
246 }
247 
248 // Returns true if the Keystore key in |dir| has already been upgraded and is
249 // pending being committed.  Assumes that key_upgrade_lock is held.
IsKeyCommitPending(const std::string & dir)250 static bool IsKeyCommitPending(const std::string& dir) {
251     for (const auto& dir_to_commit : key_dirs_to_commit) {
252         if (IsSameFile(dir, dir_to_commit)) return true;
253     }
254     return false;
255 }
256 
257 // Schedules the upgraded Keystore key in |dir| to be committed later.  Assumes
258 // that key_upgrade_lock is held and that a commit isn't already pending for the
259 // directory.
ScheduleKeyCommit(const std::string & dir)260 static void ScheduleKeyCommit(const std::string& dir) {
261     if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
262     key_dirs_to_commit.push_back(dir);
263 }
264 
CancelPendingKeyCommit(const std::string & dir)265 static void CancelPendingKeyCommit(const std::string& dir) {
266     std::lock_guard<std::mutex> lock(key_upgrade_lock);
267     for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
268         if (IsSameFile(*it, dir)) {
269             LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
270                        << " because it is being destroyed";
271             key_dirs_to_commit.erase(it);
272             break;
273         }
274     }
275 }
276 
RenameKeyDir(const std::string & old_name,const std::string & new_name)277 bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
278     std::lock_guard<std::mutex> lock(key_upgrade_lock);
279 
280     // Find the entry in key_dirs_to_commit (if any) for this directory so that
281     // we can update it if the rename succeeds.  We don't allow duplicates in
282     // this list, so there can be at most one such entry.
283     auto it = key_dirs_to_commit.begin();
284     for (; it != key_dirs_to_commit.end(); it++) {
285         if (IsSameFile(old_name, *it)) break;
286     }
287 
288     if (rename(old_name.c_str(), new_name.c_str()) != 0) {
289         PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
290                     << "\"";
291         return false;
292     }
293 
294     if (it != key_dirs_to_commit.end()) *it = new_name;
295 
296     return true;
297 }
298 
299 // Deletes a leftover upgraded key, if present.  An upgraded key can be left
300 // over if an update failed, or if we rebooted before committing the key in a
301 // freak accident.  Either way, we can re-upgrade the key if we need to.
DeleteUpgradedKey(Keystore & keystore,const std::string & path)302 static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
303     if (pathExists(path)) {
304         LOG(DEBUG) << "Deleting leftover upgraded key " << path;
305         std::string blob;
306         if (!android::base::ReadFileToString(path, &blob)) {
307             LOG(WARNING) << "Failed to read leftover upgraded key " << path
308                          << "; continuing anyway";
309         } else if (!keystore.deleteKey(blob)) {
310             LOG(WARNING) << "Failed to delete leftover upgraded key " << path
311                          << " from Keystore; continuing anyway";
312         }
313         if (unlink(path.c_str()) != 0) {
314             LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
315                          << "; continuing anyway";
316         }
317     }
318 }
319 
320 // Begins a Keystore operation using the key stored in |dir|.
BeginKeystoreOp(Keystore & keystore,const std::string & dir,const km::AuthorizationSet & keyParams,const km::AuthorizationSet & opParams,km::AuthorizationSet * outParams)321 static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
322                                          const km::AuthorizationSet& keyParams,
323                                          const km::AuthorizationSet& opParams,
324                                          km::AuthorizationSet* outParams) {
325     km::AuthorizationSet inParams(keyParams);
326     inParams.append(opParams.begin(), opParams.end());
327 
328     auto blob_file = dir + "/" + kFn_keymaster_key_blob;
329     auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
330 
331     std::lock_guard<std::mutex> lock(key_upgrade_lock);
332 
333     std::string blob;
334     bool already_upgraded = IsKeyCommitPending(dir);
335     if (already_upgraded) {
336         LOG(DEBUG)
337                 << blob_file
338                 << " was already upgraded and is waiting to be committed; using the upgraded blob";
339         if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
340     } else {
341         DeleteUpgradedKey(keystore, upgraded_blob_file);
342         if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
343     }
344 
345     auto opHandle = keystore.begin(blob, inParams, outParams);
346     if (!opHandle) return opHandle;
347 
348     // If key blob wasn't upgraded, nothing left to do.
349     if (!opHandle.getUpgradedBlob()) return opHandle;
350 
351     if (already_upgraded) {
352         LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
353                    << " still requires upgrade";
354         return KeystoreOperation();
355     }
356     LOG(INFO) << "Upgrading key: " << blob_file;
357     if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
358         return KeystoreOperation();
359     if (cp_needsCheckpoint()) {
360         LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
361                   << "; delaying commit due to checkpoint";
362         ScheduleKeyCommit(dir);
363     } else {
364         if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
365         LOG(INFO) << "Key upgraded: " << blob_file;
366     }
367     return opHandle;
368 }
369 
encryptWithKeystoreKey(Keystore & keystore,const std::string & dir,const km::AuthorizationSet & keyParams,const KeyBuffer & message,std::string * ciphertext)370 static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
371                                    const km::AuthorizationSet& keyParams, const KeyBuffer& message,
372                                    std::string* ciphertext) {
373     km::AuthorizationSet opParams =
374             km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
375     km::AuthorizationSet outParams;
376     auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
377     if (!opHandle) return false;
378     auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
379     if (!nonceBlob) {
380         LOG(ERROR) << "GCM encryption but no nonce generated";
381         return false;
382     }
383     // nonceBlob here is just a pointer into existing data, must not be freed
384     std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
385     if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
386     std::string body;
387     if (!opHandle.updateCompletely(message, &body)) return false;
388 
389     std::string mac;
390     if (!opHandle.finish(&mac)) return false;
391     if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
392     *ciphertext = nonce + body + mac;
393     return true;
394 }
395 
decryptWithKeystoreKey(Keystore & keystore,const std::string & dir,const km::AuthorizationSet & keyParams,const std::string & ciphertext,KeyBuffer * message)396 static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
397                                    const km::AuthorizationSet& keyParams,
398                                    const std::string& ciphertext, KeyBuffer* message) {
399     const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
400     auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
401     auto opParams = km::AuthorizationSetBuilder()
402                             .Authorization(km::TAG_NONCE, nonce)
403                             .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
404     auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
405     if (!opHandle) return false;
406     if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
407     if (!opHandle.finish(nullptr)) return false;
408     return true;
409 }
410 
getStretching(const KeyAuthentication & auth)411 static std::string getStretching(const KeyAuthentication& auth) {
412     if (auth.usesKeystore()) {
413         return kStretch_nopassword;
414     } else {
415         return kStretch_none;
416     }
417 }
418 
stretchSecret(const std::string & stretching,const std::string & secret,std::string * stretched)419 static bool stretchSecret(const std::string& stretching, const std::string& secret,
420                           std::string* stretched) {
421     if (stretching == kStretch_nopassword) {
422         if (!secret.empty()) {
423             LOG(WARNING) << "Password present but stretching is nopassword";
424             // Continue anyway
425         }
426         stretched->clear();
427     } else if (stretching == kStretch_none) {
428         *stretched = secret;
429     } else {
430         LOG(ERROR) << "Unknown stretching type: " << stretching;
431         return false;
432     }
433     return true;
434 }
435 
generateAppId(const KeyAuthentication & auth,const std::string & stretching,const std::string & secdiscardable_hash,std::string * appId)436 static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
437                           const std::string& secdiscardable_hash, std::string* appId) {
438     std::string stretched;
439     if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
440     *appId = secdiscardable_hash + stretched;
441 
442     const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
443     switch (storage_binding_info.state) {
444         case StorageBindingInfo::State::UNINITIALIZED:
445             storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
446             break;
447         case StorageBindingInfo::State::IN_USE:
448             appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
449             break;
450         case StorageBindingInfo::State::NOT_USED:
451             // noop
452             break;
453     }
454 
455     return true;
456 }
457 
logOpensslError()458 static void logOpensslError() {
459     LOG(ERROR) << "Openssl error: " << ERR_get_error();
460 }
461 
encryptWithoutKeystore(const std::string & preKey,const KeyBuffer & plaintext,std::string * ciphertext)462 static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
463                                    std::string* ciphertext) {
464     std::string key;
465     hashWithPrefix(kHashPrefix_keygen, preKey, &key);
466     key.resize(AES_KEY_BYTES);
467     if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
468     auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
469         EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
470     if (!ctx) {
471         logOpensslError();
472         return false;
473     }
474     if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
475                                 reinterpret_cast<const uint8_t*>(key.data()),
476                                 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
477         logOpensslError();
478         return false;
479     }
480     ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
481     int outlen;
482     if (1 != EVP_EncryptUpdate(
483                  ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
484                  &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
485         logOpensslError();
486         return false;
487     }
488     if (outlen != static_cast<int>(plaintext.size())) {
489         LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
490         return false;
491     }
492     if (1 != EVP_EncryptFinal_ex(
493                  ctx.get(),
494                  reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
495                  &outlen)) {
496         logOpensslError();
497         return false;
498     }
499     if (outlen != 0) {
500         LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
501         return false;
502     }
503     if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
504                                  reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
505                                                             plaintext.size()))) {
506         logOpensslError();
507         return false;
508     }
509     return true;
510 }
511 
decryptWithoutKeystore(const std::string & preKey,const std::string & ciphertext,KeyBuffer * plaintext)512 static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
513                                    KeyBuffer* plaintext) {
514     if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
515         LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
516         return false;
517     }
518     std::string key;
519     hashWithPrefix(kHashPrefix_keygen, preKey, &key);
520     key.resize(AES_KEY_BYTES);
521     auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
522         EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
523     if (!ctx) {
524         logOpensslError();
525         return false;
526     }
527     if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
528                                 reinterpret_cast<const uint8_t*>(key.data()),
529                                 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
530         logOpensslError();
531         return false;
532     }
533     *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
534     int outlen;
535     if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
536                                reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
537                                plaintext->size())) {
538         logOpensslError();
539         return false;
540     }
541     if (outlen != static_cast<int>(plaintext->size())) {
542         LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
543         return false;
544     }
545     if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
546                                  const_cast<void*>(reinterpret_cast<const void*>(
547                                      ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
548         logOpensslError();
549         return false;
550     }
551     if (1 != EVP_DecryptFinal_ex(ctx.get(),
552                                  reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
553                                  &outlen)) {
554         logOpensslError();
555         return false;
556     }
557     if (outlen != 0) {
558         LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
559         return false;
560     }
561     return true;
562 }
563 
564 // Creates a directory at the given path |dir| and stores |key| in it, in such a
565 // way that it can only be retrieved via Keystore (if no secret is given in
566 // |auth|) or with the given secret (if a secret is given in |auth|), and can be
567 // securely deleted.  If a storage binding seed has been set, then the storage
568 // binding seed will be required to retrieve the key as well.
storeKey(const std::string & dir,const KeyAuthentication & auth,const KeyBuffer & key)569 static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
570     if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
571         PLOG(ERROR) << "key mkdir " << dir;
572         return false;
573     }
574     if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
575     std::string secdiscardable_hash;
576     if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
577     std::string stretching = getStretching(auth);
578     if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
579     std::string appId;
580     if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
581     std::string encryptedKey;
582     if (auth.usesKeystore()) {
583         Keystore keystore;
584         if (!keystore) return false;
585         std::string ksKey;
586         if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
587         if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
588         km::AuthorizationSet keyParams = beginParams(appId);
589         if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) {
590             LOG(ERROR) << "encryptWithKeystoreKey failed";
591             return false;
592         }
593     } else {
594         if (!encryptWithoutKeystore(appId, key, &encryptedKey)) {
595             LOG(ERROR) << "encryptWithoutKeystore failed";
596             return false;
597         }
598     }
599     if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
600     if (!FsyncDirectory(dir)) return false;
601     return true;
602 }
603 
storeKeyAtomically(const std::string & key_path,const std::string & tmp_path,const KeyAuthentication & auth,const KeyBuffer & key)604 bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
605                         const KeyAuthentication& auth, const KeyBuffer& key) {
606     if (pathExists(key_path)) {
607         LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
608         return false;
609     }
610     if (pathExists(tmp_path)) {
611         LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
612         destroyKey(tmp_path);  // May be partially created so ignore errors
613     }
614     if (!storeKey(tmp_path, auth, key)) return false;
615 
616     if (!RenameKeyDir(tmp_path, key_path)) return false;
617 
618     if (!FsyncParentDirectory(key_path)) return false;
619     LOG(DEBUG) << "Created key: " << key_path;
620     return true;
621 }
622 
retrieveKey(const std::string & dir,const KeyAuthentication & auth,KeyBuffer * key)623 bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
624     std::string version;
625     if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
626     if (version != kCurrentVersion) {
627         LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
628         return false;
629     }
630     std::string secdiscardable_hash;
631     if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
632     std::string stretching;
633     if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
634     std::string appId;
635     if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
636     std::string encryptedMessage;
637     if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
638     if (auth.usesKeystore()) {
639         Keystore keystore;
640         if (!keystore) return false;
641         km::AuthorizationSet keyParams = beginParams(appId);
642         if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) {
643             LOG(ERROR) << "decryptWithKeystoreKey failed";
644             return false;
645         }
646     } else {
647         if (!decryptWithoutKeystore(appId, encryptedMessage, key)) {
648             LOG(ERROR) << "decryptWithoutKeystore failed";
649             return false;
650         }
651     }
652     return true;
653 }
654 
DeleteKeystoreKey(const std::string & blob_file)655 static bool DeleteKeystoreKey(const std::string& blob_file) {
656     std::string blob;
657     if (!readFileToString(blob_file, &blob)) return false;
658     Keystore keystore;
659     if (!keystore) return false;
660     LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
661     if (!keystore.deleteKey(blob)) return false;
662     return true;
663 }
664 
runSecdiscardSingle(const std::string & file)665 bool runSecdiscardSingle(const std::string& file) {
666     if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
667         LOG(ERROR) << "secdiscard failed";
668         return false;
669     }
670     return true;
671 }
672 
recursiveDeleteKey(const std::string & dir)673 static bool recursiveDeleteKey(const std::string& dir) {
674     if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
675         LOG(ERROR) << "recursive delete failed";
676         return false;
677     }
678     return true;
679 }
680 
destroyKey(const std::string & dir)681 bool destroyKey(const std::string& dir) {
682     bool success = true;
683 
684     CancelPendingKeyCommit(dir);
685 
686     auto secdiscard_cmd = std::vector<std::string>{
687         kSecdiscardPath,
688         "--",
689         dir + "/" + kFn_encrypted_key,
690         dir + "/" + kFn_secdiscardable,
691     };
692     // Try each thing, even if previous things failed.
693 
694     for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
695         auto blob_file = dir + "/" + fn;
696         if (pathExists(blob_file)) {
697             success &= DeleteKeystoreKey(blob_file);
698             secdiscard_cmd.push_back(blob_file);
699         }
700     }
701     if (ForkExecvp(secdiscard_cmd) != 0) {
702         LOG(ERROR) << "secdiscard failed";
703         success = false;
704     }
705     success &= recursiveDeleteKey(dir);
706     return success;
707 }
708 
setKeyStorageBindingSeed(const std::vector<uint8_t> & seed)709 bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
710     const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
711     switch (storage_binding_info.state) {
712         case StorageBindingInfo::State::UNINITIALIZED:
713             storage_binding_info.state = StorageBindingInfo::State::IN_USE;
714             storage_binding_info.seed = seed;
715             android::base::SetProperty("vold.storage_seed_bound", "1");
716             return true;
717         case StorageBindingInfo::State::IN_USE:
718             LOG(ERROR) << "key storage binding seed already set";
719             return false;
720         case StorageBindingInfo::State::NOT_USED:
721             LOG(ERROR) << "key storage already in use without binding";
722             return false;
723     }
724     return false;
725 }
726 
727 }  // namespace vold
728 }  // namespace android
729