blob: 125ee2bc37b051d42b185385bf15402875f5ea93 [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
Pig654cdd12020-09-25 22:56:33 +080068static const int32_t KM_TAG_FBE_ICE = static_cast<int32_t>(7 << 28) | 16201;
69
Seth Moore5a43d612021-01-19 17:51:51 +000070namespace {
71
72// Storage binding info for ensuring key encryption keys include a
73// platform-provided seed in their derivation.
74struct StorageBindingInfo {
75 enum class State {
76 UNINITIALIZED,
77 IN_USE, // key storage keys are bound to seed
78 NOT_USED, // key storage keys are NOT bound to seed
79 };
80
81 // Binding seed mixed into all key storage keys.
82 std::vector<uint8_t> seed;
83
84 // State tracker for the key storage key binding.
85 State state = State::UNINITIALIZED;
86
87 std::mutex guard;
88};
89
90// Never freed as the dtor is non-trivial.
91StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
92
93} // namespace
94
Paul Crowley13ffd8e2016-01-27 14:30:22 +000095static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000096 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080097 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
98 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000099 return false;
100 }
101 return true;
102}
103
Paul Crowley26a53882017-10-26 11:16:39 -0700104static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000105 SHA512_CTX c;
106
107 SHA512_Init(&c);
108 // Personalise the hashing by introducing a fixed prefix.
109 // Hashing applications should use personalization except when there is a
110 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800111 std::string hashingPrefix = prefix;
112 hashingPrefix.resize(SHA512_CBLOCK);
113 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
114 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700115 res->assign(SHA512_DIGEST_LENGTH, '\0');
116 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000117}
118
Eric Biggers2d30b892022-07-28 18:06:42 +0000119static bool generateKeyStorageKey(Keystore& keystore, const std::string& appId, std::string* key) {
120 auto paramBuilder = km::AuthorizationSetBuilder()
121 .AesEncryptionKey(AES_KEY_BYTES * 8)
122 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
123 .Authorization(km::TAG_APPLICATION_ID, appId)
124 .Authorization(km::TAG_NO_AUTH_REQUIRED);
125 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersb2024e02021-03-15 12:44:36 -0700126 auto paramsWithRollback = paramBuilder;
127 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
128
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700129 if (!keystore.generateKey(paramsWithRollback, key)) {
130 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keystore "
Eric Biggersb2024e02021-03-15 12:44:36 -0700131 "doesn't support rollback resistance. Falling back to "
132 "non-rollback-resistant key.";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700133 if (!keystore.generateKey(paramBuilder, key)) return false;
Eric Biggersb2024e02021-03-15 12:44:36 -0700134 }
135 return true;
136}
137
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800138bool generateWrappedStorageKey(KeyBuffer* key) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700139 Keystore keystore;
140 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800141 std::string key_temp;
142 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800143 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Pig654cdd12020-09-25 22:56:33 +0800144
145 km::KeyParameter param1;
146 param1.tag = (km::Tag) (KM_TAG_FBE_ICE);
147 param1.value = km::KeyParameterValue::make<km::KeyParameterValue::boolValue>(true);
148 paramBuilder.push_back(param1);
149
Eric Biggers2d30b892022-07-28 18:06:42 +0000150 if (!keystore.generateKey(paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800151 *key = KeyBuffer(key_temp.size());
152 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
153 return true;
154}
155
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700156bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
157 Keystore keystore;
158 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800159 std::string key_temp;
160
Neeraj Soniabcc61f2020-02-26 15:59:27 +0530161 auto ret = keystore.exportKey(ksKey, &key_temp);
162 if (ret != km::ErrorCode::OK) {
163 if (ret == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
164 // TODO(b/187304488): Re-land the below logic. (keystore.upgradeKey() was removed)
165 return false;
166 /*
167 std::string kmKeyStr(reinterpret_cast<const char*>(ksKey.data()), ksKey.size());
168 std::string Keystr;
169 if (!keystore.upgradeKey(kmKeyStr, km::AuthorizationSet(), &Keystr)) return false;
170 KeyBuffer upgradedKey = KeyBuffer(Keystr.size());
171 memcpy(reinterpret_cast<void*>(upgradedKey.data()), Keystr.c_str(), upgradedKey.size());
172 ret = keystore.exportKey(upgradedKey, &key_temp);
173 if (ret != km::ErrorCode::OK) return false;
174 */
175 } else {
176 return false;
177 }
178 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800179 *key = KeyBuffer(key_temp.size());
180 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
181 return true;
182}
183
Satya Tangiralae1361712021-03-15 15:33:08 -0700184static km::AuthorizationSet beginParams(const std::string& appId) {
185 return km::AuthorizationSetBuilder()
186 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800187 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000188}
189
Paul Crowleydf528a72016-03-09 09:31:37 -0800190static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800191 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800192 PLOG(ERROR) << "Failed to read from " << filename;
193 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000194 }
195 return true;
196}
197
Paul Crowley26a53882017-10-26 11:16:39 -0700198static bool readRandomBytesOrLog(size_t count, std::string* out) {
199 auto status = ReadRandomBytes(count, *out);
200 if (status != OK) {
201 LOG(ERROR) << "Random read failed with status: " << status;
202 return false;
203 }
204 return true;
205}
206
207bool createSecdiscardable(const std::string& filename, std::string* hash) {
208 std::string secdiscardable;
209 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
210 if (!writeStringToFile(secdiscardable, filename)) return false;
211 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
212 return true;
213}
214
215bool readSecdiscardable(const std::string& filename, std::string* hash) {
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000216 if (pathExists(filename)) {
217 std::string secdiscardable;
218 if (!readFileToString(filename, &secdiscardable)) return false;
219 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
220 } else {
221 *hash = "";
222 }
Paul Crowley26a53882017-10-26 11:16:39 -0700223 return true;
224}
225
Eric Biggersf74373b2020-11-05 19:58:26 -0800226static std::mutex key_upgrade_lock;
227
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700228// List of key directories that have had their Keystore key upgraded during
Eric Biggersf74373b2020-11-05 19:58:26 -0800229// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
230// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
Eric Biggers107d21d2021-06-08 12:55:00 -0700231// A directory can be in this list at most once.
Eric Biggersf74373b2020-11-05 19:58:26 -0800232static std::vector<std::string> key_dirs_to_commit;
233
234// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700235// deletes the old key from Keystore.
236static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800237 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
238 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
239
240 std::string blob;
241 if (!readFileToString(blob_file, &blob)) return false;
242
243 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
244 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
245 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700246 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700247 // Ensure that the rename is persisted before deleting the Keystore key.
Eric Biggersf74373b2020-11-05 19:58:26 -0800248 if (!FsyncDirectory(dir)) return false;
249
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700250 if (!keystore || !keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800251 LOG(WARNING) << "Failed to delete old key " << blob_file
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700252 << " from Keystore; continuing anyway";
253 // Continue on, but the space in Keystore used by the old key won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800254 }
255 return true;
256}
257
Eric Biggersb615f3b2022-11-09 05:48:45 +0000258void DeferredCommitKeystoreKeys() {
259 LOG(INFO) << "Committing upgraded Keystore keys";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700260 Keystore keystore;
261 if (!keystore) {
262 LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
263 // Continue on, but the space in Keystore used by the old keys won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800264 }
265 std::lock_guard<std::mutex> lock(key_upgrade_lock);
266 for (auto& dir : key_dirs_to_commit) {
Eric Biggersb615f3b2022-11-09 05:48:45 +0000267 LOG(INFO) << "Committing upgraded Keystore key for " << dir;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700268 CommitUpgradedKey(keystore, dir);
Eric Biggersf74373b2020-11-05 19:58:26 -0800269 }
270 key_dirs_to_commit.clear();
Eric Biggersb615f3b2022-11-09 05:48:45 +0000271 LOG(INFO) << "Done committing upgraded Keystore keys";
Eric Biggersf74373b2020-11-05 19:58:26 -0800272}
273
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700274// Returns true if the Keystore key in |dir| has already been upgraded and is
Eric Biggersf74373b2020-11-05 19:58:26 -0800275// pending being committed. Assumes that key_upgrade_lock is held.
276static bool IsKeyCommitPending(const std::string& dir) {
277 for (const auto& dir_to_commit : key_dirs_to_commit) {
278 if (IsSameFile(dir, dir_to_commit)) return true;
279 }
280 return false;
281}
282
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700283// Schedules the upgraded Keystore key in |dir| to be committed later. Assumes
Eric Biggers107d21d2021-06-08 12:55:00 -0700284// that key_upgrade_lock is held and that a commit isn't already pending for the
285// directory.
Eric Biggersf74373b2020-11-05 19:58:26 -0800286static void ScheduleKeyCommit(const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800287 key_dirs_to_commit.push_back(dir);
288}
289
290static void CancelPendingKeyCommit(const std::string& dir) {
291 std::lock_guard<std::mutex> lock(key_upgrade_lock);
292 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
293 if (IsSameFile(*it, dir)) {
294 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
295 << " because it is being destroyed";
296 key_dirs_to_commit.erase(it);
297 break;
298 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700299 }
300}
301
Satya Tangirala0f890a92021-06-08 12:55:24 -0700302bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
Satya Tangirala9475b112021-05-13 00:43:03 -0700303 std::lock_guard<std::mutex> lock(key_upgrade_lock);
304
Eric Biggers107d21d2021-06-08 12:55:00 -0700305 // Find the entry in key_dirs_to_commit (if any) for this directory so that
306 // we can update it if the rename succeeds. We don't allow duplicates in
307 // this list, so there can be at most one such entry.
308 auto it = key_dirs_to_commit.begin();
309 for (; it != key_dirs_to_commit.end(); it++) {
310 if (IsSameFile(old_name, *it)) break;
311 }
312
Satya Tangirala0f890a92021-06-08 12:55:24 -0700313 if (rename(old_name.c_str(), new_name.c_str()) != 0) {
314 PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
315 << "\"";
316 return false;
317 }
Satya Tangirala9475b112021-05-13 00:43:03 -0700318
Eric Biggers107d21d2021-06-08 12:55:00 -0700319 if (it != key_dirs_to_commit.end()) *it = new_name;
320
Satya Tangirala9475b112021-05-13 00:43:03 -0700321 return true;
322}
323
Eric Biggersf74373b2020-11-05 19:58:26 -0800324// Deletes a leftover upgraded key, if present. An upgraded key can be left
325// over if an update failed, or if we rebooted before committing the key in a
326// freak accident. Either way, we can re-upgrade the key if we need to.
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700327static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800328 if (pathExists(path)) {
329 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
330 std::string blob;
331 if (!android::base::ReadFileToString(path, &blob)) {
332 LOG(WARNING) << "Failed to read leftover upgraded key " << path
333 << "; continuing anyway";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700334 } else if (!keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800335 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700336 << " from Keystore; continuing anyway";
Eric Biggersf74373b2020-11-05 19:58:26 -0800337 }
338 if (unlink(path.c_str()) != 0) {
339 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
340 << "; continuing anyway";
341 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700342 }
343}
344
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700345// Begins a Keystore operation using the key stored in |dir|.
346static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
347 const km::AuthorizationSet& keyParams,
348 const km::AuthorizationSet& opParams,
349 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700350 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100351 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800352
353 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
354 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
355
356 std::lock_guard<std::mutex> lock(key_upgrade_lock);
357
358 std::string blob;
359 bool already_upgraded = IsKeyCommitPending(dir);
360 if (already_upgraded) {
361 LOG(DEBUG)
362 << blob_file
363 << " was already upgraded and is waiting to be committed; using the upgraded blob";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700364 if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800365 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700366 DeleteUpgradedKey(keystore, upgraded_blob_file);
367 if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700368 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800369
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700370 auto opHandle = keystore.begin(blob, inParams, outParams);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800371 if (!opHandle) return opHandle;
372
373 // If key blob wasn't upgraded, nothing left to do.
374 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800375
376 if (already_upgraded) {
377 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
378 << " still requires upgrade";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700379 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800380 }
381 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800382 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700383 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800384 if (cp_needsCheckpoint()) {
385 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
386 << "; delaying commit due to checkpoint";
387 ScheduleKeyCommit(dir);
388 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700389 if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800390 LOG(INFO) << "Key upgraded: " << blob_file;
391 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800392 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700393}
394
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700395static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
396 const km::AuthorizationSet& keyParams, const KeyBuffer& message,
397 std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800398 km::AuthorizationSet opParams =
Haiping Yangc0a46c82021-08-23 01:24:25 +0000399 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700400 km::AuthorizationSet outParams;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700401 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700402 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700403 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800404 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700405 LOG(ERROR) << "GCM encryption but no nonce generated";
406 return false;
407 }
408 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800409 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700410 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
411 std::string body;
412 if (!opHandle.updateCompletely(message, &body)) return false;
413
414 std::string mac;
415 if (!opHandle.finish(&mac)) return false;
416 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
417 *ciphertext = nonce + body + mac;
418 return true;
419}
420
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700421static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
422 const km::AuthorizationSet& keyParams,
423 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800424 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700425 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800426 auto opParams = km::AuthorizationSetBuilder()
427 .Authorization(km::TAG_NONCE, nonce)
428 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700429 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700430 if (!opHandle) return false;
431 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
432 if (!opHandle.finish(nullptr)) return false;
433 return true;
434}
435
Eric Biggersf187f052022-10-13 03:50:21 +0000436static std::string generateAppId(const KeyAuthentication& auth,
437 const std::string& secdiscardable_hash) {
438 std::string appId = secdiscardable_hash + auth.secret;
Seth Moore5a43d612021-01-19 17:51:51 +0000439
440 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
441 switch (storage_binding_info.state) {
442 case StorageBindingInfo::State::UNINITIALIZED:
443 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
444 break;
445 case StorageBindingInfo::State::IN_USE:
Eric Biggersf187f052022-10-13 03:50:21 +0000446 appId.append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
Seth Moore5a43d612021-01-19 17:51:51 +0000447 break;
448 case StorageBindingInfo::State::NOT_USED:
449 // noop
450 break;
451 }
Eric Biggersf187f052022-10-13 03:50:21 +0000452 return appId;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800453}
454
455static void logOpensslError() {
456 LOG(ERROR) << "Openssl error: " << ERR_get_error();
457}
458
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700459static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
460 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700461 std::string key;
462 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800463 key.resize(AES_KEY_BYTES);
464 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
465 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
466 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
467 if (!ctx) {
468 logOpensslError();
469 return false;
470 }
471 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700472 reinterpret_cast<const uint8_t*>(key.data()),
473 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800474 logOpensslError();
475 return false;
476 }
477 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
478 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700479 if (1 != EVP_EncryptUpdate(
480 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
481 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800482 logOpensslError();
483 return false;
484 }
485 if (outlen != static_cast<int>(plaintext.size())) {
486 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
487 return false;
488 }
Shawn Willden785365b2018-01-20 09:37:36 -0700489 if (1 != EVP_EncryptFinal_ex(
490 ctx.get(),
491 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
492 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800493 logOpensslError();
494 return false;
495 }
496 if (outlen != 0) {
497 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
498 return false;
499 }
500 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700501 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
502 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800503 logOpensslError();
504 return false;
505 }
506 return true;
507}
508
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700509static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
510 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800511 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
512 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
513 return false;
514 }
Paul Crowley26a53882017-10-26 11:16:39 -0700515 std::string key;
516 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800517 key.resize(AES_KEY_BYTES);
518 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
519 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
520 if (!ctx) {
521 logOpensslError();
522 return false;
523 }
524 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700525 reinterpret_cast<const uint8_t*>(key.data()),
526 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800527 logOpensslError();
528 return false;
529 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100530 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800531 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700532 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
533 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
534 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800535 logOpensslError();
536 return false;
537 }
538 if (outlen != static_cast<int>(plaintext->size())) {
539 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
540 return false;
541 }
542 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700543 const_cast<void*>(reinterpret_cast<const void*>(
544 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800545 logOpensslError();
546 return false;
547 }
548 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700549 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
550 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800551 logOpensslError();
552 return false;
553 }
554 if (outlen != 0) {
555 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
556 return false;
557 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000558 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000559}
560
Satya Tangirala351a4af2021-06-08 12:55:37 -0700561// Creates a directory at the given path |dir| and stores |key| in it, in such a
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700562// way that it can only be retrieved via Keystore (if no secret is given in
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000563// |auth|) or with the given secret (if a secret is given in |auth|). In the
564// former case, an attempt is made to make the key securely deletable. In the
565// latter case, secure deletion is expected to be handled at a higher level.
566//
567// If a storage binding seed has been set, then the storage binding seed will be
568// required to retrieve the key as well.
Satya Tangirala351a4af2021-06-08 12:55:37 -0700569static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000570 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
571 PLOG(ERROR) << "key mkdir " << dir;
572 return false;
573 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800574 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700575 std::string secdiscardable_hash;
Eric Biggers08f4bdf2022-10-07 05:19:50 +0000576 if (auth.usesKeystore() &&
577 !createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash))
578 return false;
Eric Biggersf187f052022-10-13 03:50:21 +0000579 std::string appId = generateAppId(auth, secdiscardable_hash);
Paul Crowley320e5e12016-03-04 14:07:05 -0800580 std::string encryptedKey;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700581 if (auth.usesKeystore()) {
582 Keystore keystore;
583 if (!keystore) return false;
584 std::string ksKey;
585 if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
586 if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700587 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700588 if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) {
589 LOG(ERROR) << "encryptWithKeystoreKey failed";
590 return false;
591 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800592 } else {
David Andersone1791572021-11-05 18:57:49 -0700593 if (!encryptWithoutKeystore(appId, key, &encryptedKey)) {
594 LOG(ERROR) << "encryptWithoutKeystore failed";
595 return false;
596 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800597 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000598 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800599 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000600 return true;
601}
602
Paul Crowleyf71ace32016-06-02 11:01:19 -0700603bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100604 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700605 if (pathExists(key_path)) {
606 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
607 return false;
608 }
609 if (pathExists(tmp_path)) {
610 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
611 destroyKey(tmp_path); // May be partially created so ignore errors
612 }
613 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700614
Satya Tangirala0f890a92021-06-08 12:55:24 -0700615 if (!RenameKeyDir(tmp_path, key_path)) return false;
616
Eric Biggers3345a2a2021-02-16 15:59:17 -0800617 if (!FsyncParentDirectory(key_path)) return false;
Eric Biggers8c1659e2022-09-06 21:29:14 +0000618 LOG(DEBUG) << "Stored key " << key_path;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700619 return true;
620}
621
Eric Biggersf74373b2020-11-05 19:58:26 -0800622bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000623 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800624 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000625 if (version != kCurrentVersion) {
626 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
627 return false;
628 }
Paul Crowley26a53882017-10-26 11:16:39 -0700629 std::string secdiscardable_hash;
630 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Eric Biggersf187f052022-10-13 03:50:21 +0000631 std::string appId = generateAppId(auth, secdiscardable_hash);
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000632 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800633 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700634 if (auth.usesKeystore()) {
635 Keystore keystore;
636 if (!keystore) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700637 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700638 if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) {
639 LOG(ERROR) << "decryptWithKeystoreKey failed";
640 return false;
641 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800642 } else {
David Andersone1791572021-11-05 18:57:49 -0700643 if (!decryptWithoutKeystore(appId, encryptedMessage, key)) {
644 LOG(ERROR) << "decryptWithoutKeystore failed";
645 return false;
646 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800647 }
648 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000649}
650
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700651static bool DeleteKeystoreKey(const std::string& blob_file) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800652 std::string blob;
653 if (!readFileToString(blob_file, &blob)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700654 Keystore keystore;
655 if (!keystore) return false;
656 LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
657 if (!keystore.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000658 return true;
659}
660
Rubin Xu2436e272017-04-27 20:43:10 +0100661bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700662 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100663 LOG(ERROR) << "secdiscard failed";
664 return false;
665 }
666 return true;
667}
668
Paul Crowleydf528a72016-03-09 09:31:37 -0800669static bool recursiveDeleteKey(const std::string& dir) {
670 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000671 LOG(ERROR) << "recursive delete failed";
672 return false;
673 }
674 return true;
675}
676
Paul Crowleydf528a72016-03-09 09:31:37 -0800677bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000678 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800679
680 CancelPendingKeyCommit(dir);
681
Paul Crowleyff19b052017-10-26 11:28:55 -0700682 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700683 kSecdiscardPath,
684 "--",
685 dir + "/" + kFn_encrypted_key,
Paul Crowleyff19b052017-10-26 11:28:55 -0700686 };
Eric Biggers73e29362023-03-03 19:39:24 +0000687 auto secdiscardable = dir + "/" + kFn_secdiscardable;
688 if (pathExists(secdiscardable)) {
689 secdiscard_cmd.push_back(secdiscardable);
690 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800691 // Try each thing, even if previous things failed.
692
693 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
694 auto blob_file = dir + "/" + fn;
695 if (pathExists(blob_file)) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700696 success &= DeleteKeystoreKey(blob_file);
Eric Biggersf74373b2020-11-05 19:58:26 -0800697 secdiscard_cmd.push_back(blob_file);
698 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700699 }
700 if (ForkExecvp(secdiscard_cmd) != 0) {
701 LOG(ERROR) << "secdiscard failed";
702 success = false;
703 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000704 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000705 return success;
706}
707
Seth Moore5a43d612021-01-19 17:51:51 +0000708bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
709 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
710 switch (storage_binding_info.state) {
711 case StorageBindingInfo::State::UNINITIALIZED:
712 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
713 storage_binding_info.seed = seed;
Keith Moke8600252021-09-01 18:37:48 +0000714 android::base::SetProperty("vold.storage_seed_bound", "1");
Seth Moore5a43d612021-01-19 17:51:51 +0000715 return true;
716 case StorageBindingInfo::State::IN_USE:
717 LOG(ERROR) << "key storage binding seed already set";
718 return false;
719 case StorageBindingInfo::State::NOT_USED:
720 LOG(ERROR) << "key storage already in use without binding";
721 return false;
722 }
723 return false;
724}
725
Paul Crowley1ef25582016-01-21 20:26:12 +0000726} // namespace vold
727} // namespace android