blob: 395b6b34b18397f1ec0d9d7d8828b4edc9b2bed1 [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 Huckleberry759ac5f2023-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>
Nikita Ioffeeea8bd32020-04-20 22:21:49 +010031#include <android-base/properties.h>
Elliott Hughesc3bda182017-05-09 17:01:04 -070032#include <keyutils.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070033
34#include "KeyStorage.h"
35#include "Utils.h"
36
37namespace android {
38namespace vold {
39
Paul Crowleyf4430382020-04-05 19:34:31 -070040using android::fscrypt::EncryptionOptions;
41using android::fscrypt::EncryptionPolicy;
42
Nathan Huckleberry759ac5f2023-02-22 02:28:28 +000043// This must be acquired before calling fscrypt ioctls that operate on keys.
44// This prevents race conditions between evicting and reinstalling keys.
45static std::mutex fscrypt_keyring_mutex;
46
Paul Crowley4eac2642020-02-12 11:04:05 -080047const KeyGeneration neverGen() {
48 return KeyGeneration{0, false, false};
49}
50
51static bool randomKey(size_t size, KeyBuffer* key) {
52 *key = KeyBuffer(size);
Pavel Grafove2e2d302017-08-01 17:15:53 +010053 if (ReadRandomBytes(key->size(), key->data()) != 0) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070054 // TODO status_t plays badly with PLOG, fix it.
55 LOG(ERROR) << "Random read failed";
56 return false;
57 }
58 return true;
59}
60
Paul Crowley4eac2642020-02-12 11:04:05 -080061bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key) {
David Andersone1791572021-11-05 18:57:49 -070062 if (!gen.allow_gen) {
63 LOG(ERROR) << "Generating storage key not allowed";
64 return false;
65 }
Paul Crowley4eac2642020-02-12 11:04:05 -080066 if (gen.use_hw_wrapped_key) {
67 if (gen.keysize != FSCRYPT_MAX_KEY_SIZE) {
68 LOG(ERROR) << "Cannot generate a wrapped key " << gen.keysize << " bytes long";
69 return false;
70 }
Eric Biggersb2024e02021-03-15 12:44:36 -070071 LOG(DEBUG) << "Generating wrapped storage key";
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080072 return generateWrappedStorageKey(key);
Paul Crowley4eac2642020-02-12 11:04:05 -080073 } else {
Eric Biggersb2024e02021-03-15 12:44:36 -070074 LOG(DEBUG) << "Generating standard storage key";
Paul Crowley4eac2642020-02-12 11:04:05 -080075 return randomKey(gen.keysize, key);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080076 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080077}
78
Eric Biggers7604eb92020-07-16 14:29:59 -070079static bool isFsKeyringSupportedImpl() {
80 android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
81
82 // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY if
83 // the ioctl isn't supported. Otherwise it will fail with another error
84 // code such as EFAULT.
85 //
86 // Note that there's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY,
87 // since it's guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is.
88 // There's also no need to check for support on external volumes separately
89 // from /data, since either the kernel supports the ioctls on all
90 // fscrypt-capable filesystems or it doesn't.
91 errno = 0;
92 (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
93 if (errno == ENOTTY) {
94 LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
95 "session keyring";
96 return false;
97 }
98 if (errno != EFAULT) {
99 PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
100 }
101 LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
102 android::base::SetProperty("ro.crypto.uses_fs_ioc_add_encryption_key", "true");
103 return true;
104}
105
Eric Biggersf3dc4202019-09-30 13:05:58 -0700106// Return true if the kernel supports the ioctls to add/remove fscrypt keys
107// directly to/from the filesystem.
108bool isFsKeyringSupported(void) {
Eric Biggers7604eb92020-07-16 14:29:59 -0700109 static bool supported = isFsKeyringSupportedImpl();
Eric Biggersf3dc4202019-09-30 13:05:58 -0700110 return supported;
111}
112
Paul Crowleyf71ace32016-06-02 11:01:19 -0700113// Get raw keyref - used to make keyname and to pass to ioctl
Eric Biggersba997ee2018-10-23 13:07:43 -0700114static std::string generateKeyRef(const uint8_t* key, int length) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700115 SHA512_CTX c;
116
117 SHA512_Init(&c);
118 SHA512_Update(&c, key, length);
119 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
120 SHA512_Final(key_ref1, &c);
121
122 SHA512_Init(&c);
123 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
124 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
125 SHA512_Final(key_ref2, &c);
126
Eric Biggers506342f2019-12-17 13:11:25 -0800127 static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
128 "Hash too short for descriptor");
129 return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700130}
131
Eric Biggersa701c452018-10-23 13:06:55 -0700132static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
Eric Biggers506342f2019-12-17 13:11:25 -0800133 if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700134 LOG(ERROR) << "Wrong size key " << key.size();
135 return false;
136 }
Eric Biggers506342f2019-12-17 13:11:25 -0800137 static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
138 fs_key->mode = 0; // unused by kernel
Eric Biggersa701c452018-10-23 13:06:55 -0700139 memcpy(fs_key->raw, key.data(), key.size());
Eric Biggers506342f2019-12-17 13:11:25 -0800140 fs_key->size = key.size();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700141 return true;
142}
143
Paul Crowley14c8c072018-09-18 13:30:21 -0700144static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700145
Eric Biggersf3dc4202019-09-30 13:05:58 -0700146static std::string keyrefstring(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700147 std::ostringstream o;
Chen, Luhai5744dfe2017-08-18 14:49:45 +0800148 for (unsigned char i : raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700149 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
150 }
151 return o.str();
152}
153
Eric Biggersf3dc4202019-09-30 13:05:58 -0700154static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
155 return prefix + ":" + keyrefstring(raw_ref);
156}
157
158// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
159// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
Eric Biggersa701c452018-10-23 13:06:55 -0700160static bool fscryptKeyring(key_serial_t* device_keyring) {
161 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700162 if (*device_keyring == -1) {
163 PLOG(ERROR) << "Unable to find device keyring";
164 return false;
165 }
166 return true;
167}
168
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000169// Add an encryption key of type "logon" to the global session keyring.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700170static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
Eric Biggersa701c452018-10-23 13:06:55 -0700171 // Place fscrypt_key into automatically zeroing buffer.
172 KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
173 fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
Pavel Grafove2e2d302017-08-01 17:15:53 +0100174
Eric Biggersa701c452018-10-23 13:06:55 -0700175 if (!fillKey(key, &fs_key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700176 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700177 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700178 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700179 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700180 key_serial_t key_id =
Eric Biggersa701c452018-10-23 13:06:55 -0700181 add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700182 if (key_id == -1) {
183 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
184 return false;
185 }
186 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
187 << " in process " << getpid();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700188 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700189 return true;
190}
191
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000192// Installs fscrypt-provisioning key into session level kernel keyring.
193// This allows for the given key to be installed back into filesystem keyring.
194// For more context see reloadKeyFromSessionKeyring.
195static bool installProvisioningKey(const KeyBuffer& key, const std::string& ref,
196 const fscrypt_key_specifier& key_spec) {
197 key_serial_t device_keyring;
198 if (!fscryptKeyring(&device_keyring)) return false;
199
200 // Place fscrypt_provisioning_key_payload into automatically zeroing buffer.
201 KeyBuffer buf(sizeof(fscrypt_provisioning_key_payload) + key.size(), 0);
202 fscrypt_provisioning_key_payload& provisioning_key =
203 *reinterpret_cast<fscrypt_provisioning_key_payload*>(buf.data());
204 memcpy(provisioning_key.raw, key.data(), key.size());
205 provisioning_key.type = key_spec.type;
206
207 key_serial_t key_id = add_key("fscrypt-provisioning", ref.c_str(), (void*)&provisioning_key,
208 buf.size(), device_keyring);
209 if (key_id == -1) {
210 PLOG(ERROR) << "Failed to insert fscrypt-provisioning key for " << ref
211 << " into session keyring";
212 return false;
213 }
214 LOG(DEBUG) << "Added fscrypt-provisioning key for " << ref << " to session keyring";
215 return true;
216}
217
Eric Biggers83a73d72019-09-30 13:06:47 -0700218// Build a struct fscrypt_key_specifier for use in the key management ioctls.
Paul Crowley77df7f22020-01-23 15:29:30 -0800219static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
220 switch (policy.options.version) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700221 case 1:
Paul Crowley77df7f22020-01-23 15:29:30 -0800222 if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700223 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
Paul Crowley77df7f22020-01-23 15:29:30 -0800224 << policy.key_raw_ref.size();
Eric Biggers83a73d72019-09-30 13:06:47 -0700225 return false;
226 }
227 spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
Paul Crowley77df7f22020-01-23 15:29:30 -0800228 memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700229 return true;
230 case 2:
Paul Crowley77df7f22020-01-23 15:29:30 -0800231 if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700232 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
Paul Crowley77df7f22020-01-23 15:29:30 -0800233 << policy.key_raw_ref.size();
Eric Biggers83a73d72019-09-30 13:06:47 -0700234 return false;
235 }
236 spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
Paul Crowley77df7f22020-01-23 15:29:30 -0800237 memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700238 return true;
239 default:
Paul Crowley77df7f22020-01-23 15:29:30 -0800240 LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
Eric Biggers83a73d72019-09-30 13:06:47 -0700241 return false;
242 }
243}
244
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000245// Installs key into keyring of a filesystem mounted on |mountpoint|.
246//
247// It's callers responsibility to fill key specifier, and either arg->raw or arg->key_id.
248//
249// In case arg->key_spec.type equals to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER
250// arg->key_spec.u.identifier will be populated with raw key reference generated
251// by kernel.
252//
253// For documentation on difference between arg->raw and arg->key_id see
254// https://www.kernel.org/doc/html/latest/filesystems/fscrypt.html#fs-ioc-add-encryption-key
255static bool installFsKeyringKey(const std::string& mountpoint, const EncryptionOptions& options,
256 fscrypt_add_key_arg* arg) {
Eric Biggerse0217d72020-07-16 16:31:00 -0700257 if (options.use_hw_wrapped_key) arg->__flags |= __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED;
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000258
259 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
260 if (fd == -1) {
261 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
262 return false;
263 }
264
265 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
266 PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
267 return false;
268 }
269
270 return true;
271}
272
Paul Crowley77df7f22020-01-23 15:29:30 -0800273bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
274 const KeyBuffer& key, EncryptionPolicy* policy) {
Nathan Huckleberry759ac5f2023-02-22 02:28:28 +0000275 const std::lock_guard<std::mutex> lock(fscrypt_keyring_mutex);
Paul Crowley77df7f22020-01-23 15:29:30 -0800276 policy->options = options;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700277 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
278 // have to copy the raw key into it.
279 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
280 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
281
Eric Biggers83a73d72019-09-30 13:06:47 -0700282 // Initialize the "key specifier", which is like a name for the key.
Paul Crowley77df7f22020-01-23 15:29:30 -0800283 switch (options.version) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700284 case 1:
285 // A key for a v1 policy is specified by an arbitrary 8-byte
286 // "descriptor", which must be provided by userspace. We use the
287 // first 8 bytes from the double SHA-512 of the key itself.
Paul Crowley77df7f22020-01-23 15:29:30 -0800288 policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
Eric Biggers83a73d72019-09-30 13:06:47 -0700289 if (!isFsKeyringSupported()) {
Paul Crowley77df7f22020-01-23 15:29:30 -0800290 return installKeyLegacy(key, policy->key_raw_ref);
Eric Biggers83a73d72019-09-30 13:06:47 -0700291 }
Paul Crowley77df7f22020-01-23 15:29:30 -0800292 if (!buildKeySpecifier(&arg->key_spec, *policy)) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700293 return false;
294 }
295 break;
296 case 2:
297 // A key for a v2 policy is specified by an 16-byte "identifier",
298 // which is a cryptographic hash of the key itself which the kernel
299 // computes and returns. Any user-provided value is ignored; we
300 // just need to set the specifier type to indicate that we're adding
301 // this type of key.
302 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
303 break;
304 default:
Paul Crowley77df7f22020-01-23 15:29:30 -0800305 LOG(ERROR) << "Invalid encryption policy version: " << options.version;
Eric Biggers83a73d72019-09-30 13:06:47 -0700306 return false;
307 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700308
309 arg->raw_size = key.size();
310 memcpy(arg->raw, key.data(), key.size());
311
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000312 if (!installFsKeyringKey(mountpoint, options, arg)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700313
Eric Biggers83a73d72019-09-30 13:06:47 -0700314 if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
315 // Retrieve the key identifier that the kernel computed.
Paul Crowley77df7f22020-01-23 15:29:30 -0800316 policy->key_raw_ref =
317 std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700318 }
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000319 std::string ref = keyrefstring(policy->key_raw_ref);
320 LOG(DEBUG) << "Installed fscrypt key with ref " << ref << " to " << mountpoint;
321
322 if (!installProvisioningKey(key, ref, arg->key_spec)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700323 return true;
324}
325
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000326// Remove an encryption key of type "logon" from the global session keyring.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700327static bool evictKeyLegacy(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700328 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700329 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700330 bool success = true;
331 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700332 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700333 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700334
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700335 // Unlink the key from the keyring. Prefer unlinking to revoking or
336 // invalidating, since unlinking is actually no less secure currently, and
337 // it avoids bugs in certain kernel versions where the keyring key is
338 // referenced from places it shouldn't be.
339 if (keyctl_unlink(key_serial, device_keyring) != 0) {
340 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
341 success = false;
342 } else {
343 LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
344 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700345 }
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700346 return success;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700347}
348
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000349static bool evictProvisioningKey(const std::string& ref) {
350 key_serial_t device_keyring;
351 if (!fscryptKeyring(&device_keyring)) {
352 return false;
353 }
354
355 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
356 if (key_serial == -1 && errno != ENOKEY) {
357 PLOG(ERROR) << "Error searching session keyring for fscrypt-provisioning key for " << ref;
358 return false;
359 }
360
361 if (key_serial != -1 && keyctl_unlink(key_serial, device_keyring) != 0) {
362 PLOG(ERROR) << "Failed to unlink fscrypt-provisioning key for " << ref
363 << " from session keyring";
364 return false;
365 }
366 return true;
367}
368
Nathan Huckleberry759ac5f2023-02-22 02:28:28 +0000369static void waitForBusyFiles(const struct fscrypt_key_specifier key_spec, const std::string ref,
370 const std::string mountpoint) {
371 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
372 if (fd == -1) {
373 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
374 return;
375 }
376
377 std::chrono::milliseconds wait_time(3200);
378 std::chrono::milliseconds total_wait_time(0);
379 while (wait_time <= std::chrono::milliseconds(51200)) {
380 total_wait_time += wait_time;
381 std::this_thread::sleep_for(wait_time);
382
383 const std::lock_guard<std::mutex> lock(fscrypt_keyring_mutex);
384
385 struct fscrypt_get_key_status_arg get_arg;
386 memset(&get_arg, 0, sizeof(get_arg));
387 get_arg.key_spec = key_spec;
388
389 if (ioctl(fd, FS_IOC_GET_ENCRYPTION_KEY_STATUS, &get_arg) != 0) {
390 PLOG(ERROR) << "Failed to get status for fscrypt key with ref " << ref << " from "
391 << mountpoint;
392 return;
393 }
394 if (get_arg.status != FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED) {
395 LOG(DEBUG) << "Key status changed, cancelling busy file cleanup for key with ref "
396 << ref << ".";
397 return;
398 }
399
400 struct fscrypt_remove_key_arg remove_arg;
401 memset(&remove_arg, 0, sizeof(remove_arg));
402 remove_arg.key_spec = key_spec;
403
404 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &remove_arg) != 0) {
405 PLOG(ERROR) << "Failed to clean up busy files for fscrypt key with ref " << ref
406 << " from " << mountpoint;
407 return;
408 }
409 if (remove_arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
410 // Should never happen because keys are only added/removed as root.
411 LOG(ERROR) << "Unexpected case: key with ref " << ref
412 << " is still added by other users!";
413 } else if (!(remove_arg.removal_status_flags &
414 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY)) {
415 LOG(INFO) << "Successfully cleaned up busy files for key with ref " << ref
416 << ". After waiting " << total_wait_time.count() << "ms.";
417 return;
418 }
419 LOG(WARNING) << "Files still open after waiting " << total_wait_time.count()
420 << "ms. Key with ref " << ref << " still has unlocked files!";
421 wait_time *= 2;
422 }
423 LOG(ERROR) << "Waiting for files to close never completed. Files using key with ref " << ref
424 << " were not locked!";
425}
426
Paul Crowley77df7f22020-01-23 15:29:30 -0800427bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
Nathan Huckleberry759ac5f2023-02-22 02:28:28 +0000428 const std::lock_guard<std::mutex> lock(fscrypt_keyring_mutex);
Paul Crowley77df7f22020-01-23 15:29:30 -0800429 if (policy.options.version == 1 && !isFsKeyringSupported()) {
430 return evictKeyLegacy(policy.key_raw_ref);
Eric Biggersf3dc4202019-09-30 13:05:58 -0700431 }
432
433 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
434 if (fd == -1) {
435 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
436 return false;
437 }
438
439 struct fscrypt_remove_key_arg arg;
440 memset(&arg, 0, sizeof(arg));
441
Paul Crowley77df7f22020-01-23 15:29:30 -0800442 if (!buildKeySpecifier(&arg.key_spec, policy)) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700443 return false;
444 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700445
Paul Crowley77df7f22020-01-23 15:29:30 -0800446 std::string ref = keyrefstring(policy.key_raw_ref);
Eric Biggersf3dc4202019-09-30 13:05:58 -0700447
448 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
449 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
450 return false;
451 }
452
453 LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
454 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
455 // Should never happen because keys are only added/removed as root.
456 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
457 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
Nathan Huckleberry759ac5f2023-02-22 02:28:28 +0000458 LOG(WARNING)
459 << "Files still open after removing key with ref " << ref
460 << ". These files were not locked! Punting busy file clean up to worker thread.";
461 // Processes are killed asynchronously in ActivityManagerService due to performance issues
462 // with synchronous kills. If there were busy files they will probably be killed soon. Wait
463 // for them asynchronously.
464 std::thread busyFilesThread(waitForBusyFiles, arg.key_spec, ref, mountpoint);
465 busyFilesThread.detach();
Eric Biggersf3dc4202019-09-30 13:05:58 -0700466 }
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000467
468 if (!evictProvisioningKey(ref)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700469 return true;
470}
471
Paul Crowley4eac2642020-02-12 11:04:05 -0800472bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
473 const KeyAuthentication& key_authentication, const KeyGeneration& gen,
Eric Biggersf74373b2020-11-05 19:58:26 -0800474 KeyBuffer* key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700475 if (pathExists(key_path)) {
476 LOG(DEBUG) << "Key exists, using: " << key_path;
Eric Biggersf74373b2020-11-05 19:58:26 -0800477 if (!retrieveKey(key_path, key_authentication, key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700478 } else {
Paul Crowley4eac2642020-02-12 11:04:05 -0800479 if (!gen.allow_gen) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700480 LOG(ERROR) << "No key found in " << key_path;
481 return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700482 }
483 LOG(INFO) << "Creating new key in " << key_path;
Paul Crowley4eac2642020-02-12 11:04:05 -0800484 if (!generateStorageKey(gen, key)) return false;
Paul Crowley77df7f22020-01-23 15:29:30 -0800485 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700486 }
487 return true;
488}
489
Nikita Ioffe1c6731c2020-02-28 19:50:31 +0000490bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy) {
491 key_serial_t device_keyring;
492 if (!fscryptKeyring(&device_keyring)) {
493 return false;
494 }
495
496 std::string ref = keyrefstring(policy.key_raw_ref);
497 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
498 if (key_serial == -1) {
499 PLOG(ERROR) << "Failed to find fscrypt-provisioning key for " << ref
500 << " in session keyring";
501 return false;
502 }
503
504 LOG(DEBUG) << "Installing fscrypt-provisioning key for " << ref << " back into " << mountpoint
505 << " fs-keyring";
506
507 struct fscrypt_add_key_arg arg;
508 memset(&arg, 0, sizeof(arg));
509 if (!buildKeySpecifier(&arg.key_spec, policy)) return false;
510 arg.key_id = key_serial;
511 if (!installFsKeyringKey(mountpoint, policy.options, &arg)) return false;
512
513 return true;
514}
515
Paul Crowleyf71ace32016-06-02 11:01:19 -0700516} // namespace vold
517} // namespace android