blob: 4a02ec5706b36c527c56f11f63af7949891c72bf [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>
22
Eric Biggersf3dc4202019-09-30 13:05:58 -070023#include <fcntl.h>
Eric Biggers3e9c9962019-12-16 15:55:12 -080024#include <linux/fscrypt.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070025#include <openssl/sha.h>
Eric Biggersf3dc4202019-09-30 13:05:58 -070026#include <sys/ioctl.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070027
28#include <android-base/file.h>
29#include <android-base/logging.h>
Nikita Ioffe78f80612020-04-20 22:21:49 +010030#include <android-base/properties.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
Paul Crowley4eac2642020-02-12 11:04:05 -080042const KeyGeneration neverGen() {
43 return KeyGeneration{0, false, false};
44}
45
46static bool randomKey(size_t size, KeyBuffer* key) {
47 *key = KeyBuffer(size);
Pavel Grafove2e2d302017-08-01 17:15:53 +010048 if (ReadRandomBytes(key->size(), key->data()) != 0) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070049 // TODO status_t plays badly with PLOG, fix it.
50 LOG(ERROR) << "Random read failed";
51 return false;
52 }
53 return true;
54}
55
Paul Crowley4eac2642020-02-12 11:04:05 -080056bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key) {
David Andersone1791572021-11-05 18:57:49 -070057 if (!gen.allow_gen) {
58 LOG(ERROR) << "Generating storage key not allowed";
59 return false;
60 }
Paul Crowley4eac2642020-02-12 11:04:05 -080061 if (gen.use_hw_wrapped_key) {
62 if (gen.keysize != FSCRYPT_MAX_KEY_SIZE) {
63 LOG(ERROR) << "Cannot generate a wrapped key " << gen.keysize << " bytes long";
64 return false;
65 }
Eric Biggersb2024e02021-03-15 12:44:36 -070066 LOG(DEBUG) << "Generating wrapped storage key";
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080067 return generateWrappedStorageKey(key);
Paul Crowley4eac2642020-02-12 11:04:05 -080068 } else {
Eric Biggersb2024e02021-03-15 12:44:36 -070069 LOG(DEBUG) << "Generating standard storage key";
Paul Crowley4eac2642020-02-12 11:04:05 -080070 return randomKey(gen.keysize, key);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080071 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -080072}
73
Eric Biggers7604eb92020-07-16 14:29:59 -070074static bool isFsKeyringSupportedImpl() {
75 android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
76
77 // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY if
78 // the ioctl isn't supported. Otherwise it will fail with another error
79 // code such as EFAULT.
80 //
81 // Note that there's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY,
82 // since it's guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is.
83 // There's also no need to check for support on external volumes separately
84 // from /data, since either the kernel supports the ioctls on all
85 // fscrypt-capable filesystems or it doesn't.
86 errno = 0;
87 (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
88 if (errno == ENOTTY) {
89 LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
90 "session keyring";
91 return false;
92 }
93 if (errno != EFAULT) {
94 PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
95 }
96 LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
97 android::base::SetProperty("ro.crypto.uses_fs_ioc_add_encryption_key", "true");
98 return true;
99}
100
Eric Biggersf3dc4202019-09-30 13:05:58 -0700101// Return true if the kernel supports the ioctls to add/remove fscrypt keys
102// directly to/from the filesystem.
103bool isFsKeyringSupported(void) {
Eric Biggers7604eb92020-07-16 14:29:59 -0700104 static bool supported = isFsKeyringSupportedImpl();
Eric Biggersf3dc4202019-09-30 13:05:58 -0700105 return supported;
106}
107
Paul Crowleyf71ace32016-06-02 11:01:19 -0700108// Get raw keyref - used to make keyname and to pass to ioctl
Eric Biggersba997ee2018-10-23 13:07:43 -0700109static std::string generateKeyRef(const uint8_t* key, int length) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700110 SHA512_CTX c;
111
112 SHA512_Init(&c);
113 SHA512_Update(&c, key, length);
114 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
115 SHA512_Final(key_ref1, &c);
116
117 SHA512_Init(&c);
118 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
119 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
120 SHA512_Final(key_ref2, &c);
121
Eric Biggers506342f2019-12-17 13:11:25 -0800122 static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
123 "Hash too short for descriptor");
124 return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700125}
126
Eric Biggersa701c452018-10-23 13:06:55 -0700127static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
Eric Biggers506342f2019-12-17 13:11:25 -0800128 if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700129 LOG(ERROR) << "Wrong size key " << key.size();
130 return false;
131 }
Eric Biggers506342f2019-12-17 13:11:25 -0800132 static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
133 fs_key->mode = 0; // unused by kernel
Eric Biggersa701c452018-10-23 13:06:55 -0700134 memcpy(fs_key->raw, key.data(), key.size());
Eric Biggers506342f2019-12-17 13:11:25 -0800135 fs_key->size = key.size();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700136 return true;
137}
138
Paul Crowley14c8c072018-09-18 13:30:21 -0700139static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700140
Eric Biggersf3dc4202019-09-30 13:05:58 -0700141static std::string keyrefstring(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700142 std::ostringstream o;
Chen, Luhai5744dfe2017-08-18 14:49:45 +0800143 for (unsigned char i : raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700144 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
145 }
146 return o.str();
147}
148
Eric Biggersf3dc4202019-09-30 13:05:58 -0700149static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
150 return prefix + ":" + keyrefstring(raw_ref);
151}
152
153// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
154// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
Eric Biggersa701c452018-10-23 13:06:55 -0700155static bool fscryptKeyring(key_serial_t* device_keyring) {
156 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700157 if (*device_keyring == -1) {
158 PLOG(ERROR) << "Unable to find device keyring";
159 return false;
160 }
161 return true;
162}
163
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000164// Add an encryption key of type "logon" to the global session keyring.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700165static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
Eric Biggersa701c452018-10-23 13:06:55 -0700166 // Place fscrypt_key into automatically zeroing buffer.
167 KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
168 fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
Pavel Grafove2e2d302017-08-01 17:15:53 +0100169
Eric Biggersa701c452018-10-23 13:06:55 -0700170 if (!fillKey(key, &fs_key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700171 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700172 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700173 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700174 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700175 key_serial_t key_id =
Eric Biggersa701c452018-10-23 13:06:55 -0700176 add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700177 if (key_id == -1) {
178 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
179 return false;
180 }
181 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
182 << " in process " << getpid();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700183 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700184 return true;
185}
186
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000187// Installs fscrypt-provisioning key into session level kernel keyring.
188// This allows for the given key to be installed back into filesystem keyring.
189// For more context see reloadKeyFromSessionKeyring.
190static bool installProvisioningKey(const KeyBuffer& key, const std::string& ref,
191 const fscrypt_key_specifier& key_spec) {
192 key_serial_t device_keyring;
193 if (!fscryptKeyring(&device_keyring)) return false;
194
195 // Place fscrypt_provisioning_key_payload into automatically zeroing buffer.
196 KeyBuffer buf(sizeof(fscrypt_provisioning_key_payload) + key.size(), 0);
197 fscrypt_provisioning_key_payload& provisioning_key =
198 *reinterpret_cast<fscrypt_provisioning_key_payload*>(buf.data());
199 memcpy(provisioning_key.raw, key.data(), key.size());
200 provisioning_key.type = key_spec.type;
201
202 key_serial_t key_id = add_key("fscrypt-provisioning", ref.c_str(), (void*)&provisioning_key,
203 buf.size(), device_keyring);
204 if (key_id == -1) {
205 PLOG(ERROR) << "Failed to insert fscrypt-provisioning key for " << ref
206 << " into session keyring";
207 return false;
208 }
209 LOG(DEBUG) << "Added fscrypt-provisioning key for " << ref << " to session keyring";
210 return true;
211}
212
Eric Biggers83a73d72019-09-30 13:06:47 -0700213// Build a struct fscrypt_key_specifier for use in the key management ioctls.
Paul Crowley77df7f22020-01-23 15:29:30 -0800214static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
215 switch (policy.options.version) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700216 case 1:
Paul Crowley77df7f22020-01-23 15:29:30 -0800217 if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700218 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
Paul Crowley77df7f22020-01-23 15:29:30 -0800219 << policy.key_raw_ref.size();
Eric Biggers83a73d72019-09-30 13:06:47 -0700220 return false;
221 }
222 spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
Paul Crowley77df7f22020-01-23 15:29:30 -0800223 memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700224 return true;
225 case 2:
Paul Crowley77df7f22020-01-23 15:29:30 -0800226 if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700227 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
Paul Crowley77df7f22020-01-23 15:29:30 -0800228 << policy.key_raw_ref.size();
Eric Biggers83a73d72019-09-30 13:06:47 -0700229 return false;
230 }
231 spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
Paul Crowley77df7f22020-01-23 15:29:30 -0800232 memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700233 return true;
234 default:
Paul Crowley77df7f22020-01-23 15:29:30 -0800235 LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
Eric Biggers83a73d72019-09-30 13:06:47 -0700236 return false;
237 }
238}
239
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000240// Installs key into keyring of a filesystem mounted on |mountpoint|.
241//
242// It's callers responsibility to fill key specifier, and either arg->raw or arg->key_id.
243//
244// In case arg->key_spec.type equals to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER
245// arg->key_spec.u.identifier will be populated with raw key reference generated
246// by kernel.
247//
248// For documentation on difference between arg->raw and arg->key_id see
249// https://www.kernel.org/doc/html/latest/filesystems/fscrypt.html#fs-ioc-add-encryption-key
250static bool installFsKeyringKey(const std::string& mountpoint, const EncryptionOptions& options,
251 fscrypt_add_key_arg* arg) {
Eric Biggerse0217d72020-07-16 16:31:00 -0700252 if (options.use_hw_wrapped_key) arg->__flags |= __FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED;
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000253
254 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
255 if (fd == -1) {
256 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
257 return false;
258 }
259
260 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
261 PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
262 return false;
263 }
264
265 return true;
266}
267
Paul Crowley77df7f22020-01-23 15:29:30 -0800268bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
269 const KeyBuffer& key, EncryptionPolicy* policy) {
270 policy->options = options;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700271 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
272 // have to copy the raw key into it.
273 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
274 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
275
Eric Biggers83a73d72019-09-30 13:06:47 -0700276 // Initialize the "key specifier", which is like a name for the key.
Paul Crowley77df7f22020-01-23 15:29:30 -0800277 switch (options.version) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700278 case 1:
279 // A key for a v1 policy is specified by an arbitrary 8-byte
280 // "descriptor", which must be provided by userspace. We use the
281 // first 8 bytes from the double SHA-512 of the key itself.
Steven Laver7fe4cdb2020-02-14 13:18:26 -0800282 if (options.use_hw_wrapped_key) {
Steven Lavered747be2019-10-24 16:40:01 -0700283 /* When wrapped key is supported, only the first 32 bytes are
284 the same per boot. The second 32 bytes can change as the ephemeral
285 key is different. */
Steven Lavered7b3532020-02-12 12:49:40 -0800286 policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size()/2);
Steven Lavered747be2019-10-24 16:40:01 -0700287 } else {
Steven Lavered7b3532020-02-12 12:49:40 -0800288 policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
Steven Lavered747be2019-10-24 16:40:01 -0700289 }
Eric Biggers83a73d72019-09-30 13:06:47 -0700290 if (!isFsKeyringSupported()) {
Paul Crowley77df7f22020-01-23 15:29:30 -0800291 return installKeyLegacy(key, policy->key_raw_ref);
Eric Biggers83a73d72019-09-30 13:06:47 -0700292 }
Paul Crowley77df7f22020-01-23 15:29:30 -0800293 if (!buildKeySpecifier(&arg->key_spec, *policy)) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700294 return false;
295 }
296 break;
297 case 2:
298 // A key for a v2 policy is specified by an 16-byte "identifier",
299 // which is a cryptographic hash of the key itself which the kernel
300 // computes and returns. Any user-provided value is ignored; we
301 // just need to set the specifier type to indicate that we're adding
302 // this type of key.
303 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
304 break;
305 default:
Paul Crowley77df7f22020-01-23 15:29:30 -0800306 LOG(ERROR) << "Invalid encryption policy version: " << options.version;
Eric Biggers83a73d72019-09-30 13:06:47 -0700307 return false;
308 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700309
310 arg->raw_size = key.size();
311 memcpy(arg->raw, key.data(), key.size());
312
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000313 if (!installFsKeyringKey(mountpoint, options, arg)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700314
Eric Biggers83a73d72019-09-30 13:06:47 -0700315 if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
316 // Retrieve the key identifier that the kernel computed.
Paul Crowley77df7f22020-01-23 15:29:30 -0800317 policy->key_raw_ref =
318 std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
Eric Biggers83a73d72019-09-30 13:06:47 -0700319 }
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000320 std::string ref = keyrefstring(policy->key_raw_ref);
321 LOG(DEBUG) << "Installed fscrypt key with ref " << ref << " to " << mountpoint;
322
323 if (!installProvisioningKey(key, ref, arg->key_spec)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700324 return true;
325}
326
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000327// Remove an encryption key of type "logon" from the global session keyring.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700328static bool evictKeyLegacy(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700329 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700330 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700331 bool success = true;
332 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700333 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700334 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700335
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700336 // Unlink the key from the keyring. Prefer unlinking to revoking or
337 // invalidating, since unlinking is actually no less secure currently, and
338 // it avoids bugs in certain kernel versions where the keyring key is
339 // referenced from places it shouldn't be.
340 if (keyctl_unlink(key_serial, device_keyring) != 0) {
341 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
342 success = false;
343 } else {
344 LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
345 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700346 }
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700347 return success;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700348}
349
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000350static bool evictProvisioningKey(const std::string& ref) {
351 key_serial_t device_keyring;
352 if (!fscryptKeyring(&device_keyring)) {
353 return false;
354 }
355
356 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
357 if (key_serial == -1 && errno != ENOKEY) {
358 PLOG(ERROR) << "Error searching session keyring for fscrypt-provisioning key for " << ref;
359 return false;
360 }
361
362 if (key_serial != -1 && keyctl_unlink(key_serial, device_keyring) != 0) {
363 PLOG(ERROR) << "Failed to unlink fscrypt-provisioning key for " << ref
364 << " from session keyring";
365 return false;
366 }
367 return true;
368}
369
Paul Crowley77df7f22020-01-23 15:29:30 -0800370bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
371 if (policy.options.version == 1 && !isFsKeyringSupported()) {
372 return evictKeyLegacy(policy.key_raw_ref);
Eric Biggersf3dc4202019-09-30 13:05:58 -0700373 }
374
375 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
376 if (fd == -1) {
377 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
378 return false;
379 }
380
381 struct fscrypt_remove_key_arg arg;
382 memset(&arg, 0, sizeof(arg));
383
Paul Crowley77df7f22020-01-23 15:29:30 -0800384 if (!buildKeySpecifier(&arg.key_spec, policy)) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700385 return false;
386 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700387
Paul Crowley77df7f22020-01-23 15:29:30 -0800388 std::string ref = keyrefstring(policy.key_raw_ref);
Eric Biggersf3dc4202019-09-30 13:05:58 -0700389
390 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
391 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
392 return false;
393 }
394
395 LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
396 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
397 // Should never happen because keys are only added/removed as root.
398 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
399 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
400 LOG(ERROR) << "Files still open after removing key with ref " << ref
401 << ". These files were not locked!";
402 }
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000403
404 if (!evictProvisioningKey(ref)) return false;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700405 return true;
406}
407
Paul Crowley4eac2642020-02-12 11:04:05 -0800408bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
409 const KeyAuthentication& key_authentication, const KeyGeneration& gen,
Eric Biggersf74373b2020-11-05 19:58:26 -0800410 KeyBuffer* key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700411 if (pathExists(key_path)) {
412 LOG(DEBUG) << "Key exists, using: " << key_path;
Eric Biggersf74373b2020-11-05 19:58:26 -0800413 if (!retrieveKey(key_path, key_authentication, key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700414 } else {
Paul Crowley4eac2642020-02-12 11:04:05 -0800415 if (!gen.allow_gen) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700416 LOG(ERROR) << "No key found in " << key_path;
417 return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700418 }
419 LOG(INFO) << "Creating new key in " << key_path;
Paul Crowley4eac2642020-02-12 11:04:05 -0800420 if (!generateStorageKey(gen, key)) return false;
Paul Crowley77df7f22020-01-23 15:29:30 -0800421 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700422 }
423 return true;
424}
425
Nikita Ioffe1ee35cf2020-02-28 19:50:31 +0000426bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy) {
427 key_serial_t device_keyring;
428 if (!fscryptKeyring(&device_keyring)) {
429 return false;
430 }
431
432 std::string ref = keyrefstring(policy.key_raw_ref);
433 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
434 if (key_serial == -1) {
435 PLOG(ERROR) << "Failed to find fscrypt-provisioning key for " << ref
436 << " in session keyring";
437 return false;
438 }
439
440 LOG(DEBUG) << "Installing fscrypt-provisioning key for " << ref << " back into " << mountpoint
441 << " fs-keyring";
442
443 struct fscrypt_add_key_arg arg;
444 memset(&arg, 0, sizeof(arg));
445 if (!buildKeySpecifier(&arg.key_spec, policy)) return false;
446 arg.key_id = key_serial;
447 if (!installFsKeyringKey(mountpoint, policy.options, &arg)) return false;
448
449 return true;
450}
451
Paul Crowleyf71ace32016-06-02 11:01:19 -0700452} // namespace vold
453} // namespace android