blob: b8000faeebdb87c17b85740a50cf4026c1c26db3 [file] [log] [blame]
Paul Crowley1ef25582016-01-21 20:26:12 +00001/*
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
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070019#include "Checkpoint.h"
Eric Biggersd86a8ab2021-06-15 11:34:00 -070020#include "Keystore.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000021#include "Utils.h"
22
Eric Biggersf74373b2020-11-05 19:58:26 -080023#include <algorithm>
Seth Moore5a43d612021-01-19 17:51:51 +000024#include <memory>
25#include <mutex>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070026#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000027#include <vector>
28
29#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070030#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000031#include <sys/stat.h>
32#include <sys/types.h>
33#include <sys/wait.h>
34#include <unistd.h>
35
Paul Crowley6ab2cab2017-01-04 22:32:40 -080036#include <openssl/err.h>
37#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000038#include <openssl/sha.h>
39
40#include <android-base/file.h>
41#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070042#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070043#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000044
Paul Crowley63c18d32016-02-10 14:02:47 +000045#include <cutils/properties.h>
46
Paul Crowley1ef25582016-01-21 20:26:12 +000047namespace android {
48namespace vold {
49
Satya Tangiralae1361712021-03-15 15:33:08 -070050const KeyAuthentication kEmptyAuthentication{""};
Paul Crowley05720802016-02-08 15:55:41 +000051
Paul Crowley1ef25582016-01-21 20:26:12 +000052static constexpr size_t AES_KEY_BYTES = 32;
53static constexpr size_t GCM_NONCE_BYTES = 12;
54static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080055static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
Paul Crowleyb3de3372016-04-27 12:58:41 -070056
Paul Crowley05720802016-02-08 15:55:41 +000057static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000058static const char* kRmPath = "/system/bin/rm";
59static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000060static const char* kStretch_none = "none";
61static const char* kStretch_nopassword = "nopassword";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080062static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
63static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000064static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000065static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070066static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000067static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000068static const char* kFn_stretching = "stretching";
69static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000070
Seth Moore5a43d612021-01-19 17:51:51 +000071namespace {
72
73// Storage binding info for ensuring key encryption keys include a
74// platform-provided seed in their derivation.
75struct 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.
92StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
93
94} // namespace
95
Paul Crowley13ffd8e2016-01-27 14:30:22 +000096static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000097 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080098 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
99 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +0000100 return false;
101 }
102 return true;
103}
104
Paul Crowley26a53882017-10-26 11:16:39 -0700105static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000106 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
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800112 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());
Paul Crowley26a53882017-10-26 11:16:39 -0700116 res->assign(SHA512_DIGEST_LENGTH, '\0');
117 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000118}
119
Eric Biggers2d30b892022-07-28 18:06:42 +0000120static 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";
Eric Biggersb2024e02021-03-15 12:44:36 -0700127 auto paramsWithRollback = paramBuilder;
128 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
129
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700130 if (!keystore.generateKey(paramsWithRollback, key)) {
131 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keystore "
Eric Biggersb2024e02021-03-15 12:44:36 -0700132 "doesn't support rollback resistance. Falling back to "
133 "non-rollback-resistant key.";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700134 if (!keystore.generateKey(paramBuilder, key)) return false;
Eric Biggersb2024e02021-03-15 12:44:36 -0700135 }
136 return true;
137}
138
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800139bool generateWrappedStorageKey(KeyBuffer* key) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700140 Keystore keystore;
141 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800142 std::string key_temp;
143 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800144 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Eric Biggers2d30b892022-07-28 18:06:42 +0000145 if (!keystore.generateKey(paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800146 *key = KeyBuffer(key_temp.size());
147 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
148 return true;
149}
150
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700151bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
152 Keystore keystore;
153 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800154 std::string key_temp;
155
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700156 if (!keystore.exportKey(ksKey, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800157 *key = KeyBuffer(key_temp.size());
158 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
159 return true;
160}
161
Satya Tangiralae1361712021-03-15 15:33:08 -0700162static km::AuthorizationSet beginParams(const std::string& appId) {
163 return km::AuthorizationSetBuilder()
164 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800165 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000166}
167
Paul Crowleydf528a72016-03-09 09:31:37 -0800168static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800169 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800170 PLOG(ERROR) << "Failed to read from " << filename;
171 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000172 }
173 return true;
174}
175
Paul Crowley26a53882017-10-26 11:16:39 -0700176static 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
185bool 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
193bool readSecdiscardable(const std::string& filename, std::string* hash) {
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000194 if (pathExists(filename)) {
195 std::string secdiscardable;
196 if (!readFileToString(filename, &secdiscardable)) return false;
197 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
198 } else {
199 *hash = "";
200 }
Paul Crowley26a53882017-10-26 11:16:39 -0700201 return true;
202}
203
Eric Biggersf74373b2020-11-05 19:58:26 -0800204static std::mutex key_upgrade_lock;
205
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700206// List of key directories that have had their Keystore key upgraded during
Eric Biggersf74373b2020-11-05 19:58:26 -0800207// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
208// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
Eric Biggers107d21d2021-06-08 12:55:00 -0700209// A directory can be in this list at most once.
Eric Biggersf74373b2020-11-05 19:58:26 -0800210static std::vector<std::string> key_dirs_to_commit;
211
212// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700213// deletes the old key from Keystore.
214static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800215 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
216 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
217
218 std::string blob;
219 if (!readFileToString(blob_file, &blob)) return false;
220
221 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
222 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
223 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700224 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700225 // Ensure that the rename is persisted before deleting the Keystore key.
Eric Biggersf74373b2020-11-05 19:58:26 -0800226 if (!FsyncDirectory(dir)) return false;
227
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700228 if (!keystore || !keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800229 LOG(WARNING) << "Failed to delete old key " << blob_file
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700230 << " from Keystore; continuing anyway";
231 // Continue on, but the space in Keystore used by the old key won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800232 }
233 return true;
234}
235
236static void DeferredCommitKeys() {
237 android::base::WaitForProperty("vold.checkpoint_committed", "1");
238 LOG(INFO) << "Committing upgraded keys";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700239 Keystore keystore;
240 if (!keystore) {
241 LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
242 // Continue on, but the space in Keystore used by the old keys won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800243 }
244 std::lock_guard<std::mutex> lock(key_upgrade_lock);
245 for (auto& dir : key_dirs_to_commit) {
246 LOG(INFO) << "Committing upgraded key " << dir;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700247 CommitUpgradedKey(keystore, dir);
Eric Biggersf74373b2020-11-05 19:58:26 -0800248 }
249 key_dirs_to_commit.clear();
250}
251
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700252// Returns true if the Keystore key in |dir| has already been upgraded and is
Eric Biggersf74373b2020-11-05 19:58:26 -0800253// pending being committed. Assumes that key_upgrade_lock is held.
254static bool IsKeyCommitPending(const std::string& dir) {
255 for (const auto& dir_to_commit : key_dirs_to_commit) {
256 if (IsSameFile(dir, dir_to_commit)) return true;
257 }
258 return false;
259}
260
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700261// Schedules the upgraded Keystore key in |dir| to be committed later. Assumes
Eric Biggers107d21d2021-06-08 12:55:00 -0700262// that key_upgrade_lock is held and that a commit isn't already pending for the
263// directory.
Eric Biggersf74373b2020-11-05 19:58:26 -0800264static void ScheduleKeyCommit(const std::string& dir) {
265 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
266 key_dirs_to_commit.push_back(dir);
267}
268
269static void CancelPendingKeyCommit(const std::string& dir) {
270 std::lock_guard<std::mutex> lock(key_upgrade_lock);
271 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
272 if (IsSameFile(*it, dir)) {
273 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
274 << " because it is being destroyed";
275 key_dirs_to_commit.erase(it);
276 break;
277 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700278 }
279}
280
Satya Tangirala0f890a92021-06-08 12:55:24 -0700281bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
Satya Tangirala9475b112021-05-13 00:43:03 -0700282 std::lock_guard<std::mutex> lock(key_upgrade_lock);
283
Eric Biggers107d21d2021-06-08 12:55:00 -0700284 // Find the entry in key_dirs_to_commit (if any) for this directory so that
285 // we can update it if the rename succeeds. We don't allow duplicates in
286 // this list, so there can be at most one such entry.
287 auto it = key_dirs_to_commit.begin();
288 for (; it != key_dirs_to_commit.end(); it++) {
289 if (IsSameFile(old_name, *it)) break;
290 }
291
Satya Tangirala0f890a92021-06-08 12:55:24 -0700292 if (rename(old_name.c_str(), new_name.c_str()) != 0) {
293 PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
294 << "\"";
295 return false;
296 }
Satya Tangirala9475b112021-05-13 00:43:03 -0700297
Eric Biggers107d21d2021-06-08 12:55:00 -0700298 if (it != key_dirs_to_commit.end()) *it = new_name;
299
Satya Tangirala9475b112021-05-13 00:43:03 -0700300 return true;
301}
302
Eric Biggersf74373b2020-11-05 19:58:26 -0800303// Deletes a leftover upgraded key, if present. An upgraded key can be left
304// over if an update failed, or if we rebooted before committing the key in a
305// freak accident. Either way, we can re-upgrade the key if we need to.
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700306static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800307 if (pathExists(path)) {
308 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
309 std::string blob;
310 if (!android::base::ReadFileToString(path, &blob)) {
311 LOG(WARNING) << "Failed to read leftover upgraded key " << path
312 << "; continuing anyway";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700313 } else if (!keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800314 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700315 << " from Keystore; continuing anyway";
Eric Biggersf74373b2020-11-05 19:58:26 -0800316 }
317 if (unlink(path.c_str()) != 0) {
318 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
319 << "; continuing anyway";
320 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700321 }
322}
323
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700324// Begins a Keystore operation using the key stored in |dir|.
325static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
326 const km::AuthorizationSet& keyParams,
327 const km::AuthorizationSet& opParams,
328 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700329 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100330 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800331
332 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
333 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
334
335 std::lock_guard<std::mutex> lock(key_upgrade_lock);
336
337 std::string blob;
338 bool already_upgraded = IsKeyCommitPending(dir);
339 if (already_upgraded) {
340 LOG(DEBUG)
341 << blob_file
342 << " was already upgraded and is waiting to be committed; using the upgraded blob";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700343 if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800344 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700345 DeleteUpgradedKey(keystore, upgraded_blob_file);
346 if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700347 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800348
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700349 auto opHandle = keystore.begin(blob, inParams, outParams);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800350 if (!opHandle) return opHandle;
351
352 // If key blob wasn't upgraded, nothing left to do.
353 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800354
355 if (already_upgraded) {
356 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
357 << " still requires upgrade";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700358 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800359 }
360 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800361 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700362 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800363 if (cp_needsCheckpoint()) {
364 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
365 << "; delaying commit due to checkpoint";
366 ScheduleKeyCommit(dir);
367 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700368 if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800369 LOG(INFO) << "Key upgraded: " << blob_file;
370 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800371 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700372}
373
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700374static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
375 const km::AuthorizationSet& keyParams, const KeyBuffer& message,
376 std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800377 km::AuthorizationSet opParams =
Haiping Yangc0a46c82021-08-23 01:24:25 +0000378 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700379 km::AuthorizationSet outParams;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700380 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700381 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700382 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800383 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700384 LOG(ERROR) << "GCM encryption but no nonce generated";
385 return false;
386 }
387 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800388 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700389 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
390 std::string body;
391 if (!opHandle.updateCompletely(message, &body)) return false;
392
393 std::string mac;
394 if (!opHandle.finish(&mac)) return false;
395 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
396 *ciphertext = nonce + body + mac;
397 return true;
398}
399
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700400static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
401 const km::AuthorizationSet& keyParams,
402 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800403 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700404 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800405 auto opParams = km::AuthorizationSetBuilder()
406 .Authorization(km::TAG_NONCE, nonce)
407 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700408 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700409 if (!opHandle) return false;
410 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
411 if (!opHandle.finish(nullptr)) return false;
412 return true;
413}
414
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800415static std::string getStretching(const KeyAuthentication& auth) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700416 if (auth.usesKeystore()) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800417 return kStretch_nopassword;
418 } else {
Satya Tangiralae1361712021-03-15 15:33:08 -0700419 return kStretch_none;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800420 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000421}
422
Paul Crowleydf528a72016-03-09 09:31:37 -0800423static bool stretchSecret(const std::string& stretching, const std::string& secret,
Satya Tangirala478cea92021-04-07 14:30:25 -0700424 std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000425 if (stretching == kStretch_nopassword) {
426 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800427 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000428 // Continue anyway
429 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800430 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000431 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800432 *stretched = secret;
Paul Crowley63c18d32016-02-10 14:02:47 +0000433 } else {
434 LOG(ERROR) << "Unknown stretching type: " << stretching;
435 return false;
436 }
437 return true;
438}
439
Paul Crowleydf528a72016-03-09 09:31:37 -0800440static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Satya Tangirala478cea92021-04-07 14:30:25 -0700441 const std::string& secdiscardable_hash, std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000442 std::string stretched;
Satya Tangirala478cea92021-04-07 14:30:25 -0700443 if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700444 *appId = secdiscardable_hash + stretched;
Seth Moore5a43d612021-01-19 17:51:51 +0000445
446 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
447 switch (storage_binding_info.state) {
448 case StorageBindingInfo::State::UNINITIALIZED:
449 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
450 break;
451 case StorageBindingInfo::State::IN_USE:
452 appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
453 break;
454 case StorageBindingInfo::State::NOT_USED:
455 // noop
456 break;
457 }
458
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800459 return true;
460}
461
462static void logOpensslError() {
463 LOG(ERROR) << "Openssl error: " << ERR_get_error();
464}
465
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700466static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
467 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700468 std::string key;
469 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800470 key.resize(AES_KEY_BYTES);
471 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
472 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
473 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
474 if (!ctx) {
475 logOpensslError();
476 return false;
477 }
478 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700479 reinterpret_cast<const uint8_t*>(key.data()),
480 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800481 logOpensslError();
482 return false;
483 }
484 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
485 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700486 if (1 != EVP_EncryptUpdate(
487 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
488 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800489 logOpensslError();
490 return false;
491 }
492 if (outlen != static_cast<int>(plaintext.size())) {
493 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
494 return false;
495 }
Shawn Willden785365b2018-01-20 09:37:36 -0700496 if (1 != EVP_EncryptFinal_ex(
497 ctx.get(),
498 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
499 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800500 logOpensslError();
501 return false;
502 }
503 if (outlen != 0) {
504 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
505 return false;
506 }
507 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700508 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
509 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800510 logOpensslError();
511 return false;
512 }
513 return true;
514}
515
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700516static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
517 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800518 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
519 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
520 return false;
521 }
Paul Crowley26a53882017-10-26 11:16:39 -0700522 std::string key;
523 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800524 key.resize(AES_KEY_BYTES);
525 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
526 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
527 if (!ctx) {
528 logOpensslError();
529 return false;
530 }
531 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700532 reinterpret_cast<const uint8_t*>(key.data()),
533 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800534 logOpensslError();
535 return false;
536 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100537 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800538 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700539 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
540 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
541 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800542 logOpensslError();
543 return false;
544 }
545 if (outlen != static_cast<int>(plaintext->size())) {
546 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
547 return false;
548 }
549 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700550 const_cast<void*>(reinterpret_cast<const void*>(
551 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800552 logOpensslError();
553 return false;
554 }
555 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700556 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
557 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800558 logOpensslError();
559 return false;
560 }
561 if (outlen != 0) {
562 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
563 return false;
564 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000565 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000566}
567
Satya Tangirala351a4af2021-06-08 12:55:37 -0700568// Creates a directory at the given path |dir| and stores |key| in it, in such a
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700569// way that it can only be retrieved via Keystore (if no secret is given in
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000570// |auth|) or with the given secret (if a secret is given in |auth|). In the
571// former case, an attempt is made to make the key securely deletable. In the
572// latter case, secure deletion is expected to be handled at a higher level.
573//
574// If a storage binding seed has been set, then the storage binding seed will be
575// required to retrieve the key as well.
Satya Tangirala351a4af2021-06-08 12:55:37 -0700576static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000577 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
578 PLOG(ERROR) << "key mkdir " << dir;
579 return false;
580 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800581 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700582 std::string secdiscardable_hash;
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000583 if (auth.usesKeystore() &&
584 !createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash))
585 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800586 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800587 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800588 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700589 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800590 std::string encryptedKey;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700591 if (auth.usesKeystore()) {
592 Keystore keystore;
593 if (!keystore) return false;
594 std::string ksKey;
595 if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
596 if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700597 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700598 if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) {
599 LOG(ERROR) << "encryptWithKeystoreKey failed";
600 return false;
601 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800602 } else {
David Andersone1791572021-11-05 18:57:49 -0700603 if (!encryptWithoutKeystore(appId, key, &encryptedKey)) {
604 LOG(ERROR) << "encryptWithoutKeystore failed";
605 return false;
606 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800607 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000608 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800609 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000610 return true;
611}
612
Paul Crowleyf71ace32016-06-02 11:01:19 -0700613bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100614 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700615 if (pathExists(key_path)) {
616 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
617 return false;
618 }
619 if (pathExists(tmp_path)) {
620 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
621 destroyKey(tmp_path); // May be partially created so ignore errors
622 }
623 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700624
Satya Tangirala0f890a92021-06-08 12:55:24 -0700625 if (!RenameKeyDir(tmp_path, key_path)) return false;
626
Eric Biggers3345a2a2021-02-16 15:59:17 -0800627 if (!FsyncParentDirectory(key_path)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700628 LOG(DEBUG) << "Created key: " << key_path;
629 return true;
630}
631
Eric Biggersf74373b2020-11-05 19:58:26 -0800632bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000633 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800634 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000635 if (version != kCurrentVersion) {
636 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
637 return false;
638 }
Paul Crowley26a53882017-10-26 11:16:39 -0700639 std::string secdiscardable_hash;
640 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000641 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800642 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800643 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700644 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000645 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800646 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700647 if (auth.usesKeystore()) {
648 Keystore keystore;
649 if (!keystore) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700650 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700651 if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) {
652 LOG(ERROR) << "decryptWithKeystoreKey failed";
653 return false;
654 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800655 } else {
David Andersone1791572021-11-05 18:57:49 -0700656 if (!decryptWithoutKeystore(appId, encryptedMessage, key)) {
657 LOG(ERROR) << "decryptWithoutKeystore failed";
658 return false;
659 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800660 }
661 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000662}
663
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700664static bool DeleteKeystoreKey(const std::string& blob_file) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800665 std::string blob;
666 if (!readFileToString(blob_file, &blob)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700667 Keystore keystore;
668 if (!keystore) return false;
669 LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
670 if (!keystore.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000671 return true;
672}
673
Rubin Xu2436e272017-04-27 20:43:10 +0100674bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700675 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100676 LOG(ERROR) << "secdiscard failed";
677 return false;
678 }
679 return true;
680}
681
Paul Crowleydf528a72016-03-09 09:31:37 -0800682static bool recursiveDeleteKey(const std::string& dir) {
683 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000684 LOG(ERROR) << "recursive delete failed";
685 return false;
686 }
687 return true;
688}
689
Paul Crowleydf528a72016-03-09 09:31:37 -0800690bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000691 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800692
693 CancelPendingKeyCommit(dir);
694
Paul Crowleyff19b052017-10-26 11:28:55 -0700695 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700696 kSecdiscardPath,
697 "--",
698 dir + "/" + kFn_encrypted_key,
699 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700700 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800701 // Try each thing, even if previous things failed.
702
703 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
704 auto blob_file = dir + "/" + fn;
705 if (pathExists(blob_file)) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700706 success &= DeleteKeystoreKey(blob_file);
Eric Biggersf74373b2020-11-05 19:58:26 -0800707 secdiscard_cmd.push_back(blob_file);
708 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700709 }
710 if (ForkExecvp(secdiscard_cmd) != 0) {
711 LOG(ERROR) << "secdiscard failed";
712 success = false;
713 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000714 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000715 return success;
716}
717
Seth Moore5a43d612021-01-19 17:51:51 +0000718bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
719 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
720 switch (storage_binding_info.state) {
721 case StorageBindingInfo::State::UNINITIALIZED:
722 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
723 storage_binding_info.seed = seed;
Keith Moke8600252021-09-01 18:37:48 +0000724 android::base::SetProperty("vold.storage_seed_bound", "1");
Seth Moore5a43d612021-01-19 17:51:51 +0000725 return true;
726 case StorageBindingInfo::State::IN_USE:
727 LOG(ERROR) << "key storage binding seed already set";
728 return false;
729 case StorageBindingInfo::State::NOT_USED:
730 LOG(ERROR) << "key storage already in use without binding";
731 return false;
732 }
733 return false;
734}
735
Paul Crowley1ef25582016-01-21 20:26:12 +0000736} // namespace vold
737} // namespace android