blob: 5a8b5503d0e6970da13cb84cfb39a9d213b0bbe9 [file] [log] [blame]
Paul Crowleyf71ace32016-06-02 11:01:19 -07001/*
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 "KeyUtil.h"
18
19#include <iomanip>
20#include <sstream>
21#include <string>
Nathan Huckleberrya21962b2023-02-22 02:28:28 +000022#include <thread>
Paul Crowleyf71ace32016-06-02 11:01:19 -070023
Eric Biggersf3dc4202019-09-30 13:05:58 -070024#include <fcntl.h>
Eric Biggers3e9c9962019-12-16 15:55:12 -080025#include <linux/fscrypt.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070026#include <openssl/sha.h>
Eric Biggersf3dc4202019-09-30 13:05:58 -070027#include <sys/ioctl.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070028
29#include <android-base/file.h>
30#include <android-base/logging.h>
Elliott Hughesc3bda182017-05-09 17:01:04 -070031#include <keyutils.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070032
33#include "KeyStorage.h"
34#include "Utils.h"
35
36namespace android {
37namespace vold {
38
Paul Crowleyf4430382020-04-05 19:34:31 -070039using android::fscrypt::EncryptionOptions;
40using android::fscrypt::EncryptionPolicy;
41
Nathan Huckleberrya21962b2023-02-22 02:28:28 +000042// This must be acquired before calling fscrypt ioctls that operate on keys.
43// This prevents race conditions between evicting and reinstalling keys.
44static std::mutex fscrypt_keyring_mutex;
45
Paul Crowley4eac2642020-02-12 11:04:05 -080046const KeyGeneration neverGen() {
47 return KeyGeneration{0, false, false};
48}
49
50static bool randomKey(size_t size, KeyBuffer* key) {
51 *key = KeyBuffer(size);
Pavel Grafove2e2d302017-08-01 17:15:53 +010052 if (ReadRandomBytes(key->size(), key->data()) != 0) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070053 // TODO status_t plays badly with PLOG, fix it.
54 LOG(ERROR) << "Random read failed";
55 return false;
56 }
57 return true;
58}
59
Paul Crowley4eac2642020-02-12 11:04:05 -080060bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key) {
David Andersone1791572021-11-05 18:57:49 -070061 if (!gen.allow_gen) {
62 LOG(ERROR) << "Generating storage key not allowed";
63 return false;
64 }
Paul Crowley4eac2642020-02-12 11:04:05 -080065 if (gen.use_hw_wrapped_key) {
66 if (gen.keysize != FSCRYPT_MAX_KEY_SIZE) {
67 LOG(ERROR) << "Cannot generate a wrapped key " << gen.keysize << " bytes long";
68 return false;
69 }
Eric Biggersb2024e02021-03-15 12:44:36 -070070 LOG(DEBUG) << "Generating wrapped storage key";
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080071 return generateWrappedStorageKey(key);
Paul Crowley4eac2642020-02-12 11:04:05 -080072 } else {
Eric Biggersb2024e02021-03-15 12:44:36 -070073 LOG(DEBUG) << "Generating standard storage key";
Paul Crowley4eac2642020-02-12 11:04:05 -080074 return randomKey(gen.keysize, key);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080075 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080076}
77
Eric Biggers7604eb92020-07-16 14:29:59 -070078static bool isFsKeyringSupportedImpl() {
79 android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
80
81 // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY if
82 // the ioctl isn't supported. Otherwise it will fail with another error
83 // code such as EFAULT.
84 //
85 // Note that there's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY,
86 // since it's guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is.
87 // There's also no need to check for support on external volumes separately
88 // from /data, since either the kernel supports the ioctls on all
89 // fscrypt-capable filesystems or it doesn't.
90 errno = 0;
91 (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
92 if (errno == ENOTTY) {
93 LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
94 "session keyring";
95 return false;
96 }
97 if (errno != EFAULT) {
98 PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
99 }
100 LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
Eric Biggers7604eb92020-07-16 14:29:59 -0700101 return true;
102}
103
Eric Biggersf3dc4202019-09-30 13:05:58 -0700104// Return true if the kernel supports the ioctls to add/remove fscrypt keys
105// directly to/from the filesystem.
106bool isFsKeyringSupported(void) {
Eric Biggers7604eb92020-07-16 14:29:59 -0700107 static bool supported = isFsKeyringSupportedImpl();
Eric Biggersf3dc4202019-09-30 13:05:58 -0700108 return supported;
109}
110
Paul Crowleyf71ace32016-06-02 11:01:19 -0700111// Get raw keyref - used to make keyname and to pass to ioctl
Eric Biggersba997ee2018-10-23 13:07:43 -0700112static std::string generateKeyRef(const uint8_t* key, int length) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700113 SHA512_CTX c;
114
115 SHA512_Init(&c);
116 SHA512_Update(&c, key, length);
117 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
118 SHA512_Final(key_ref1, &c);
119
120 SHA512_Init(&c);
121 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
122 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
123 SHA512_Final(key_ref2, &c);
124
Eric Biggers506342f2019-12-17 13:11:25 -0800125 static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
126 "Hash too short for descriptor");
127 return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700128}
129
Eric Biggersa701c452018-10-23 13:06:55 -0700130static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
Eric Biggers506342f2019-12-17 13:11:25 -0800131 if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700132 LOG(ERROR) << "Wrong size key " << key.size();
133 return false;
134 }
Eric Biggers506342f2019-12-17 13:11:25 -0800135 static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
136 fs_key->mode = 0; // unused by kernel
Eric Biggersa701c452018-10-23 13:06:55 -0700137 memcpy(fs_key->raw, key.data(), key.size());
Eric Biggers506342f2019-12-17 13:11:25 -0800138 fs_key->size = key.size();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700139 return true;
140}
141
Paul Crowley14c8c072018-09-18 13:30:21 -0700142static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700143
Eric Biggersf3dc4202019-09-30 13:05:58 -0700144static std::string keyrefstring(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700145 std::ostringstream o;
Chen, Luhai5744dfe2017-08-18 14:49:45 +0800146 for (unsigned char i : raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700147 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
148 }
149 return o.str();
150}
151
Eric Biggersf3dc4202019-09-30 13:05:58 -0700152static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
153 return prefix + ":" + keyrefstring(raw_ref);
154}
155
156// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
157// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
Eric Biggersa701c452018-10-23 13:06:55 -0700158static bool fscryptKeyring(key_serial_t* device_keyring) {
159 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700160 if (*device_keyring == -1) {
161 PLOG(ERROR) << "Unable to find device keyring";
162 return false;
163 }
164 return true;
165}
166
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000167// Add an encryption key of type "logon" to the global session keyring.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700168static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
Eric Biggersa701c452018-10-23 13:06:55 -0700169 // Place fscrypt_key into automatically zeroing buffer.
170 KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
171 fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
Pavel Grafove2e2d302017-08-01 17:15:53 +0100172
Eric Biggersa701c452018-10-23 13:06:55 -0700173 if (!fillKey(key, &fs_key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700174 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700175 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700176 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700177 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700178 key_serial_t key_id =
Eric Biggersa701c452018-10-23 13:06:55 -0700179 add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700180 if (key_id == -1) {
181 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
182 return false;
183 }
184 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
185 << " in process " << getpid();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700186 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700187 return true;
188}
189
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000190// Installs fscrypt-provisioning key into session level kernel keyring.
191// This allows for the given key to be installed back into filesystem keyring.
192// For more context see reloadKeyFromSessionKeyring.
193static bool installProvisioningKey(const KeyBuffer& key, const std::string& ref,
194 const fscrypt_key_specifier& key_spec) {
195 key_serial_t device_keyring;
196 if (!fscryptKeyring(&device_keyring)) return false;
197
198 // Place fscrypt_provisioning_key_payload into automatically zeroing buffer.
199 KeyBuffer buf(sizeof(fscrypt_provisioning_key_payload) + key.size(), 0);
200 fscrypt_provisioning_key_payload& provisioning_key =
201 *reinterpret_cast<fscrypt_provisioning_key_payload*>(buf.data());
202 memcpy(provisioning_key.raw, key.data(), key.size());
203 provisioning_key.type = key_spec.type;
204
205 key_serial_t key_id = add_key("fscrypt-provisioning", ref.c_str(), (void*)&provisioning_key,
206 buf.size(), device_keyring);
207 if (key_id == -1) {
208 PLOG(ERROR) << "Failed to insert fscrypt-provisioning key for " << ref
209 << " into session keyring";
210 return false;
211 }
212 LOG(DEBUG) << "Added fscrypt-provisioning key for " << ref << " to session keyring";
213 return true;
214}
215
Eric Biggers83a73d72019-09-30 13:06:47 -0700216// Build a struct fscrypt_key_specifier for use in the key management ioctls.
Paul Crowley77df7f22020-01-23 15:29:30 -0800217static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
218 switch (policy.options.version) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700219 case 1:
Paul Crowley77df7f22020-01-23 15:29:30 -0800220 if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700221 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
Paul Crowley77df7f22020-01-23 15:29:30 -0800222 << policy.key_raw_ref.size();
Eric Biggers83a73d72019-09-30 13:06:47 -0700223 return false;
224 }
225 spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
Paul Crowley77df7f22020-01-23 15:29:30 -0800226 memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700227 return true;
228 case 2:
Paul Crowley77df7f22020-01-23 15:29:30 -0800229 if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700230 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
Paul Crowley77df7f22020-01-23 15:29:30 -0800231 << policy.key_raw_ref.size();
Eric Biggers83a73d72019-09-30 13:06:47 -0700232 return false;
233 }
234 spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
Paul Crowley77df7f22020-01-23 15:29:30 -0800235 memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700236 return true;
237 default:
Paul Crowley77df7f22020-01-23 15:29:30 -0800238 LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
Eric Biggers83a73d72019-09-30 13:06:47 -0700239 return false;
240 }
241}
242
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000243// Installs key into keyring of a filesystem mounted on |mountpoint|.
244//
245// It's callers responsibility to fill key specifier, and either arg->raw or arg->key_id.
246//
247// In case arg->key_spec.type equals to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER
248// arg->key_spec.u.identifier will be populated with raw key reference generated
249// by kernel.
250//
251// For documentation on difference between arg->raw and arg->key_id see
252// https://www.kernel.org/doc/html/latest/filesystems/fscrypt.html#fs-ioc-add-encryption-key
253static bool installFsKeyringKey(const std::string& mountpoint, const EncryptionOptions& options,
254 fscrypt_add_key_arg* arg) {
Eric Biggerse0217d72020-07-16 16:31:00 -0700255 if (options.use_hw_wrapped_key) arg->__flags |= __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED;
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000256
257 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
258 if (fd == -1) {
259 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
260 return false;
261 }
262
263 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
264 PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
265 return false;
266 }
267
268 return true;
269}
270
Paul Crowley77df7f22020-01-23 15:29:30 -0800271bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
272 const KeyBuffer& key, EncryptionPolicy* policy) {
Nathan Huckleberrya21962b2023-02-22 02:28:28 +0000273 const std::lock_guard<std::mutex> lock(fscrypt_keyring_mutex);
Paul Crowley77df7f22020-01-23 15:29:30 -0800274 policy->options = options;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700275 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
276 // have to copy the raw key into it.
277 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
278 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
279
Eric Biggers83a73d72019-09-30 13:06:47 -0700280 // Initialize the "key specifier", which is like a name for the key.
Paul Crowley77df7f22020-01-23 15:29:30 -0800281 switch (options.version) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700282 case 1:
283 // A key for a v1 policy is specified by an arbitrary 8-byte
284 // "descriptor", which must be provided by userspace. We use the
285 // first 8 bytes from the double SHA-512 of the key itself.
Paul Crowley77df7f22020-01-23 15:29:30 -0800286 policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
Eric Biggers83a73d72019-09-30 13:06:47 -0700287 if (!isFsKeyringSupported()) {
Paul Crowley77df7f22020-01-23 15:29:30 -0800288 return installKeyLegacy(key, policy->key_raw_ref);
Eric Biggers83a73d72019-09-30 13:06:47 -0700289 }
Paul Crowley77df7f22020-01-23 15:29:30 -0800290 if (!buildKeySpecifier(&arg->key_spec, *policy)) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700291 return false;
292 }
293 break;
294 case 2:
295 // A key for a v2 policy is specified by an 16-byte "identifier",
296 // which is a cryptographic hash of the key itself which the kernel
297 // computes and returns. Any user-provided value is ignored; we
298 // just need to set the specifier type to indicate that we're adding
299 // this type of key.
300 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
301 break;
302 default:
Paul Crowley77df7f22020-01-23 15:29:30 -0800303 LOG(ERROR) << "Invalid encryption policy version: " << options.version;
Eric Biggers83a73d72019-09-30 13:06:47 -0700304 return false;
305 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700306
307 arg->raw_size = key.size();
308 memcpy(arg->raw, key.data(), key.size());
309
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000310 if (!installFsKeyringKey(mountpoint, options, arg)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700311
Eric Biggers83a73d72019-09-30 13:06:47 -0700312 if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
313 // Retrieve the key identifier that the kernel computed.
Paul Crowley77df7f22020-01-23 15:29:30 -0800314 policy->key_raw_ref =
315 std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700316 }
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000317 std::string ref = keyrefstring(policy->key_raw_ref);
318 LOG(DEBUG) << "Installed fscrypt key with ref " << ref << " to " << mountpoint;
319
320 if (!installProvisioningKey(key, ref, arg->key_spec)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700321 return true;
322}
323
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000324// Remove an encryption key of type "logon" from the global session keyring.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700325static bool evictKeyLegacy(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700326 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700327 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700328 bool success = true;
329 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700330 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700331 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700332
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700333 // Unlink the key from the keyring. Prefer unlinking to revoking or
334 // invalidating, since unlinking is actually no less secure currently, and
335 // it avoids bugs in certain kernel versions where the keyring key is
336 // referenced from places it shouldn't be.
337 if (keyctl_unlink(key_serial, device_keyring) != 0) {
338 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
339 success = false;
340 } else {
341 LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
342 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700343 }
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700344 return success;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700345}
346
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000347static bool evictProvisioningKey(const std::string& ref) {
348 key_serial_t device_keyring;
349 if (!fscryptKeyring(&device_keyring)) {
350 return false;
351 }
352
353 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
354 if (key_serial == -1 && errno != ENOKEY) {
355 PLOG(ERROR) << "Error searching session keyring for fscrypt-provisioning key for " << ref;
356 return false;
357 }
358
359 if (key_serial != -1 && keyctl_unlink(key_serial, device_keyring) != 0) {
360 PLOG(ERROR) << "Failed to unlink fscrypt-provisioning key for " << ref
361 << " from session keyring";
362 return false;
363 }
364 return true;
365}
366
Nathan Huckleberrya21962b2023-02-22 02:28:28 +0000367static void waitForBusyFiles(const struct fscrypt_key_specifier key_spec, const std::string ref,
368 const std::string mountpoint) {
369 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
370 if (fd == -1) {
371 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
372 return;
373 }
374
375 std::chrono::milliseconds wait_time(3200);
376 std::chrono::milliseconds total_wait_time(0);
377 while (wait_time <= std::chrono::milliseconds(51200)) {
378 total_wait_time += wait_time;
379 std::this_thread::sleep_for(wait_time);
380
381 const std::lock_guard<std::mutex> lock(fscrypt_keyring_mutex);
382
383 struct fscrypt_get_key_status_arg get_arg;
384 memset(&get_arg, 0, sizeof(get_arg));
385 get_arg.key_spec = key_spec;
386
387 if (ioctl(fd, FS_IOC_GET_ENCRYPTION_KEY_STATUS, &get_arg) != 0) {
388 PLOG(ERROR) << "Failed to get status for fscrypt key with ref " << ref << " from "
389 << mountpoint;
390 return;
391 }
392 if (get_arg.status != FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED) {
393 LOG(DEBUG) << "Key status changed, cancelling busy file cleanup for key with ref "
394 << ref << ".";
395 return;
396 }
397
398 struct fscrypt_remove_key_arg remove_arg;
399 memset(&remove_arg, 0, sizeof(remove_arg));
400 remove_arg.key_spec = key_spec;
401
402 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &remove_arg) != 0) {
403 PLOG(ERROR) << "Failed to clean up busy files for fscrypt key with ref " << ref
404 << " from " << mountpoint;
405 return;
406 }
407 if (remove_arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
408 // Should never happen because keys are only added/removed as root.
409 LOG(ERROR) << "Unexpected case: key with ref " << ref
410 << " is still added by other users!";
411 } else if (!(remove_arg.removal_status_flags &
412 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY)) {
413 LOG(INFO) << "Successfully cleaned up busy files for key with ref " << ref
414 << ". After waiting " << total_wait_time.count() << "ms.";
415 return;
416 }
417 LOG(WARNING) << "Files still open after waiting " << total_wait_time.count()
418 << "ms. Key with ref " << ref << " still has unlocked files!";
419 wait_time *= 2;
420 }
421 LOG(ERROR) << "Waiting for files to close never completed. Files using key with ref " << ref
422 << " were not locked!";
423}
424
Paul Crowley77df7f22020-01-23 15:29:30 -0800425bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
Nathan Huckleberrya21962b2023-02-22 02:28:28 +0000426 const std::lock_guard<std::mutex> lock(fscrypt_keyring_mutex);
Paul Crowley77df7f22020-01-23 15:29:30 -0800427 if (policy.options.version == 1 && !isFsKeyringSupported()) {
428 return evictKeyLegacy(policy.key_raw_ref);
Eric Biggersf3dc4202019-09-30 13:05:58 -0700429 }
430
431 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
432 if (fd == -1) {
433 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
434 return false;
435 }
436
437 struct fscrypt_remove_key_arg arg;
438 memset(&arg, 0, sizeof(arg));
439
Paul Crowley77df7f22020-01-23 15:29:30 -0800440 if (!buildKeySpecifier(&arg.key_spec, policy)) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700441 return false;
442 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700443
Paul Crowley77df7f22020-01-23 15:29:30 -0800444 std::string ref = keyrefstring(policy.key_raw_ref);
Eric Biggersf3dc4202019-09-30 13:05:58 -0700445
446 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
447 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
448 return false;
449 }
450
451 LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
452 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
453 // Should never happen because keys are only added/removed as root.
454 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
455 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
Nathan Huckleberrya21962b2023-02-22 02:28:28 +0000456 LOG(WARNING)
457 << "Files still open after removing key with ref " << ref
458 << ". These files were not locked! Punting busy file clean up to worker thread.";
459 // Processes are killed asynchronously in ActivityManagerService due to performance issues
460 // with synchronous kills. If there were busy files they will probably be killed soon. Wait
461 // for them asynchronously.
462 std::thread busyFilesThread(waitForBusyFiles, arg.key_spec, ref, mountpoint);
463 busyFilesThread.detach();
Eric Biggersf3dc4202019-09-30 13:05:58 -0700464 }
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000465
466 if (!evictProvisioningKey(ref)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700467 return true;
468}
469
Paul Crowley4eac2642020-02-12 11:04:05 -0800470bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
471 const KeyAuthentication& key_authentication, const KeyGeneration& gen,
Eric Biggersf74373b2020-11-05 19:58:26 -0800472 KeyBuffer* key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700473 if (pathExists(key_path)) {
474 LOG(DEBUG) << "Key exists, using: " << key_path;
Eric Biggersf74373b2020-11-05 19:58:26 -0800475 if (!retrieveKey(key_path, key_authentication, key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700476 } else {
Paul Crowley4eac2642020-02-12 11:04:05 -0800477 if (!gen.allow_gen) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700478 LOG(ERROR) << "No key found in " << key_path;
479 return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700480 }
481 LOG(INFO) << "Creating new key in " << key_path;
Paul Crowley4eac2642020-02-12 11:04:05 -0800482 if (!generateStorageKey(gen, key)) return false;
Paul Crowley77df7f22020-01-23 15:29:30 -0800483 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700484 }
485 return true;
486}
487
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000488bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy) {
489 key_serial_t device_keyring;
490 if (!fscryptKeyring(&device_keyring)) {
491 return false;
492 }
493
494 std::string ref = keyrefstring(policy.key_raw_ref);
495 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
496 if (key_serial == -1) {
497 PLOG(ERROR) << "Failed to find fscrypt-provisioning key for " << ref
498 << " in session keyring";
499 return false;
500 }
501
502 LOG(DEBUG) << "Installing fscrypt-provisioning key for " << ref << " back into " << mountpoint
503 << " fs-keyring";
504
505 struct fscrypt_add_key_arg arg;
506 memset(&arg, 0, sizeof(arg));
507 if (!buildKeySpecifier(&arg.key_spec, policy)) return false;
508 arg.key_id = key_serial;
509 if (!installFsKeyringKey(mountpoint, policy.options, &arg)) return false;
510
511 return true;
512}
513
Paul Crowleyf71ace32016-06-02 11:01:19 -0700514} // namespace vold
515} // namespace android