OSDN Git Service

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