blob: eb994e9cb0d89b567051b17f6436eb23bbc3e16a [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 Crowley6ab2cab2017-01-04 22:32:40 -080060static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
61static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000062static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000063static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070064static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000065static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000066static const char* kFn_version = "version";
Eric Biggersf187f052022-10-13 03:50:21 +000067// Note: old key directories may contain a file named "stretching".
Paul Crowley1ef25582016-01-21 20:26:12 +000068
Seth Moore5a43d612021-01-19 17:51:51 +000069namespace {
70
71// Storage binding info for ensuring key encryption keys include a
72// platform-provided seed in their derivation.
73struct StorageBindingInfo {
74 enum class State {
75 UNINITIALIZED,
76 IN_USE, // key storage keys are bound to seed
77 NOT_USED, // key storage keys are NOT bound to seed
78 };
79
80 // Binding seed mixed into all key storage keys.
81 std::vector<uint8_t> seed;
82
83 // State tracker for the key storage key binding.
84 State state = State::UNINITIALIZED;
85
86 std::mutex guard;
87};
88
89// Never freed as the dtor is non-trivial.
90StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
91
92} // namespace
93
Paul Crowley13ffd8e2016-01-27 14:30:22 +000094static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000095 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080096 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
97 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000098 return false;
99 }
100 return true;
101}
102
Paul Crowley26a53882017-10-26 11:16:39 -0700103static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000104 SHA512_CTX c;
105
106 SHA512_Init(&c);
107 // Personalise the hashing by introducing a fixed prefix.
108 // Hashing applications should use personalization except when there is a
109 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800110 std::string hashingPrefix = prefix;
111 hashingPrefix.resize(SHA512_CBLOCK);
112 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
113 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700114 res->assign(SHA512_DIGEST_LENGTH, '\0');
115 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000116}
117
Eric Biggers2d30b892022-07-28 18:06:42 +0000118static bool generateKeyStorageKey(Keystore& keystore, const std::string& appId, std::string* key) {
119 auto paramBuilder = km::AuthorizationSetBuilder()
120 .AesEncryptionKey(AES_KEY_BYTES * 8)
121 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
122 .Authorization(km::TAG_APPLICATION_ID, appId)
123 .Authorization(km::TAG_NO_AUTH_REQUIRED);
124 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersb2024e02021-03-15 12:44:36 -0700125 auto paramsWithRollback = paramBuilder;
126 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
127
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700128 if (!keystore.generateKey(paramsWithRollback, key)) {
129 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keystore "
Eric Biggersb2024e02021-03-15 12:44:36 -0700130 "doesn't support rollback resistance. Falling back to "
131 "non-rollback-resistant key.";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700132 if (!keystore.generateKey(paramBuilder, key)) return false;
Eric Biggersb2024e02021-03-15 12:44:36 -0700133 }
134 return true;
135}
136
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800137bool generateWrappedStorageKey(KeyBuffer* key) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700138 Keystore keystore;
139 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800140 std::string key_temp;
141 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800142 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Eric Biggers2d30b892022-07-28 18:06:42 +0000143 if (!keystore.generateKey(paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800144 *key = KeyBuffer(key_temp.size());
145 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
146 return true;
147}
148
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700149bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
150 Keystore keystore;
151 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800152 std::string key_temp;
153
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700154 if (!keystore.exportKey(ksKey, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800155 *key = KeyBuffer(key_temp.size());
156 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
157 return true;
158}
159
Satya Tangiralae1361712021-03-15 15:33:08 -0700160static km::AuthorizationSet beginParams(const std::string& appId) {
161 return km::AuthorizationSetBuilder()
162 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800163 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000164}
165
Paul Crowleydf528a72016-03-09 09:31:37 -0800166static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800167 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800168 PLOG(ERROR) << "Failed to read from " << filename;
169 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000170 }
171 return true;
172}
173
Paul Crowley26a53882017-10-26 11:16:39 -0700174static bool readRandomBytesOrLog(size_t count, std::string* out) {
175 auto status = ReadRandomBytes(count, *out);
176 if (status != OK) {
177 LOG(ERROR) << "Random read failed with status: " << status;
178 return false;
179 }
180 return true;
181}
182
183bool createSecdiscardable(const std::string& filename, std::string* hash) {
184 std::string secdiscardable;
185 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
186 if (!writeStringToFile(secdiscardable, filename)) return false;
187 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
188 return true;
189}
190
191bool readSecdiscardable(const std::string& filename, std::string* hash) {
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000192 if (pathExists(filename)) {
193 std::string secdiscardable;
194 if (!readFileToString(filename, &secdiscardable)) return false;
195 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
196 } else {
197 *hash = "";
198 }
Paul Crowley26a53882017-10-26 11:16:39 -0700199 return true;
200}
201
Eric Biggersf74373b2020-11-05 19:58:26 -0800202static std::mutex key_upgrade_lock;
203
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700204// List of key directories that have had their Keystore key upgraded during
Eric Biggersf74373b2020-11-05 19:58:26 -0800205// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
206// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
Eric Biggers107d21d2021-06-08 12:55:00 -0700207// A directory can be in this list at most once.
Eric Biggersf74373b2020-11-05 19:58:26 -0800208static std::vector<std::string> key_dirs_to_commit;
209
210// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700211// deletes the old key from Keystore.
212static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800213 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
214 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
215
216 std::string blob;
217 if (!readFileToString(blob_file, &blob)) return false;
218
219 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
220 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
221 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700222 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700223 // Ensure that the rename is persisted before deleting the Keystore key.
Eric Biggersf74373b2020-11-05 19:58:26 -0800224 if (!FsyncDirectory(dir)) return false;
225
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700226 if (!keystore || !keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800227 LOG(WARNING) << "Failed to delete old key " << blob_file
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700228 << " from Keystore; continuing anyway";
229 // Continue on, but the space in Keystore used by the old key won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800230 }
231 return true;
232}
233
234static void DeferredCommitKeys() {
235 android::base::WaitForProperty("vold.checkpoint_committed", "1");
236 LOG(INFO) << "Committing upgraded keys";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700237 Keystore keystore;
238 if (!keystore) {
239 LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
240 // Continue on, but the space in Keystore used by the old keys won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800241 }
242 std::lock_guard<std::mutex> lock(key_upgrade_lock);
243 for (auto& dir : key_dirs_to_commit) {
244 LOG(INFO) << "Committing upgraded key " << dir;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700245 CommitUpgradedKey(keystore, dir);
Eric Biggersf74373b2020-11-05 19:58:26 -0800246 }
247 key_dirs_to_commit.clear();
248}
249
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700250// Returns true if the Keystore key in |dir| has already been upgraded and is
Eric Biggersf74373b2020-11-05 19:58:26 -0800251// pending being committed. Assumes that key_upgrade_lock is held.
252static bool IsKeyCommitPending(const std::string& dir) {
253 for (const auto& dir_to_commit : key_dirs_to_commit) {
254 if (IsSameFile(dir, dir_to_commit)) return true;
255 }
256 return false;
257}
258
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700259// Schedules the upgraded Keystore key in |dir| to be committed later. Assumes
Eric Biggers107d21d2021-06-08 12:55:00 -0700260// that key_upgrade_lock is held and that a commit isn't already pending for the
261// directory.
Eric Biggersf74373b2020-11-05 19:58:26 -0800262static void ScheduleKeyCommit(const std::string& dir) {
263 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
264 key_dirs_to_commit.push_back(dir);
265}
266
267static void CancelPendingKeyCommit(const std::string& dir) {
268 std::lock_guard<std::mutex> lock(key_upgrade_lock);
269 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
270 if (IsSameFile(*it, dir)) {
271 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
272 << " because it is being destroyed";
273 key_dirs_to_commit.erase(it);
274 break;
275 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700276 }
277}
278
Satya Tangirala0f890a92021-06-08 12:55:24 -0700279bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
Satya Tangirala9475b112021-05-13 00:43:03 -0700280 std::lock_guard<std::mutex> lock(key_upgrade_lock);
281
Eric Biggers107d21d2021-06-08 12:55:00 -0700282 // Find the entry in key_dirs_to_commit (if any) for this directory so that
283 // we can update it if the rename succeeds. We don't allow duplicates in
284 // this list, so there can be at most one such entry.
285 auto it = key_dirs_to_commit.begin();
286 for (; it != key_dirs_to_commit.end(); it++) {
287 if (IsSameFile(old_name, *it)) break;
288 }
289
Satya Tangirala0f890a92021-06-08 12:55:24 -0700290 if (rename(old_name.c_str(), new_name.c_str()) != 0) {
291 PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
292 << "\"";
293 return false;
294 }
Satya Tangirala9475b112021-05-13 00:43:03 -0700295
Eric Biggers107d21d2021-06-08 12:55:00 -0700296 if (it != key_dirs_to_commit.end()) *it = new_name;
297
Satya Tangirala9475b112021-05-13 00:43:03 -0700298 return true;
299}
300
Eric Biggersf74373b2020-11-05 19:58:26 -0800301// Deletes a leftover upgraded key, if present. An upgraded key can be left
302// over if an update failed, or if we rebooted before committing the key in a
303// freak accident. Either way, we can re-upgrade the key if we need to.
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700304static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800305 if (pathExists(path)) {
306 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
307 std::string blob;
308 if (!android::base::ReadFileToString(path, &blob)) {
309 LOG(WARNING) << "Failed to read leftover upgraded key " << path
310 << "; continuing anyway";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700311 } else if (!keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800312 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700313 << " from Keystore; continuing anyway";
Eric Biggersf74373b2020-11-05 19:58:26 -0800314 }
315 if (unlink(path.c_str()) != 0) {
316 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
317 << "; continuing anyway";
318 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700319 }
320}
321
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700322// Begins a Keystore operation using the key stored in |dir|.
323static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
324 const km::AuthorizationSet& keyParams,
325 const km::AuthorizationSet& opParams,
326 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700327 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100328 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800329
330 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
331 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
332
333 std::lock_guard<std::mutex> lock(key_upgrade_lock);
334
335 std::string blob;
336 bool already_upgraded = IsKeyCommitPending(dir);
337 if (already_upgraded) {
338 LOG(DEBUG)
339 << blob_file
340 << " was already upgraded and is waiting to be committed; using the upgraded blob";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700341 if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800342 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700343 DeleteUpgradedKey(keystore, upgraded_blob_file);
344 if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700345 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800346
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700347 auto opHandle = keystore.begin(blob, inParams, outParams);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800348 if (!opHandle) return opHandle;
349
350 // If key blob wasn't upgraded, nothing left to do.
351 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800352
353 if (already_upgraded) {
354 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
355 << " still requires upgrade";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700356 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800357 }
358 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800359 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700360 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800361 if (cp_needsCheckpoint()) {
362 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
363 << "; delaying commit due to checkpoint";
364 ScheduleKeyCommit(dir);
365 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700366 if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800367 LOG(INFO) << "Key upgraded: " << blob_file;
368 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800369 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700370}
371
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700372static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
373 const km::AuthorizationSet& keyParams, const KeyBuffer& message,
374 std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800375 km::AuthorizationSet opParams =
Haiping Yangc0a46c82021-08-23 01:24:25 +0000376 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700377 km::AuthorizationSet outParams;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700378 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700379 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700380 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800381 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700382 LOG(ERROR) << "GCM encryption but no nonce generated";
383 return false;
384 }
385 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800386 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700387 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
388 std::string body;
389 if (!opHandle.updateCompletely(message, &body)) return false;
390
391 std::string mac;
392 if (!opHandle.finish(&mac)) return false;
393 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
394 *ciphertext = nonce + body + mac;
395 return true;
396}
397
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700398static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
399 const km::AuthorizationSet& keyParams,
400 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800401 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700402 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800403 auto opParams = km::AuthorizationSetBuilder()
404 .Authorization(km::TAG_NONCE, nonce)
405 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700406 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700407 if (!opHandle) return false;
408 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
409 if (!opHandle.finish(nullptr)) return false;
410 return true;
411}
412
Eric Biggersf187f052022-10-13 03:50:21 +0000413static std::string generateAppId(const KeyAuthentication& auth,
414 const std::string& secdiscardable_hash) {
415 std::string appId = secdiscardable_hash + auth.secret;
Seth Moore5a43d612021-01-19 17:51:51 +0000416
417 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
418 switch (storage_binding_info.state) {
419 case StorageBindingInfo::State::UNINITIALIZED:
420 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
421 break;
422 case StorageBindingInfo::State::IN_USE:
Eric Biggersf187f052022-10-13 03:50:21 +0000423 appId.append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
Seth Moore5a43d612021-01-19 17:51:51 +0000424 break;
425 case StorageBindingInfo::State::NOT_USED:
426 // noop
427 break;
428 }
Eric Biggersf187f052022-10-13 03:50:21 +0000429 return appId;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800430}
431
432static void logOpensslError() {
433 LOG(ERROR) << "Openssl error: " << ERR_get_error();
434}
435
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700436static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
437 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700438 std::string key;
439 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800440 key.resize(AES_KEY_BYTES);
441 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
442 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
443 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
444 if (!ctx) {
445 logOpensslError();
446 return false;
447 }
448 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700449 reinterpret_cast<const uint8_t*>(key.data()),
450 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800451 logOpensslError();
452 return false;
453 }
454 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
455 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700456 if (1 != EVP_EncryptUpdate(
457 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
458 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800459 logOpensslError();
460 return false;
461 }
462 if (outlen != static_cast<int>(plaintext.size())) {
463 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
464 return false;
465 }
Shawn Willden785365b2018-01-20 09:37:36 -0700466 if (1 != EVP_EncryptFinal_ex(
467 ctx.get(),
468 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
469 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800470 logOpensslError();
471 return false;
472 }
473 if (outlen != 0) {
474 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
475 return false;
476 }
477 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700478 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
479 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800480 logOpensslError();
481 return false;
482 }
483 return true;
484}
485
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700486static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
487 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800488 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
489 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
490 return false;
491 }
Paul Crowley26a53882017-10-26 11:16:39 -0700492 std::string key;
493 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800494 key.resize(AES_KEY_BYTES);
495 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
496 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
497 if (!ctx) {
498 logOpensslError();
499 return false;
500 }
501 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700502 reinterpret_cast<const uint8_t*>(key.data()),
503 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800504 logOpensslError();
505 return false;
506 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100507 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800508 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700509 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
510 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
511 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800512 logOpensslError();
513 return false;
514 }
515 if (outlen != static_cast<int>(plaintext->size())) {
516 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
517 return false;
518 }
519 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700520 const_cast<void*>(reinterpret_cast<const void*>(
521 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800522 logOpensslError();
523 return false;
524 }
525 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700526 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
527 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800528 logOpensslError();
529 return false;
530 }
531 if (outlen != 0) {
532 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
533 return false;
534 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000535 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000536}
537
Satya Tangirala351a4af2021-06-08 12:55:37 -0700538// Creates a directory at the given path |dir| and stores |key| in it, in such a
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700539// way that it can only be retrieved via Keystore (if no secret is given in
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000540// |auth|) or with the given secret (if a secret is given in |auth|). In the
541// former case, an attempt is made to make the key securely deletable. In the
542// latter case, secure deletion is expected to be handled at a higher level.
543//
544// If a storage binding seed has been set, then the storage binding seed will be
545// required to retrieve the key as well.
Satya Tangirala351a4af2021-06-08 12:55:37 -0700546static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000547 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
548 PLOG(ERROR) << "key mkdir " << dir;
549 return false;
550 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800551 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700552 std::string secdiscardable_hash;
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000553 if (auth.usesKeystore() &&
554 !createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash))
555 return false;
Eric Biggersf187f052022-10-13 03:50:21 +0000556 std::string appId = generateAppId(auth, secdiscardable_hash);
Paul Crowley320e5e12016-03-04 14:07:05 -0800557 std::string encryptedKey;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700558 if (auth.usesKeystore()) {
559 Keystore keystore;
560 if (!keystore) return false;
561 std::string ksKey;
562 if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
563 if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700564 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700565 if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) {
566 LOG(ERROR) << "encryptWithKeystoreKey failed";
567 return false;
568 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800569 } else {
David Andersone1791572021-11-05 18:57:49 -0700570 if (!encryptWithoutKeystore(appId, key, &encryptedKey)) {
571 LOG(ERROR) << "encryptWithoutKeystore failed";
572 return false;
573 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800574 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000575 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800576 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000577 return true;
578}
579
Paul Crowleyf71ace32016-06-02 11:01:19 -0700580bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100581 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700582 if (pathExists(key_path)) {
583 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
584 return false;
585 }
586 if (pathExists(tmp_path)) {
587 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
588 destroyKey(tmp_path); // May be partially created so ignore errors
589 }
590 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700591
Satya Tangirala0f890a92021-06-08 12:55:24 -0700592 if (!RenameKeyDir(tmp_path, key_path)) return false;
593
Eric Biggers3345a2a2021-02-16 15:59:17 -0800594 if (!FsyncParentDirectory(key_path)) return false;
Eric Biggers8c1659e2022-09-06 21:29:14 +0000595 LOG(DEBUG) << "Stored key " << key_path;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700596 return true;
597}
598
Eric Biggersf74373b2020-11-05 19:58:26 -0800599bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000600 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800601 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000602 if (version != kCurrentVersion) {
603 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
604 return false;
605 }
Paul Crowley26a53882017-10-26 11:16:39 -0700606 std::string secdiscardable_hash;
607 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Eric Biggersf187f052022-10-13 03:50:21 +0000608 std::string appId = generateAppId(auth, secdiscardable_hash);
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000609 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800610 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700611 if (auth.usesKeystore()) {
612 Keystore keystore;
613 if (!keystore) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700614 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700615 if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) {
616 LOG(ERROR) << "decryptWithKeystoreKey failed";
617 return false;
618 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800619 } else {
David Andersone1791572021-11-05 18:57:49 -0700620 if (!decryptWithoutKeystore(appId, encryptedMessage, key)) {
621 LOG(ERROR) << "decryptWithoutKeystore failed";
622 return false;
623 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800624 }
625 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000626}
627
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700628static bool DeleteKeystoreKey(const std::string& blob_file) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800629 std::string blob;
630 if (!readFileToString(blob_file, &blob)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700631 Keystore keystore;
632 if (!keystore) return false;
633 LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
634 if (!keystore.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000635 return true;
636}
637
Rubin Xu2436e272017-04-27 20:43:10 +0100638bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700639 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100640 LOG(ERROR) << "secdiscard failed";
641 return false;
642 }
643 return true;
644}
645
Paul Crowleydf528a72016-03-09 09:31:37 -0800646static bool recursiveDeleteKey(const std::string& dir) {
647 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000648 LOG(ERROR) << "recursive delete failed";
649 return false;
650 }
651 return true;
652}
653
Paul Crowleydf528a72016-03-09 09:31:37 -0800654bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000655 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800656
657 CancelPendingKeyCommit(dir);
658
Paul Crowleyff19b052017-10-26 11:28:55 -0700659 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700660 kSecdiscardPath,
661 "--",
662 dir + "/" + kFn_encrypted_key,
663 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700664 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800665 // Try each thing, even if previous things failed.
666
667 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
668 auto blob_file = dir + "/" + fn;
669 if (pathExists(blob_file)) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700670 success &= DeleteKeystoreKey(blob_file);
Eric Biggersf74373b2020-11-05 19:58:26 -0800671 secdiscard_cmd.push_back(blob_file);
672 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700673 }
674 if (ForkExecvp(secdiscard_cmd) != 0) {
675 LOG(ERROR) << "secdiscard failed";
676 success = false;
677 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000678 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000679 return success;
680}
681
Seth Moore5a43d612021-01-19 17:51:51 +0000682bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
683 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
684 switch (storage_binding_info.state) {
685 case StorageBindingInfo::State::UNINITIALIZED:
686 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
687 storage_binding_info.seed = seed;
Keith Moke8600252021-09-01 18:37:48 +0000688 android::base::SetProperty("vold.storage_seed_bound", "1");
Seth Moore5a43d612021-01-19 17:51:51 +0000689 return true;
690 case StorageBindingInfo::State::IN_USE:
691 LOG(ERROR) << "key storage binding seed already set";
692 return false;
693 case StorageBindingInfo::State::NOT_USED:
694 LOG(ERROR) << "key storage already in use without binding";
695 return false;
696 }
697 return false;
698}
699
Paul Crowley1ef25582016-01-21 20:26:12 +0000700} // namespace vold
701} // namespace android