OSDN Git Service

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