blob: 5090b4e6ea9f3c74c6c6deb016989ab21cd220c4 [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>
Paul Crowley1ef25582016-01-21 20:26:12 +000026#include <vector>
27
28#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070029#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000030#include <sys/stat.h>
31#include <sys/types.h>
32#include <sys/wait.h>
33#include <unistd.h>
34
Paul Crowley6ab2cab2017-01-04 22:32:40 -080035#include <openssl/err.h>
36#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000037#include <openssl/sha.h>
38
39#include <android-base/file.h>
40#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070041#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070042#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000043
Paul Crowley63c18d32016-02-10 14:02:47 +000044#include <cutils/properties.h>
45
Paul Crowley1ef25582016-01-21 20:26:12 +000046namespace android {
47namespace vold {
48
Satya Tangiralae1361712021-03-15 15:33:08 -070049const KeyAuthentication kEmptyAuthentication{""};
Paul Crowley05720802016-02-08 15:55:41 +000050
Paul Crowley1ef25582016-01-21 20:26:12 +000051static constexpr size_t AES_KEY_BYTES = 32;
52static constexpr size_t GCM_NONCE_BYTES = 12;
53static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080054static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
Paul Crowleyb3de3372016-04-27 12:58:41 -070055
Paul Crowley05720802016-02-08 15:55:41 +000056static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000057static const char* kRmPath = "/system/bin/rm";
58static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080059static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
60static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000061static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000062static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070063static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000064static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000065static const char* kFn_version = "version";
Eric Biggersf187f052022-10-13 03:50:21 +000066// Note: old key directories may contain a file named "stretching".
Paul Crowley1ef25582016-01-21 20:26:12 +000067
Seth Moore5a43d612021-01-19 17:51:51 +000068namespace {
69
70// Storage binding info for ensuring key encryption keys include a
71// platform-provided seed in their derivation.
72struct StorageBindingInfo {
73 enum class State {
74 UNINITIALIZED,
75 IN_USE, // key storage keys are bound to seed
76 NOT_USED, // key storage keys are NOT bound to seed
77 };
78
79 // Binding seed mixed into all key storage keys.
80 std::vector<uint8_t> seed;
81
82 // State tracker for the key storage key binding.
83 State state = State::UNINITIALIZED;
84
85 std::mutex guard;
86};
87
88// Never freed as the dtor is non-trivial.
89StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
90
91} // namespace
92
Paul Crowley13ffd8e2016-01-27 14:30:22 +000093static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000094 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080095 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
96 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000097 return false;
98 }
99 return true;
100}
101
Paul Crowley26a53882017-10-26 11:16:39 -0700102static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000103 SHA512_CTX c;
104
105 SHA512_Init(&c);
106 // Personalise the hashing by introducing a fixed prefix.
107 // Hashing applications should use personalization except when there is a
108 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800109 std::string hashingPrefix = prefix;
110 hashingPrefix.resize(SHA512_CBLOCK);
111 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
112 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700113 res->assign(SHA512_DIGEST_LENGTH, '\0');
114 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000115}
116
Eric Biggers2d30b892022-07-28 18:06:42 +0000117static bool generateKeyStorageKey(Keystore& keystore, const std::string& appId, std::string* key) {
118 auto paramBuilder = km::AuthorizationSetBuilder()
119 .AesEncryptionKey(AES_KEY_BYTES * 8)
120 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
121 .Authorization(km::TAG_APPLICATION_ID, appId)
122 .Authorization(km::TAG_NO_AUTH_REQUIRED);
123 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersb2024e02021-03-15 12:44:36 -0700124 auto paramsWithRollback = paramBuilder;
125 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
126
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700127 if (!keystore.generateKey(paramsWithRollback, key)) {
128 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keystore "
Eric Biggersb2024e02021-03-15 12:44:36 -0700129 "doesn't support rollback resistance. Falling back to "
130 "non-rollback-resistant key.";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700131 if (!keystore.generateKey(paramBuilder, key)) return false;
Eric Biggersb2024e02021-03-15 12:44:36 -0700132 }
133 return true;
134}
135
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800136bool generateWrappedStorageKey(KeyBuffer* key) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700137 Keystore keystore;
138 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800139 std::string key_temp;
140 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800141 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Eric Biggers2d30b892022-07-28 18:06:42 +0000142 if (!keystore.generateKey(paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800143 *key = KeyBuffer(key_temp.size());
144 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
145 return true;
146}
147
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700148bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
149 Keystore keystore;
150 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800151 std::string key_temp;
152
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700153 if (!keystore.exportKey(ksKey, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800154 *key = KeyBuffer(key_temp.size());
155 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
156 return true;
157}
158
Satya Tangiralae1361712021-03-15 15:33:08 -0700159static km::AuthorizationSet beginParams(const std::string& appId) {
160 return km::AuthorizationSetBuilder()
161 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800162 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000163}
164
Paul Crowleydf528a72016-03-09 09:31:37 -0800165static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800166 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800167 PLOG(ERROR) << "Failed to read from " << filename;
168 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000169 }
170 return true;
171}
172
Paul Crowley26a53882017-10-26 11:16:39 -0700173static bool readRandomBytesOrLog(size_t count, std::string* out) {
174 auto status = ReadRandomBytes(count, *out);
175 if (status != OK) {
176 LOG(ERROR) << "Random read failed with status: " << status;
177 return false;
178 }
179 return true;
180}
181
182bool createSecdiscardable(const std::string& filename, std::string* hash) {
183 std::string secdiscardable;
184 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
185 if (!writeStringToFile(secdiscardable, filename)) return false;
186 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
187 return true;
188}
189
190bool readSecdiscardable(const std::string& filename, std::string* hash) {
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000191 if (pathExists(filename)) {
192 std::string secdiscardable;
193 if (!readFileToString(filename, &secdiscardable)) return false;
194 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
195 } else {
196 *hash = "";
197 }
Paul Crowley26a53882017-10-26 11:16:39 -0700198 return true;
199}
200
Eric Biggersf74373b2020-11-05 19:58:26 -0800201static std::mutex key_upgrade_lock;
202
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700203// List of key directories that have had their Keystore key upgraded during
Eric Biggersf74373b2020-11-05 19:58:26 -0800204// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
205// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
Eric Biggers107d21d2021-06-08 12:55:00 -0700206// A directory can be in this list at most once.
Eric Biggersf74373b2020-11-05 19:58:26 -0800207static std::vector<std::string> key_dirs_to_commit;
208
209// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700210// deletes the old key from Keystore.
211static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800212 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
213 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
214
215 std::string blob;
216 if (!readFileToString(blob_file, &blob)) return false;
217
218 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
219 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
220 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700221 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700222 // Ensure that the rename is persisted before deleting the Keystore key.
Eric Biggersf74373b2020-11-05 19:58:26 -0800223 if (!FsyncDirectory(dir)) return false;
224
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700225 if (!keystore || !keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800226 LOG(WARNING) << "Failed to delete old key " << blob_file
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700227 << " from Keystore; continuing anyway";
228 // Continue on, but the space in Keystore used by the old key won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800229 }
230 return true;
231}
232
Eric Biggersb615f3b2022-11-09 05:48:45 +0000233void DeferredCommitKeystoreKeys() {
234 LOG(INFO) << "Committing upgraded Keystore keys";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700235 Keystore keystore;
236 if (!keystore) {
237 LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
238 // Continue on, but the space in Keystore used by the old keys won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800239 }
240 std::lock_guard<std::mutex> lock(key_upgrade_lock);
241 for (auto& dir : key_dirs_to_commit) {
Eric Biggersb615f3b2022-11-09 05:48:45 +0000242 LOG(INFO) << "Committing upgraded Keystore key for " << dir;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700243 CommitUpgradedKey(keystore, dir);
Eric Biggersf74373b2020-11-05 19:58:26 -0800244 }
245 key_dirs_to_commit.clear();
Eric Biggersb615f3b2022-11-09 05:48:45 +0000246 LOG(INFO) << "Done committing upgraded Keystore keys";
Eric Biggersf74373b2020-11-05 19:58:26 -0800247}
248
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700249// Returns true if the Keystore key in |dir| has already been upgraded and is
Eric Biggersf74373b2020-11-05 19:58:26 -0800250// pending being committed. Assumes that key_upgrade_lock is held.
251static bool IsKeyCommitPending(const std::string& dir) {
252 for (const auto& dir_to_commit : key_dirs_to_commit) {
253 if (IsSameFile(dir, dir_to_commit)) return true;
254 }
255 return false;
256}
257
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700258// Schedules the upgraded Keystore key in |dir| to be committed later. Assumes
Eric Biggers107d21d2021-06-08 12:55:00 -0700259// that key_upgrade_lock is held and that a commit isn't already pending for the
260// directory.
Eric Biggersf74373b2020-11-05 19:58:26 -0800261static void ScheduleKeyCommit(const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800262 key_dirs_to_commit.push_back(dir);
263}
264
265static void CancelPendingKeyCommit(const std::string& dir) {
266 std::lock_guard<std::mutex> lock(key_upgrade_lock);
267 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
268 if (IsSameFile(*it, dir)) {
269 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
270 << " because it is being destroyed";
271 key_dirs_to_commit.erase(it);
272 break;
273 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700274 }
275}
276
Satya Tangirala0f890a92021-06-08 12:55:24 -0700277bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
Satya Tangirala9475b112021-05-13 00:43:03 -0700278 std::lock_guard<std::mutex> lock(key_upgrade_lock);
279
Eric Biggers107d21d2021-06-08 12:55:00 -0700280 // Find the entry in key_dirs_to_commit (if any) for this directory so that
281 // we can update it if the rename succeeds. We don't allow duplicates in
282 // this list, so there can be at most one such entry.
283 auto it = key_dirs_to_commit.begin();
284 for (; it != key_dirs_to_commit.end(); it++) {
285 if (IsSameFile(old_name, *it)) break;
286 }
287
Satya Tangirala0f890a92021-06-08 12:55:24 -0700288 if (rename(old_name.c_str(), new_name.c_str()) != 0) {
289 PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
290 << "\"";
291 return false;
292 }
Satya Tangirala9475b112021-05-13 00:43:03 -0700293
Eric Biggers107d21d2021-06-08 12:55:00 -0700294 if (it != key_dirs_to_commit.end()) *it = new_name;
295
Satya Tangirala9475b112021-05-13 00:43:03 -0700296 return true;
297}
298
Eric Biggersf74373b2020-11-05 19:58:26 -0800299// Deletes a leftover upgraded key, if present. An upgraded key can be left
300// over if an update failed, or if we rebooted before committing the key in a
301// freak accident. Either way, we can re-upgrade the key if we need to.
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700302static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800303 if (pathExists(path)) {
304 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
305 std::string blob;
306 if (!android::base::ReadFileToString(path, &blob)) {
307 LOG(WARNING) << "Failed to read leftover upgraded key " << path
308 << "; continuing anyway";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700309 } else if (!keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800310 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700311 << " from Keystore; continuing anyway";
Eric Biggersf74373b2020-11-05 19:58:26 -0800312 }
313 if (unlink(path.c_str()) != 0) {
314 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
315 << "; continuing anyway";
316 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700317 }
318}
319
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700320// Begins a Keystore operation using the key stored in |dir|.
321static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
322 const km::AuthorizationSet& keyParams,
323 const km::AuthorizationSet& opParams,
324 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700325 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100326 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800327
328 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
329 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
330
331 std::lock_guard<std::mutex> lock(key_upgrade_lock);
332
333 std::string blob;
334 bool already_upgraded = IsKeyCommitPending(dir);
335 if (already_upgraded) {
336 LOG(DEBUG)
337 << blob_file
338 << " was already upgraded and is waiting to be committed; using the upgraded blob";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700339 if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800340 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700341 DeleteUpgradedKey(keystore, upgraded_blob_file);
342 if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700343 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800344
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700345 auto opHandle = keystore.begin(blob, inParams, outParams);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800346 if (!opHandle) return opHandle;
347
348 // If key blob wasn't upgraded, nothing left to do.
349 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800350
351 if (already_upgraded) {
352 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
353 << " still requires upgrade";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700354 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800355 }
356 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800357 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700358 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800359 if (cp_needsCheckpoint()) {
360 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
361 << "; delaying commit due to checkpoint";
362 ScheduleKeyCommit(dir);
363 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700364 if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800365 LOG(INFO) << "Key upgraded: " << blob_file;
366 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800367 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700368}
369
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700370static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
371 const km::AuthorizationSet& keyParams, const KeyBuffer& message,
372 std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800373 km::AuthorizationSet opParams =
Haiping Yangc0a46c82021-08-23 01:24:25 +0000374 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700375 km::AuthorizationSet outParams;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700376 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700377 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700378 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800379 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700380 LOG(ERROR) << "GCM encryption but no nonce generated";
381 return false;
382 }
383 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800384 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700385 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
386 std::string body;
387 if (!opHandle.updateCompletely(message, &body)) return false;
388
389 std::string mac;
390 if (!opHandle.finish(&mac)) return false;
391 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
392 *ciphertext = nonce + body + mac;
393 return true;
394}
395
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700396static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
397 const km::AuthorizationSet& keyParams,
398 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800399 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700400 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800401 auto opParams = km::AuthorizationSetBuilder()
402 .Authorization(km::TAG_NONCE, nonce)
403 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700404 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700405 if (!opHandle) return false;
406 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
407 if (!opHandle.finish(nullptr)) return false;
408 return true;
409}
410
Eric Biggersf187f052022-10-13 03:50:21 +0000411static std::string generateAppId(const KeyAuthentication& auth,
412 const std::string& secdiscardable_hash) {
413 std::string appId = secdiscardable_hash + auth.secret;
Seth Moore5a43d612021-01-19 17:51:51 +0000414
415 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
416 switch (storage_binding_info.state) {
417 case StorageBindingInfo::State::UNINITIALIZED:
418 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
419 break;
420 case StorageBindingInfo::State::IN_USE:
Eric Biggersf187f052022-10-13 03:50:21 +0000421 appId.append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
Seth Moore5a43d612021-01-19 17:51:51 +0000422 break;
423 case StorageBindingInfo::State::NOT_USED:
424 // noop
425 break;
426 }
Eric Biggersf187f052022-10-13 03:50:21 +0000427 return appId;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800428}
429
430static void logOpensslError() {
431 LOG(ERROR) << "Openssl error: " << ERR_get_error();
432}
433
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700434static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
435 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700436 std::string key;
437 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800438 key.resize(AES_KEY_BYTES);
439 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
440 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
441 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
442 if (!ctx) {
443 logOpensslError();
444 return false;
445 }
446 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700447 reinterpret_cast<const uint8_t*>(key.data()),
448 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800449 logOpensslError();
450 return false;
451 }
452 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
453 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700454 if (1 != EVP_EncryptUpdate(
455 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
456 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800457 logOpensslError();
458 return false;
459 }
460 if (outlen != static_cast<int>(plaintext.size())) {
461 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
462 return false;
463 }
Shawn Willden785365b2018-01-20 09:37:36 -0700464 if (1 != EVP_EncryptFinal_ex(
465 ctx.get(),
466 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
467 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800468 logOpensslError();
469 return false;
470 }
471 if (outlen != 0) {
472 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
473 return false;
474 }
475 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700476 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
477 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800478 logOpensslError();
479 return false;
480 }
481 return true;
482}
483
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700484static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
485 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800486 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
487 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
488 return false;
489 }
Paul Crowley26a53882017-10-26 11:16:39 -0700490 std::string key;
491 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800492 key.resize(AES_KEY_BYTES);
493 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
494 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
495 if (!ctx) {
496 logOpensslError();
497 return false;
498 }
499 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700500 reinterpret_cast<const uint8_t*>(key.data()),
501 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800502 logOpensslError();
503 return false;
504 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100505 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800506 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700507 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
508 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
509 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800510 logOpensslError();
511 return false;
512 }
513 if (outlen != static_cast<int>(plaintext->size())) {
514 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
515 return false;
516 }
517 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700518 const_cast<void*>(reinterpret_cast<const void*>(
519 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800520 logOpensslError();
521 return false;
522 }
523 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700524 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
525 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800526 logOpensslError();
527 return false;
528 }
529 if (outlen != 0) {
530 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
531 return false;
532 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000533 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000534}
535
Satya Tangirala351a4af2021-06-08 12:55:37 -0700536// Creates a directory at the given path |dir| and stores |key| in it, in such a
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700537// way that it can only be retrieved via Keystore (if no secret is given in
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000538// |auth|) or with the given secret (if a secret is given in |auth|). In the
539// former case, an attempt is made to make the key securely deletable. In the
540// latter case, secure deletion is expected to be handled at a higher level.
541//
542// If a storage binding seed has been set, then the storage binding seed will be
543// required to retrieve the key as well.
Satya Tangirala351a4af2021-06-08 12:55:37 -0700544static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000545 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
546 PLOG(ERROR) << "key mkdir " << dir;
547 return false;
548 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800549 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700550 std::string secdiscardable_hash;
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000551 if (auth.usesKeystore() &&
552 !createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash))
553 return false;
Eric Biggersf187f052022-10-13 03:50:21 +0000554 std::string appId = generateAppId(auth, secdiscardable_hash);
Paul Crowley320e5e12016-03-04 14:07:05 -0800555 std::string encryptedKey;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700556 if (auth.usesKeystore()) {
557 Keystore keystore;
558 if (!keystore) return false;
559 std::string ksKey;
560 if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
561 if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700562 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700563 if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) {
564 LOG(ERROR) << "encryptWithKeystoreKey failed";
565 return false;
566 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800567 } else {
David Andersone1791572021-11-05 18:57:49 -0700568 if (!encryptWithoutKeystore(appId, key, &encryptedKey)) {
569 LOG(ERROR) << "encryptWithoutKeystore failed";
570 return false;
571 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800572 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000573 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800574 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000575 return true;
576}
577
Paul Crowleyf71ace32016-06-02 11:01:19 -0700578bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100579 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700580 if (pathExists(key_path)) {
581 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
582 return false;
583 }
584 if (pathExists(tmp_path)) {
585 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
586 destroyKey(tmp_path); // May be partially created so ignore errors
587 }
588 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700589
Satya Tangirala0f890a92021-06-08 12:55:24 -0700590 if (!RenameKeyDir(tmp_path, key_path)) return false;
591
Eric Biggers3345a2a2021-02-16 15:59:17 -0800592 if (!FsyncParentDirectory(key_path)) return false;
Eric Biggers8c1659e2022-09-06 21:29:14 +0000593 LOG(DEBUG) << "Stored key " << key_path;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700594 return true;
595}
596
Eric Biggersf74373b2020-11-05 19:58:26 -0800597bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000598 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800599 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000600 if (version != kCurrentVersion) {
601 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
602 return false;
603 }
Paul Crowley26a53882017-10-26 11:16:39 -0700604 std::string secdiscardable_hash;
605 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Eric Biggersf187f052022-10-13 03:50:21 +0000606 std::string appId = generateAppId(auth, secdiscardable_hash);
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000607 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800608 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700609 if (auth.usesKeystore()) {
610 Keystore keystore;
611 if (!keystore) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700612 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700613 if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) {
614 LOG(ERROR) << "decryptWithKeystoreKey failed";
615 return false;
616 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800617 } else {
David Andersone1791572021-11-05 18:57:49 -0700618 if (!decryptWithoutKeystore(appId, encryptedMessage, key)) {
619 LOG(ERROR) << "decryptWithoutKeystore failed";
620 return false;
621 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800622 }
623 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000624}
625
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700626static bool DeleteKeystoreKey(const std::string& blob_file) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800627 std::string blob;
628 if (!readFileToString(blob_file, &blob)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700629 Keystore keystore;
630 if (!keystore) return false;
631 LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
632 if (!keystore.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000633 return true;
634}
635
Rubin Xu2436e272017-04-27 20:43:10 +0100636bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700637 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100638 LOG(ERROR) << "secdiscard failed";
639 return false;
640 }
641 return true;
642}
643
Paul Crowleydf528a72016-03-09 09:31:37 -0800644static bool recursiveDeleteKey(const std::string& dir) {
645 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000646 LOG(ERROR) << "recursive delete failed";
647 return false;
648 }
649 return true;
650}
651
Paul Crowleydf528a72016-03-09 09:31:37 -0800652bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000653 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800654
655 CancelPendingKeyCommit(dir);
656
Paul Crowleyff19b052017-10-26 11:28:55 -0700657 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700658 kSecdiscardPath,
659 "--",
660 dir + "/" + kFn_encrypted_key,
Paul Crowleyff19b052017-10-26 11:28:55 -0700661 };
Eric Biggers73e29362023-03-03 19:39:24 +0000662 auto secdiscardable = dir + "/" + kFn_secdiscardable;
663 if (pathExists(secdiscardable)) {
664 secdiscard_cmd.push_back(secdiscardable);
665 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800666 // Try each thing, even if previous things failed.
667
668 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
669 auto blob_file = dir + "/" + fn;
670 if (pathExists(blob_file)) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700671 success &= DeleteKeystoreKey(blob_file);
Eric Biggersf74373b2020-11-05 19:58:26 -0800672 secdiscard_cmd.push_back(blob_file);
673 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700674 }
675 if (ForkExecvp(secdiscard_cmd) != 0) {
676 LOG(ERROR) << "secdiscard failed";
677 success = false;
678 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000679 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000680 return success;
681}
682
Seth Moore5a43d612021-01-19 17:51:51 +0000683bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
684 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
685 switch (storage_binding_info.state) {
686 case StorageBindingInfo::State::UNINITIALIZED:
687 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
688 storage_binding_info.seed = seed;
Keith Moke8600252021-09-01 18:37:48 +0000689 android::base::SetProperty("vold.storage_seed_bound", "1");
Seth Moore5a43d612021-01-19 17:51:51 +0000690 return true;
691 case StorageBindingInfo::State::IN_USE:
692 LOG(ERROR) << "key storage binding seed already set";
693 return false;
694 case StorageBindingInfo::State::NOT_USED:
695 LOG(ERROR) << "key storage already in use without binding";
696 return false;
697 }
698 return false;
699}
700
Paul Crowley1ef25582016-01-21 20:26:12 +0000701} // namespace vold
702} // namespace android