blob: ebaefa398028c55bd193e22700e45b97ae218ff1 [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 Crowley63c18d32016-02-10 14:02:47 +000021#include "ScryptParameters.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000022#include "Utils.h"
23
Eric Biggersf74373b2020-11-05 19:58:26 -080024#include <algorithm>
Seth Moore5a43d612021-01-19 17:51:51 +000025#include <memory>
26#include <mutex>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070027#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000028#include <vector>
29
30#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070031#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000032#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/wait.h>
35#include <unistd.h>
36
Paul Crowley6ab2cab2017-01-04 22:32:40 -080037#include <openssl/err.h>
38#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000039#include <openssl/sha.h>
40
41#include <android-base/file.h>
42#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070043#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070044#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000045
Paul Crowley63c18d32016-02-10 14:02:47 +000046#include <cutils/properties.h>
47
Paul Crowley63c18d32016-02-10 14:02:47 +000048extern "C" {
49
50#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000051}
52
Paul Crowley1ef25582016-01-21 20:26:12 +000053namespace android {
54namespace vold {
55
Satya Tangiralae1361712021-03-15 15:33:08 -070056const KeyAuthentication kEmptyAuthentication{""};
Paul Crowley05720802016-02-08 15:55:41 +000057
Paul Crowley1ef25582016-01-21 20:26:12 +000058static constexpr size_t AES_KEY_BYTES = 32;
59static constexpr size_t GCM_NONCE_BYTES = 12;
60static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080061static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
Paul Crowleyb3de3372016-04-27 12:58:41 -070062
Paul Crowley05720802016-02-08 15:55:41 +000063static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000064static const char* kRmPath = "/system/bin/rm";
65static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000066static const char* kStretch_none = "none";
67static const char* kStretch_nopassword = "nopassword";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080068static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
69static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000070static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000071static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070072static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000073static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000074static const char* kFn_stretching = "stretching";
75static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000076
Seth Moore5a43d612021-01-19 17:51:51 +000077namespace {
78
79// Storage binding info for ensuring key encryption keys include a
80// platform-provided seed in their derivation.
81struct StorageBindingInfo {
82 enum class State {
83 UNINITIALIZED,
84 IN_USE, // key storage keys are bound to seed
85 NOT_USED, // key storage keys are NOT bound to seed
86 };
87
88 // Binding seed mixed into all key storage keys.
89 std::vector<uint8_t> seed;
90
91 // State tracker for the key storage key binding.
92 State state = State::UNINITIALIZED;
93
94 std::mutex guard;
95};
96
97// Never freed as the dtor is non-trivial.
98StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
99
100} // namespace
101
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000102static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000103 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800104 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
105 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +0000106 return false;
107 }
108 return true;
109}
110
Paul Crowley26a53882017-10-26 11:16:39 -0700111static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000112 SHA512_CTX c;
113
114 SHA512_Init(&c);
115 // Personalise the hashing by introducing a fixed prefix.
116 // Hashing applications should use personalization except when there is a
117 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800118 std::string hashingPrefix = prefix;
119 hashingPrefix.resize(SHA512_CBLOCK);
120 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
121 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700122 res->assign(SHA512_DIGEST_LENGTH, '\0');
123 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000124}
125
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700126// Generates a keystore key, using rollback resistance if supported.
127static bool generateKeystoreKey(Keystore& keystore, const km::AuthorizationSetBuilder& paramBuilder,
128 std::string* 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
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700141static bool generateKeyStorageKey(Keystore& keystore, const std::string& appId, std::string* key) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800142 auto paramBuilder = km::AuthorizationSetBuilder()
143 .AesEncryptionKey(AES_KEY_BYTES * 8)
144 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
145 .Authorization(km::TAG_APPLICATION_ID, appId)
146 .Authorization(km::TAG_NO_AUTH_REQUIRED);
Satya Tangirala6b98fb62021-05-11 19:48:47 -0700147 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700148 return generateKeystoreKey(keystore, paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800149}
150
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800151bool generateWrappedStorageKey(KeyBuffer* key) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700152 Keystore keystore;
153 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800154 std::string key_temp;
155 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800156 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700157 if (!generateKeystoreKey(keystore, paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800158 *key = KeyBuffer(key_temp.size());
159 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
160 return true;
161}
162
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700163bool exportWrappedStorageKey(const KeyBuffer& ksKey, KeyBuffer* key) {
164 Keystore keystore;
165 if (!keystore) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800166 std::string key_temp;
167
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700168 if (!keystore.exportKey(ksKey, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800169 *key = KeyBuffer(key_temp.size());
170 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
171 return true;
172}
173
Satya Tangiralae1361712021-03-15 15:33:08 -0700174static km::AuthorizationSet beginParams(const std::string& appId) {
175 return km::AuthorizationSetBuilder()
176 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800177 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000178}
179
Paul Crowleydf528a72016-03-09 09:31:37 -0800180static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800181 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800182 PLOG(ERROR) << "Failed to read from " << filename;
183 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000184 }
185 return true;
186}
187
Paul Crowley26a53882017-10-26 11:16:39 -0700188static bool readRandomBytesOrLog(size_t count, std::string* out) {
189 auto status = ReadRandomBytes(count, *out);
190 if (status != OK) {
191 LOG(ERROR) << "Random read failed with status: " << status;
192 return false;
193 }
194 return true;
195}
196
197bool createSecdiscardable(const std::string& filename, std::string* hash) {
198 std::string secdiscardable;
199 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
200 if (!writeStringToFile(secdiscardable, filename)) return false;
201 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
202 return true;
203}
204
205bool readSecdiscardable(const std::string& filename, std::string* hash) {
206 std::string secdiscardable;
207 if (!readFileToString(filename, &secdiscardable)) return false;
208 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
209 return true;
210}
211
Eric Biggersf74373b2020-11-05 19:58:26 -0800212static std::mutex key_upgrade_lock;
213
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700214// List of key directories that have had their Keystore key upgraded during
Eric Biggersf74373b2020-11-05 19:58:26 -0800215// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
216// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
Eric Biggers107d21d2021-06-08 12:55:00 -0700217// A directory can be in this list at most once.
Eric Biggersf74373b2020-11-05 19:58:26 -0800218static std::vector<std::string> key_dirs_to_commit;
219
220// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700221// deletes the old key from Keystore.
222static bool CommitUpgradedKey(Keystore& keystore, const std::string& dir) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800223 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
224 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
225
226 std::string blob;
227 if (!readFileToString(blob_file, &blob)) return false;
228
229 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
230 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
231 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700232 }
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700233 // Ensure that the rename is persisted before deleting the Keystore key.
Eric Biggersf74373b2020-11-05 19:58:26 -0800234 if (!FsyncDirectory(dir)) return false;
235
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700236 if (!keystore || !keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800237 LOG(WARNING) << "Failed to delete old key " << blob_file
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700238 << " from Keystore; continuing anyway";
239 // Continue on, but the space in Keystore used by the old key won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800240 }
241 return true;
242}
243
244static void DeferredCommitKeys() {
245 android::base::WaitForProperty("vold.checkpoint_committed", "1");
246 LOG(INFO) << "Committing upgraded keys";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700247 Keystore keystore;
248 if (!keystore) {
249 LOG(ERROR) << "Failed to open Keystore; old keys won't be deleted from Keystore";
250 // Continue on, but the space in Keystore used by the old keys won't be freed.
Eric Biggersf74373b2020-11-05 19:58:26 -0800251 }
252 std::lock_guard<std::mutex> lock(key_upgrade_lock);
253 for (auto& dir : key_dirs_to_commit) {
254 LOG(INFO) << "Committing upgraded key " << dir;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700255 CommitUpgradedKey(keystore, dir);
Eric Biggersf74373b2020-11-05 19:58:26 -0800256 }
257 key_dirs_to_commit.clear();
258}
259
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700260// Returns true if the Keystore key in |dir| has already been upgraded and is
Eric Biggersf74373b2020-11-05 19:58:26 -0800261// pending being committed. Assumes that key_upgrade_lock is held.
262static bool IsKeyCommitPending(const std::string& dir) {
263 for (const auto& dir_to_commit : key_dirs_to_commit) {
264 if (IsSameFile(dir, dir_to_commit)) return true;
265 }
266 return false;
267}
268
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700269// Schedules the upgraded Keystore key in |dir| to be committed later. Assumes
Eric Biggers107d21d2021-06-08 12:55:00 -0700270// that key_upgrade_lock is held and that a commit isn't already pending for the
271// directory.
Eric Biggersf74373b2020-11-05 19:58:26 -0800272static void ScheduleKeyCommit(const std::string& dir) {
273 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
274 key_dirs_to_commit.push_back(dir);
275}
276
277static void CancelPendingKeyCommit(const std::string& dir) {
278 std::lock_guard<std::mutex> lock(key_upgrade_lock);
279 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
280 if (IsSameFile(*it, dir)) {
281 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
282 << " because it is being destroyed";
283 key_dirs_to_commit.erase(it);
284 break;
285 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700286 }
287}
288
Satya Tangirala0f890a92021-06-08 12:55:24 -0700289bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
Satya Tangirala9475b112021-05-13 00:43:03 -0700290 std::lock_guard<std::mutex> lock(key_upgrade_lock);
291
Eric Biggers107d21d2021-06-08 12:55:00 -0700292 // Find the entry in key_dirs_to_commit (if any) for this directory so that
293 // we can update it if the rename succeeds. We don't allow duplicates in
294 // this list, so there can be at most one such entry.
295 auto it = key_dirs_to_commit.begin();
296 for (; it != key_dirs_to_commit.end(); it++) {
297 if (IsSameFile(old_name, *it)) break;
298 }
299
Satya Tangirala0f890a92021-06-08 12:55:24 -0700300 if (rename(old_name.c_str(), new_name.c_str()) != 0) {
301 PLOG(ERROR) << "Failed to rename key directory \"" << old_name << "\" to \"" << new_name
302 << "\"";
303 return false;
304 }
Satya Tangirala9475b112021-05-13 00:43:03 -0700305
Eric Biggers107d21d2021-06-08 12:55:00 -0700306 if (it != key_dirs_to_commit.end()) *it = new_name;
307
Satya Tangirala9475b112021-05-13 00:43:03 -0700308 return true;
309}
310
Eric Biggersf74373b2020-11-05 19:58:26 -0800311// Deletes a leftover upgraded key, if present. An upgraded key can be left
312// over if an update failed, or if we rebooted before committing the key in a
313// freak accident. Either way, we can re-upgrade the key if we need to.
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700314static void DeleteUpgradedKey(Keystore& keystore, const std::string& path) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800315 if (pathExists(path)) {
316 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
317 std::string blob;
318 if (!android::base::ReadFileToString(path, &blob)) {
319 LOG(WARNING) << "Failed to read leftover upgraded key " << path
320 << "; continuing anyway";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700321 } else if (!keystore.deleteKey(blob)) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800322 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700323 << " from Keystore; continuing anyway";
Eric Biggersf74373b2020-11-05 19:58:26 -0800324 }
325 if (unlink(path.c_str()) != 0) {
326 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
327 << "; continuing anyway";
328 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700329 }
330}
331
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700332// Begins a Keystore operation using the key stored in |dir|.
333static KeystoreOperation BeginKeystoreOp(Keystore& keystore, const std::string& dir,
334 const km::AuthorizationSet& keyParams,
335 const km::AuthorizationSet& opParams,
336 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700337 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100338 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800339
340 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
341 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
342
343 std::lock_guard<std::mutex> lock(key_upgrade_lock);
344
345 std::string blob;
346 bool already_upgraded = IsKeyCommitPending(dir);
347 if (already_upgraded) {
348 LOG(DEBUG)
349 << blob_file
350 << " was already upgraded and is waiting to be committed; using the upgraded blob";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700351 if (!readFileToString(upgraded_blob_file, &blob)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800352 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700353 DeleteUpgradedKey(keystore, upgraded_blob_file);
354 if (!readFileToString(blob_file, &blob)) return KeystoreOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700355 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800356
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700357 auto opHandle = keystore.begin(blob, inParams, outParams);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800358 if (!opHandle) return opHandle;
359
360 // If key blob wasn't upgraded, nothing left to do.
361 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800362
363 if (already_upgraded) {
364 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
365 << " still requires upgrade";
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700366 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800367 }
368 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800369 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700370 return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800371 if (cp_needsCheckpoint()) {
372 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
373 << "; delaying commit due to checkpoint";
374 ScheduleKeyCommit(dir);
375 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700376 if (!CommitUpgradedKey(keystore, dir)) return KeystoreOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800377 LOG(INFO) << "Key upgraded: " << blob_file;
378 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800379 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700380}
381
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700382static bool encryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
383 const km::AuthorizationSet& keyParams, const KeyBuffer& message,
384 std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800385 km::AuthorizationSet opParams =
386 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700387 km::AuthorizationSet outParams;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700388 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700389 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700390 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800391 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700392 LOG(ERROR) << "GCM encryption but no nonce generated";
393 return false;
394 }
395 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800396 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700397 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
398 std::string body;
399 if (!opHandle.updateCompletely(message, &body)) return false;
400
401 std::string mac;
402 if (!opHandle.finish(&mac)) return false;
403 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
404 *ciphertext = nonce + body + mac;
405 return true;
406}
407
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700408static bool decryptWithKeystoreKey(Keystore& keystore, const std::string& dir,
409 const km::AuthorizationSet& keyParams,
410 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800411 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700412 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800413 auto opParams = km::AuthorizationSetBuilder()
414 .Authorization(km::TAG_NONCE, nonce)
415 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700416 auto opHandle = BeginKeystoreOp(keystore, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700417 if (!opHandle) return false;
418 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
419 if (!opHandle.finish(nullptr)) return false;
420 return true;
421}
422
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800423static std::string getStretching(const KeyAuthentication& auth) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700424 if (auth.usesKeystore()) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800425 return kStretch_nopassword;
426 } else {
Satya Tangiralae1361712021-03-15 15:33:08 -0700427 return kStretch_none;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800428 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000429}
430
Paul Crowleydf528a72016-03-09 09:31:37 -0800431static bool stretchSecret(const std::string& stretching, const std::string& secret,
Satya Tangirala478cea92021-04-07 14:30:25 -0700432 std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000433 if (stretching == kStretch_nopassword) {
434 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800435 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000436 // Continue anyway
437 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800438 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000439 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800440 *stretched = secret;
Paul Crowley63c18d32016-02-10 14:02:47 +0000441 } else {
442 LOG(ERROR) << "Unknown stretching type: " << stretching;
443 return false;
444 }
445 return true;
446}
447
Paul Crowleydf528a72016-03-09 09:31:37 -0800448static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Satya Tangirala478cea92021-04-07 14:30:25 -0700449 const std::string& secdiscardable_hash, std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000450 std::string stretched;
Satya Tangirala478cea92021-04-07 14:30:25 -0700451 if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700452 *appId = secdiscardable_hash + stretched;
Seth Moore5a43d612021-01-19 17:51:51 +0000453
454 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
455 switch (storage_binding_info.state) {
456 case StorageBindingInfo::State::UNINITIALIZED:
457 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
458 break;
459 case StorageBindingInfo::State::IN_USE:
460 appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
461 break;
462 case StorageBindingInfo::State::NOT_USED:
463 // noop
464 break;
465 }
466
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800467 return true;
468}
469
470static void logOpensslError() {
471 LOG(ERROR) << "Openssl error: " << ERR_get_error();
472}
473
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700474static bool encryptWithoutKeystore(const std::string& preKey, const KeyBuffer& plaintext,
475 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700476 std::string key;
477 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800478 key.resize(AES_KEY_BYTES);
479 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
480 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
481 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
482 if (!ctx) {
483 logOpensslError();
484 return false;
485 }
486 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700487 reinterpret_cast<const uint8_t*>(key.data()),
488 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800489 logOpensslError();
490 return false;
491 }
492 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
493 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700494 if (1 != EVP_EncryptUpdate(
495 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
496 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800497 logOpensslError();
498 return false;
499 }
500 if (outlen != static_cast<int>(plaintext.size())) {
501 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
502 return false;
503 }
Shawn Willden785365b2018-01-20 09:37:36 -0700504 if (1 != EVP_EncryptFinal_ex(
505 ctx.get(),
506 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
507 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800508 logOpensslError();
509 return false;
510 }
511 if (outlen != 0) {
512 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
513 return false;
514 }
515 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700516 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
517 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800518 logOpensslError();
519 return false;
520 }
521 return true;
522}
523
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700524static bool decryptWithoutKeystore(const std::string& preKey, const std::string& ciphertext,
525 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800526 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
527 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
528 return false;
529 }
Paul Crowley26a53882017-10-26 11:16:39 -0700530 std::string key;
531 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800532 key.resize(AES_KEY_BYTES);
533 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
534 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
535 if (!ctx) {
536 logOpensslError();
537 return false;
538 }
539 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700540 reinterpret_cast<const uint8_t*>(key.data()),
541 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800542 logOpensslError();
543 return false;
544 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100545 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800546 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700547 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
548 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
549 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800550 logOpensslError();
551 return false;
552 }
553 if (outlen != static_cast<int>(plaintext->size())) {
554 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
555 return false;
556 }
557 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700558 const_cast<void*>(reinterpret_cast<const void*>(
559 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800560 logOpensslError();
561 return false;
562 }
563 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700564 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
565 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800566 logOpensslError();
567 return false;
568 }
569 if (outlen != 0) {
570 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
571 return false;
572 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000573 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000574}
575
Satya Tangirala351a4af2021-06-08 12:55:37 -0700576// Creates a directory at the given path |dir| and stores |key| in it, in such a
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700577// way that it can only be retrieved via Keystore (if no secret is given in
Satya Tangirala351a4af2021-06-08 12:55:37 -0700578// |auth|) or with the given secret (if a secret is given in |auth|), and can be
579// securely deleted. If a storage binding seed has been set, then the storage
580// binding seed will be required to retrieve the key as well.
581static bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000582 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
583 PLOG(ERROR) << "key mkdir " << dir;
584 return false;
585 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800586 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700587 std::string secdiscardable_hash;
588 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800589 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800590 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800591 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700592 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800593 std::string encryptedKey;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700594 if (auth.usesKeystore()) {
595 Keystore keystore;
596 if (!keystore) return false;
597 std::string ksKey;
598 if (!generateKeyStorageKey(keystore, appId, &ksKey)) return false;
599 if (!writeStringToFile(ksKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700600 km::AuthorizationSet keyParams = beginParams(appId);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700601 if (!encryptWithKeystoreKey(keystore, dir, keyParams, key, &encryptedKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800602 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700603 if (!encryptWithoutKeystore(appId, key, &encryptedKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800604 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000605 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800606 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000607 return true;
608}
609
Paul Crowleyf71ace32016-06-02 11:01:19 -0700610bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100611 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700612 if (pathExists(key_path)) {
613 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
614 return false;
615 }
616 if (pathExists(tmp_path)) {
617 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
618 destroyKey(tmp_path); // May be partially created so ignore errors
619 }
620 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700621
Satya Tangirala0f890a92021-06-08 12:55:24 -0700622 if (!RenameKeyDir(tmp_path, key_path)) return false;
623
Eric Biggers3345a2a2021-02-16 15:59:17 -0800624 if (!FsyncParentDirectory(key_path)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700625 LOG(DEBUG) << "Created key: " << key_path;
626 return true;
627}
628
Eric Biggersf74373b2020-11-05 19:58:26 -0800629bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000630 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800631 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000632 if (version != kCurrentVersion) {
633 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
634 return false;
635 }
Paul Crowley26a53882017-10-26 11:16:39 -0700636 std::string secdiscardable_hash;
637 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000638 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800639 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800640 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700641 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000642 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800643 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700644 if (auth.usesKeystore()) {
645 Keystore keystore;
646 if (!keystore) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700647 km::AuthorizationSet keyParams = beginParams(appId);
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700648 if (!decryptWithKeystoreKey(keystore, dir, keyParams, encryptedMessage, key)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800649 } else {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700650 if (!decryptWithoutKeystore(appId, encryptedMessage, key)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800651 }
652 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000653}
654
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700655static bool DeleteKeystoreKey(const std::string& blob_file) {
Eric Biggersf74373b2020-11-05 19:58:26 -0800656 std::string blob;
657 if (!readFileToString(blob_file, &blob)) return false;
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700658 Keystore keystore;
659 if (!keystore) return false;
660 LOG(DEBUG) << "Deleting key " << blob_file << " from Keystore";
661 if (!keystore.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000662 return true;
663}
664
Rubin Xu2436e272017-04-27 20:43:10 +0100665bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700666 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100667 LOG(ERROR) << "secdiscard failed";
668 return false;
669 }
670 return true;
671}
672
Paul Crowleydf528a72016-03-09 09:31:37 -0800673static bool recursiveDeleteKey(const std::string& dir) {
674 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000675 LOG(ERROR) << "recursive delete failed";
676 return false;
677 }
678 return true;
679}
680
Paul Crowleydf528a72016-03-09 09:31:37 -0800681bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000682 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800683
684 CancelPendingKeyCommit(dir);
685
Paul Crowleyff19b052017-10-26 11:28:55 -0700686 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700687 kSecdiscardPath,
688 "--",
689 dir + "/" + kFn_encrypted_key,
690 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700691 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800692 // Try each thing, even if previous things failed.
693
694 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
695 auto blob_file = dir + "/" + fn;
696 if (pathExists(blob_file)) {
Eric Biggersd86a8ab2021-06-15 11:34:00 -0700697 success &= DeleteKeystoreKey(blob_file);
Eric Biggersf74373b2020-11-05 19:58:26 -0800698 secdiscard_cmd.push_back(blob_file);
699 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700700 }
701 if (ForkExecvp(secdiscard_cmd) != 0) {
702 LOG(ERROR) << "secdiscard failed";
703 success = false;
704 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000705 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000706 return success;
707}
708
Seth Moore5a43d612021-01-19 17:51:51 +0000709bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
710 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
711 switch (storage_binding_info.state) {
712 case StorageBindingInfo::State::UNINITIALIZED:
713 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
714 storage_binding_info.seed = seed;
Keith Moke8600252021-09-01 18:37:48 +0000715 android::base::SetProperty("vold.storage_seed_bound", "1");
Seth Moore5a43d612021-01-19 17:51:51 +0000716 return true;
717 case StorageBindingInfo::State::IN_USE:
718 LOG(ERROR) << "key storage binding seed already set";
719 return false;
720 case StorageBindingInfo::State::NOT_USED:
721 LOG(ERROR) << "key storage already in use without binding";
722 return false;
723 }
724 return false;
725}
726
Paul Crowley1ef25582016-01-21 20:26:12 +0000727} // namespace vold
728} // namespace android