blob: e8f8b913aa07c9a80d1bccbdc3b4f669bc6e35e4 [file] [log] [blame]
Paul Crowley1ef25582016-01-21 20:26:12 +00001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "KeyStorage.h"
18
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070019#include "Checkpoint.h"
Eric Biggersd86a8ab2021-06-15 11:34:00 -070020#include "Keystore.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000021#include "Utils.h"
22
Eric Biggersf74373b2020-11-05 19:58:26 -080023#include <algorithm>
Seth Moore5a43d612021-01-19 17:51:51 +000024#include <memory>
25#include <mutex>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070026#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000027#include <vector>
28
29#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070030#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000031#include <sys/stat.h>
32#include <sys/types.h>
33#include <sys/wait.h>
34#include <unistd.h>
35
Paul Crowley6ab2cab2017-01-04 22:32:40 -080036#include <openssl/err.h>
37#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000038#include <openssl/sha.h>
39
40#include <android-base/file.h>
41#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070042#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070043#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000044
Paul Crowley63c18d32016-02-10 14:02:47 +000045#include <cutils/properties.h>
46
Paul Crowley1ef25582016-01-21 20:26:12 +000047namespace android {
48namespace vold {
49
Satya Tangiralae1361712021-03-15 15:33:08 -070050const KeyAuthentication kEmptyAuthentication{""};
Paul Crowley05720802016-02-08 15:55:41 +000051
Paul Crowley1ef25582016-01-21 20:26:12 +000052static constexpr size_t AES_KEY_BYTES = 32;
53static constexpr size_t GCM_NONCE_BYTES = 12;
54static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080055static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
Paul Crowleyb3de3372016-04-27 12:58:41 -070056
Paul Crowley05720802016-02-08 15:55:41 +000057static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000058static const char* kRmPath = "/system/bin/rm";
59static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000060static const char* kStretch_none = "none";
61static const char* kStretch_nopassword = "nopassword";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080062static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
63static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000064static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000065static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070066static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000067static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000068static const char* kFn_stretching = "stretching";
69static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000070
Pigadb91992020-09-25 22:56:33 +080071static const int32_t KM_TAG_FBE_ICE = static_cast<int32_t>(7 << 28) | 16201;
72
Seth Moore5a43d612021-01-19 17:51:51 +000073namespace {
74
75// Storage binding info for ensuring key encryption keys include a
76// platform-provided seed in their derivation.
77struct StorageBindingInfo {
78 enum class State {
79 UNINITIALIZED,
80 IN_USE, // key storage keys are bound to seed
81 NOT_USED, // key storage keys are NOT bound to seed
82 };
83
84 // Binding seed mixed into all key storage keys.
85 std::vector<uint8_t> seed;
86
87 // State tracker for the key storage key binding.
88 State state = State::UNINITIALIZED;
89
90 std::mutex guard;
91};
92
93// Never freed as the dtor is non-trivial.
94StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
95
96} // namespace
97
Paul Crowley13ffd8e2016-01-27 14:30:22 +000098static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000099 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800100 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
101 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +0000102 return false;
103 }
104 return true;
105}
106
Paul Crowley26a53882017-10-26 11:16:39 -0700107static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000108 SHA512_CTX c;
109
110 SHA512_Init(&c);
111 // Personalise the hashing by introducing a fixed prefix.
112 // Hashing applications should use personalization except when there is a
113 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800114 std::string hashingPrefix = prefix;
115 hashingPrefix.resize(SHA512_CBLOCK);
116 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
117 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700118 res->assign(SHA512_DIGEST_LENGTH, '\0');
119 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000120}
121
Eric Biggerse11788d2022-07-28 18:06:42 +0000122static bool generateKeyStorageKey(Keystore& keystore, const std::string& appId, std::string* key) {
123 auto paramBuilder = km::AuthorizationSetBuilder()
124 .AesEncryptionKey(AES_KEY_BYTES * 8)
125 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
126 .Authorization(km::TAG_APPLICATION_ID, appId)
127 .Authorization(km::TAG_NO_AUTH_REQUIRED);
128 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersb2024e02021-03-15 12:44:36 -0700129 auto paramsWithRollback = paramBuilder;
130 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
131
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700132 if (!keystore.generateKey(paramsWithRollback, key)) {
133 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keystore "
Eric Biggersb2024e02021-03-15 12:44:36 -0700134 "doesn't support rollback resistance. Falling back to "
135 "non-rollback-resistant key.";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700136 if (!keystore.generateKey(paramBuilder, key)) return false;
Eric Biggersb2024e02021-03-15 12:44:36 -0700137 }
138 return true;
139}
140
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800141bool generateWrappedStorageKey(KeyBuffer* key) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700142 Keystore keystore;
143 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800144 std::string key_temp;
145 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800146 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Pigadb91992020-09-25 22:56:33 +0800147
148 km::KeyParameter param1;
149 param1.tag = (km::Tag) (KM_TAG_FBE_ICE);
150 param1.value = km::KeyParameterValue::make<km::KeyParameterValue::boolValue>(true);
151 paramBuilder.push_back(param1);
152
Eric Biggerse11788d2022-07-28 18:06:42 +0000153 if (!keystore.generateKey(paramBuilder, &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
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700159bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
160 Keystore keystore;
161 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800162 std::string key_temp;
163
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700164 if (!keystore.exportKey(ksKey, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800165 *key = KeyBuffer(key_temp.size());
166 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
167 return true;
168}
169
Satya Tangiralae1361712021-03-15 15:33:08 -0700170static km::AuthorizationSet beginParams(const std::string& appId) {
171 return km::AuthorizationSetBuilder()
172 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800173 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000174}
175
Paul Crowleydf528a72016-03-09 09:31:37 -0800176static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800177 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800178 PLOG(ERROR) << "Failed to read from " << filename;
179 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000180 }
181 return true;
182}
183
Paul Crowley26a53882017-10-26 11:16:39 -0700184static bool readRandomBytesOrLog(size_t count, std::string* out) {
185 auto status = ReadRandomBytes(count, *out);
186 if (status != OK) {
187 LOG(ERROR) << "Random read failed with status: " << status;
188 return false;
189 }
190 return true;
191}
192
193bool createSecdiscardable(const std::string& filename, std::string* hash) {
194 std::string secdiscardable;
195 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
196 if (!writeStringToFile(secdiscardable, filename)) return false;
197 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
198 return true;
199}
200
201bool readSecdiscardable(const std::string& filename, std::string* hash) {
202 std::string secdiscardable;
203 if (!readFileToString(filename, &secdiscardable)) return false;
204 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
205 return true;
206}
207
Eric Biggersf74373b2020-11-05 19:58:26 -0800208static std::mutex key_upgrade_lock;
209
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700210// List of key directories that have had their Keystore key upgraded during
Eric Biggersf74373b2020-11-05 19:58:26 -0800211// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
212// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
Eric Biggers107d21d2021-06-08 12:55:00 -0700213// A directory can be in this list at most once.
Eric Biggersf74373b2020-11-05 19:58:26 -0800214static std::vector<std::string> key_dirs_to_commit;
215
216// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700217// deletes the old key from Keystore.
218static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800219 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
220 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
221
222 std::string blob;
223 if (!readFileToString(blob_file, &blob)) return false;
224
225 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
226 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
227 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700228 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700229 // Ensure that the rename is persisted before deleting the Keystore key.
Eric Biggersf74373b2020-11-05 19:58:26 -0800230 if (!FsyncDirectory(dir)) return false;
231
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700232 if (!keystore || !keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800233 LOG(WARNING) << "Failed to delete old key " << blob_file
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700234 << " from Keystore; continuing anyway";
235 // Continue on, but the space in Keystore used by the old key won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800236 }
237 return true;
238}
239
240static void DeferredCommitKeys() {
241 android::base::WaitForProperty("vold.checkpoint_committed", "1");
242 LOG(INFO) << "Committing upgraded keys";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700243 Keystore keystore;
244 if (!keystore) {
245 LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
246 // Continue on, but the space in Keystore used by the old keys won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800247 }
248 std::lock_guard<std::mutex> lock(key_upgrade_lock);
249 for (auto& dir : key_dirs_to_commit) {
250 LOG(INFO) << "Committing upgraded key " << dir;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700251 CommitUpgradedKey(keystore, dir);
Eric Biggersf74373b2020-11-05 19:58:26 -0800252 }
253 key_dirs_to_commit.clear();
254}
255
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700256// Returns true if the Keystore key in |dir| has already been upgraded and is
Eric Biggersf74373b2020-11-05 19:58:26 -0800257// pending being committed. Assumes that key_upgrade_lock is held.
258static bool IsKeyCommitPending(const std::string& dir) {
259 for (const auto& dir_to_commit : key_dirs_to_commit) {
260 if (IsSameFile(dir, dir_to_commit)) return true;
261 }
262 return false;
263}
264
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700265// Schedules the upgraded Keystore key in |dir| to be committed later. Assumes
Eric Biggers107d21d2021-06-08 12:55:00 -0700266// that key_upgrade_lock is held and that a commit isn't already pending for the
267// directory.
Eric Biggersf74373b2020-11-05 19:58:26 -0800268static void ScheduleKeyCommit(const std::string& dir) {
269 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
270 key_dirs_to_commit.push_back(dir);
271}
272
273static void CancelPendingKeyCommit(const std::string& dir) {
274 std::lock_guard<std::mutex> lock(key_upgrade_lock);
275 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
276 if (IsSameFile(*it, dir)) {
277 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
278 << " because it is being destroyed";
279 key_dirs_to_commit.erase(it);
280 break;
281 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700282 }
283}
284
Satya Tangirala0f890a92021-06-08 12:55:24 -0700285bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
Satya Tangirala9475b112021-05-13 00:43:03 -0700286 std::lock_guard<std::mutex> lock(key_upgrade_lock);
287
Eric Biggers107d21d2021-06-08 12:55:00 -0700288 // Find the entry in key_dirs_to_commit (if any) for this directory so that
289 // we can update it if the rename succeeds. We don't allow duplicates in
290 // this list, so there can be at most one such entry.
291 auto it = key_dirs_to_commit.begin();
292 for (; it != key_dirs_to_commit.end(); it++) {
293 if (IsSameFile(old_name, *it)) break;
294 }
295
Satya Tangirala0f890a92021-06-08 12:55:24 -0700296 if (rename(old_name.c_str(), new_name.c_str()) != 0) {
297 PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
298 << "\"";
299 return false;
300 }
Satya Tangirala9475b112021-05-13 00:43:03 -0700301
Eric Biggers107d21d2021-06-08 12:55:00 -0700302 if (it != key_dirs_to_commit.end()) *it = new_name;
303
Satya Tangirala9475b112021-05-13 00:43:03 -0700304 return true;
305}
306
Eric Biggersf74373b2020-11-05 19:58:26 -0800307// Deletes a leftover upgraded key, if present. An upgraded key can be left
308// over if an update failed, or if we rebooted before committing the key in a
309// freak accident. Either way, we can re-upgrade the key if we need to.
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700310static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800311 if (pathExists(path)) {
312 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
313 std::string blob;
314 if (!android::base::ReadFileToString(path, &blob)) {
315 LOG(WARNING) << "Failed to read leftover upgraded key " << path
316 << "; continuing anyway";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700317 } else if (!keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800318 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700319 << " from Keystore; continuing anyway";
Eric Biggersf74373b2020-11-05 19:58:26 -0800320 }
321 if (unlink(path.c_str()) != 0) {
322 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
323 << "; continuing anyway";
324 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700325 }
326}
327
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700328// Begins a Keystore operation using the key stored in |dir|.
329static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
330 const km::AuthorizationSet& keyParams,
331 const km::AuthorizationSet& opParams,
332 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700333 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100334 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800335
336 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
337 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
338
339 std::lock_guard<std::mutex> lock(key_upgrade_lock);
340
341 std::string blob;
342 bool already_upgraded = IsKeyCommitPending(dir);
343 if (already_upgraded) {
344 LOG(DEBUG)
345 << blob_file
346 << " was already upgraded and is waiting to be committed; using the upgraded blob";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700347 if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800348 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700349 DeleteUpgradedKey(keystore, upgraded_blob_file);
350 if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700351 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800352
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700353 auto opHandle = keystore.begin(blob, inParams, outParams);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800354 if (!opHandle) return opHandle;
355
356 // If key blob wasn't upgraded, nothing left to do.
357 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800358
359 if (already_upgraded) {
360 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
361 << " still requires upgrade";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700362 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800363 }
364 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800365 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700366 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800367 if (cp_needsCheckpoint()) {
368 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
369 << "; delaying commit due to checkpoint";
370 ScheduleKeyCommit(dir);
371 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700372 if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800373 LOG(INFO) << "Key upgraded: " << blob_file;
374 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800375 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700376}
377
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700378static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
379 const km::AuthorizationSet& keyParams, const KeyBuffer& message,
380 std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800381 km::AuthorizationSet opParams =
Haiping Yangc0a46c82021-08-23 01:24:25 +0000382 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700383 km::AuthorizationSet outParams;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700384 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700385 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700386 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800387 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700388 LOG(ERROR) << "GCM encryption but no nonce generated";
389 return false;
390 }
391 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800392 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700393 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
394 std::string body;
395 if (!opHandle.updateCompletely(message, &body)) return false;
396
397 std::string mac;
398 if (!opHandle.finish(&mac)) return false;
399 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
400 *ciphertext = nonce + body + mac;
401 return true;
402}
403
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700404static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
405 const km::AuthorizationSet& keyParams,
406 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800407 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700408 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800409 auto opParams = km::AuthorizationSetBuilder()
410 .Authorization(km::TAG_NONCE, nonce)
411 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700412 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700413 if (!opHandle) return false;
414 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
415 if (!opHandle.finish(nullptr)) return false;
416 return true;
417}
418
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800419static std::string getStretching(const KeyAuthentication& auth) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700420 if (auth.usesKeystore()) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800421 return kStretch_nopassword;
422 } else {
Satya Tangiralae1361712021-03-15 15:33:08 -0700423 return kStretch_none;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800424 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000425}
426
Paul Crowleydf528a72016-03-09 09:31:37 -0800427static bool stretchSecret(const std::string& stretching, const std::string& secret,
Satya Tangirala478cea92021-04-07 14:30:25 -0700428 std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000429 if (stretching == kStretch_nopassword) {
430 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800431 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000432 // Continue anyway
433 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800434 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000435 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800436 *stretched = secret;
Paul Crowley63c18d32016-02-10 14:02:47 +0000437 } else {
438 LOG(ERROR) << "Unknown stretching type: " << stretching;
439 return false;
440 }
441 return true;
442}
443
Paul Crowleydf528a72016-03-09 09:31:37 -0800444static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Satya Tangirala478cea92021-04-07 14:30:25 -0700445 const std::string& secdiscardable_hash, std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000446 std::string stretched;
Satya Tangirala478cea92021-04-07 14:30:25 -0700447 if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700448 *appId = secdiscardable_hash + stretched;
Seth Moore5a43d612021-01-19 17:51:51 +0000449
450 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
451 switch (storage_binding_info.state) {
452 case StorageBindingInfo::State::UNINITIALIZED:
453 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
454 break;
455 case StorageBindingInfo::State::IN_USE:
456 appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
457 break;
458 case StorageBindingInfo::State::NOT_USED:
459 // noop
460 break;
461 }
462
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800463 return true;
464}
465
466static void logOpensslError() {
467 LOG(ERROR) << "Openssl error: " << ERR_get_error();
468}
469
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700470static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
471 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700472 std::string key;
473 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800474 key.resize(AES_KEY_BYTES);
475 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
476 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
477 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
478 if (!ctx) {
479 logOpensslError();
480 return false;
481 }
482 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700483 reinterpret_cast<const uint8_t*>(key.data()),
484 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800485 logOpensslError();
486 return false;
487 }
488 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
489 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700490 if (1 != EVP_EncryptUpdate(
491 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
492 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800493 logOpensslError();
494 return false;
495 }
496 if (outlen != static_cast<int>(plaintext.size())) {
497 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
498 return false;
499 }
Shawn Willden785365b2018-01-20 09:37:36 -0700500 if (1 != EVP_EncryptFinal_ex(
501 ctx.get(),
502 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
503 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800504 logOpensslError();
505 return false;
506 }
507 if (outlen != 0) {
508 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
509 return false;
510 }
511 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700512 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
513 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800514 logOpensslError();
515 return false;
516 }
517 return true;
518}
519
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700520static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
521 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800522 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
523 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
524 return false;
525 }
Paul Crowley26a53882017-10-26 11:16:39 -0700526 std::string key;
527 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800528 key.resize(AES_KEY_BYTES);
529 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
530 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
531 if (!ctx) {
532 logOpensslError();
533 return false;
534 }
535 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700536 reinterpret_cast<const uint8_t*>(key.data()),
537 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800538 logOpensslError();
539 return false;
540 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100541 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800542 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700543 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
544 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
545 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800546 logOpensslError();
547 return false;
548 }
549 if (outlen != static_cast<int>(plaintext->size())) {
550 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
551 return false;
552 }
553 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700554 const_cast<void*>(reinterpret_cast<const void*>(
555 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800556 logOpensslError();
557 return false;
558 }
559 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700560 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
561 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800562 logOpensslError();
563 return false;
564 }
565 if (outlen != 0) {
566 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
567 return false;
568 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000569 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000570}
571
Satya Tangirala351a4af2021-06-08 12:55:37 -0700572// Creates a directory at the given path |dir| and stores |key| in it, in such a
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700573// way that it can only be retrieved via Keystore (if no secret is given in
Satya Tangirala351a4af2021-06-08 12:55:37 -0700574// |auth|) or with the given secret (if a secret is given in |auth|), and can be
575// securely deleted. If a storage binding seed has been set, then the storage
576// binding seed will be required to retrieve the key as well.
577static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000578 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
579 PLOG(ERROR) << "key mkdir " << dir;
580 return false;
581 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800582 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700583 std::string secdiscardable_hash;
584 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800585 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800586 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800587 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700588 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800589 std::string encryptedKey;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700590 if (auth.usesKeystore()) {
591 Keystore keystore;
592 if (!keystore) return false;
593 std::string ksKey;
594 if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
595 if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700596 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700597 if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) {
598 LOG(ERROR) << "encryptWithKeystoreKey failed";
599 return false;
600 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800601 } else {
David Andersone1791572021-11-05 18:57:49 -0700602 if (!encryptWithoutKeystore(appId, key, &encryptedKey)) {
603 LOG(ERROR) << "encryptWithoutKeystore failed";
604 return false;
605 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800606 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000607 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800608 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000609 return true;
610}
611
Paul Crowleyf71ace32016-06-02 11:01:19 -0700612bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100613 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700614 if (pathExists(key_path)) {
615 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
616 return false;
617 }
618 if (pathExists(tmp_path)) {
619 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
620 destroyKey(tmp_path); // May be partially created so ignore errors
621 }
622 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700623
Satya Tangirala0f890a92021-06-08 12:55:24 -0700624 if (!RenameKeyDir(tmp_path, key_path)) return false;
625
Eric Biggers3345a2a2021-02-16 15:59:17 -0800626 if (!FsyncParentDirectory(key_path)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700627 LOG(DEBUG) << "Created key: " << key_path;
628 return true;
629}
630
Eric Biggersf74373b2020-11-05 19:58:26 -0800631bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000632 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800633 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000634 if (version != kCurrentVersion) {
635 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
636 return false;
637 }
Paul Crowley26a53882017-10-26 11:16:39 -0700638 std::string secdiscardable_hash;
639 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000640 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800641 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800642 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700643 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000644 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800645 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700646 if (auth.usesKeystore()) {
647 Keystore keystore;
648 if (!keystore) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700649 km::AuthorizationSet keyParams = beginParams(appId);
David Andersone1791572021-11-05 18:57:49 -0700650 if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) {
651 LOG(ERROR) << "decryptWithKeystoreKey failed";
652 return false;
653 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800654 } else {
David Andersone1791572021-11-05 18:57:49 -0700655 if (!decryptWithoutKeystore(appId, encryptedMessage, key)) {
656 LOG(ERROR) << "decryptWithoutKeystore failed";
657 return false;
658 }
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800659 }
660 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000661}
662
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700663static bool DeleteKeystoreKey(const std::string& blob_file) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800664 std::string blob;
665 if (!readFileToString(blob_file, &blob)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700666 Keystore keystore;
667 if (!keystore) return false;
668 LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
669 if (!keystore.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000670 return true;
671}
672
Rubin Xu2436e272017-04-27 20:43:10 +0100673bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700674 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100675 LOG(ERROR) << "secdiscard failed";
676 return false;
677 }
678 return true;
679}
680
Paul Crowleydf528a72016-03-09 09:31:37 -0800681static bool recursiveDeleteKey(const std::string& dir) {
682 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000683 LOG(ERROR) << "recursive delete failed";
684 return false;
685 }
686 return true;
687}
688
Paul Crowleydf528a72016-03-09 09:31:37 -0800689bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000690 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800691
692 CancelPendingKeyCommit(dir);
693
Paul Crowleyff19b052017-10-26 11:28:55 -0700694 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700695 kSecdiscardPath,
696 "--",
697 dir + "/" + kFn_encrypted_key,
698 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700699 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800700 // Try each thing, even if previous things failed.
701
702 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
703 auto blob_file = dir + "/" + fn;
704 if (pathExists(blob_file)) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700705 success &= DeleteKeystoreKey(blob_file);
Eric Biggersf74373b2020-11-05 19:58:26 -0800706 secdiscard_cmd.push_back(blob_file);
707 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700708 }
709 if (ForkExecvp(secdiscard_cmd) != 0) {
710 LOG(ERROR) << "secdiscard failed";
711 success = false;
712 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000713 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000714 return success;
715}
716
Seth Moore5a43d612021-01-19 17:51:51 +0000717bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
718 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
719 switch (storage_binding_info.state) {
720 case StorageBindingInfo::State::UNINITIALIZED:
721 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
722 storage_binding_info.seed = seed;
Keith Moke8600252021-09-01 18:37:48 +0000723 android::base::SetProperty("vold.storage_seed_bound", "1");
Seth Moore5a43d612021-01-19 17:51:51 +0000724 return true;
725 case StorageBindingInfo::State::IN_USE:
726 LOG(ERROR) << "key storage binding seed already set";
727 return false;
728 case StorageBindingInfo::State::NOT_USED:
729 LOG(ERROR) << "key storage already in use without binding";
730 return false;
731 }
732 return false;
733}
734
Paul Crowley1ef25582016-01-21 20:26:12 +0000735} // namespace vold
736} // namespace android