blob: f82237726cf3a4d47278bb8fea86421b7ea8f412 [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>
24#include <linux/fs.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>
Elliott Hughesc3bda182017-05-09 17:01:04 -070030#include <keyutils.h>
Paul Crowleyf71ace32016-06-02 11:01:19 -070031
32#include "KeyStorage.h"
33#include "Utils.h"
Eric Biggersf3dc4202019-09-30 13:05:58 -070034#include "fscrypt_uapi.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070035
36namespace android {
37namespace vold {
38
Eric Biggersa701c452018-10-23 13:06:55 -070039constexpr int FS_AES_256_XTS_KEY_SIZE = 64;
Pavel Grafove2e2d302017-08-01 17:15:53 +010040
41bool randomKey(KeyBuffer* key) {
Eric Biggersa701c452018-10-23 13:06:55 -070042 *key = KeyBuffer(FS_AES_256_XTS_KEY_SIZE);
Pavel Grafove2e2d302017-08-01 17:15:53 +010043 if (ReadRandomBytes(key->size(), key->data()) != 0) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070044 // TODO status_t plays badly with PLOG, fix it.
45 LOG(ERROR) << "Random read failed";
46 return false;
47 }
48 return true;
49}
50
Eric Biggersf3dc4202019-09-30 13:05:58 -070051// Return true if the kernel supports the ioctls to add/remove fscrypt keys
52// directly to/from the filesystem.
53bool isFsKeyringSupported(void) {
54 static bool initialized = false;
55 static bool supported;
56
57 if (!initialized) {
58 android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
59
60 // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY
61 // if the ioctl isn't supported. Otherwise it will fail with another
62 // error code such as EFAULT.
63 errno = 0;
64 (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
65 if (errno == ENOTTY) {
66 LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
67 "session keyring";
68 supported = false;
69 } else {
70 if (errno != EFAULT) {
71 PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
72 }
73 LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
74 supported = true;
75 }
76 // There's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY, since it's
77 // guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is. There's
78 // also no need to check for support on external volumes separately from
79 // /data, since either the kernel supports the ioctls on all
80 // fscrypt-capable filesystems or it doesn't.
81
82 initialized = true;
83 }
84 return supported;
85}
86
Paul Crowleyf71ace32016-06-02 11:01:19 -070087// Get raw keyref - used to make keyname and to pass to ioctl
Eric Biggersba997ee2018-10-23 13:07:43 -070088static std::string generateKeyRef(const uint8_t* key, int length) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070089 SHA512_CTX c;
90
91 SHA512_Init(&c);
92 SHA512_Update(&c, key, length);
93 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
94 SHA512_Final(key_ref1, &c);
95
96 SHA512_Init(&c);
97 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
98 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
99 SHA512_Final(key_ref2, &c);
100
Eric Biggersa701c452018-10-23 13:06:55 -0700101 static_assert(FS_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH, "Hash too short for descriptor");
102 return std::string((char*)key_ref2, FS_KEY_DESCRIPTOR_SIZE);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700103}
104
Eric Biggersa701c452018-10-23 13:06:55 -0700105static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
106 if (key.size() != FS_AES_256_XTS_KEY_SIZE) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700107 LOG(ERROR) << "Wrong size key " << key.size();
108 return false;
109 }
Eric Biggersa701c452018-10-23 13:06:55 -0700110 static_assert(FS_AES_256_XTS_KEY_SIZE <= sizeof(fs_key->raw), "Key too long!");
111 fs_key->mode = FS_ENCRYPTION_MODE_AES_256_XTS;
112 fs_key->size = key.size();
113 memset(fs_key->raw, 0, sizeof(fs_key->raw));
114 memcpy(fs_key->raw, key.data(), key.size());
Paul Crowleyf71ace32016-06-02 11:01:19 -0700115 return true;
116}
117
Paul Crowley14c8c072018-09-18 13:30:21 -0700118static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700119
Eric Biggersf3dc4202019-09-30 13:05:58 -0700120static std::string keyrefstring(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700121 std::ostringstream o;
Chen, Luhai5744dfe2017-08-18 14:49:45 +0800122 for (unsigned char i : raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700123 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
124 }
125 return o.str();
126}
127
Eric Biggersf3dc4202019-09-30 13:05:58 -0700128static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
129 return prefix + ":" + keyrefstring(raw_ref);
130}
131
132// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
133// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
Eric Biggersa701c452018-10-23 13:06:55 -0700134static bool fscryptKeyring(key_serial_t* device_keyring) {
135 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700136 if (*device_keyring == -1) {
137 PLOG(ERROR) << "Unable to find device keyring";
138 return false;
139 }
140 return true;
141}
142
Eric Biggersf3dc4202019-09-30 13:05:58 -0700143// Add an encryption key to the legacy global session keyring.
144static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
Eric Biggersa701c452018-10-23 13:06:55 -0700145 // Place fscrypt_key into automatically zeroing buffer.
146 KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
147 fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
Pavel Grafove2e2d302017-08-01 17:15:53 +0100148
Eric Biggersa701c452018-10-23 13:06:55 -0700149 if (!fillKey(key, &fs_key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700150 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700151 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700152 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700153 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700154 key_serial_t key_id =
Eric Biggersa701c452018-10-23 13:06:55 -0700155 add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700156 if (key_id == -1) {
157 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
158 return false;
159 }
160 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
161 << " in process " << getpid();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700162 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700163 return true;
164}
165
Eric Biggers83a73d72019-09-30 13:06:47 -0700166// Build a struct fscrypt_key_specifier for use in the key management ioctls.
167static bool buildKeySpecifier(fscrypt_key_specifier* spec, const std::string& raw_ref,
168 int policy_version) {
169 switch (policy_version) {
170 case 1:
171 if (raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
172 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
173 << raw_ref.size();
174 return false;
175 }
176 spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
177 memcpy(spec->u.descriptor, raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
178 return true;
179 case 2:
180 if (raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
181 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
182 << raw_ref.size();
183 return false;
184 }
185 spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
186 memcpy(spec->u.identifier, raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
187 return true;
188 default:
189 LOG(ERROR) << "Invalid encryption policy version: " << policy_version;
190 return false;
191 }
192}
193
Eric Biggersf3dc4202019-09-30 13:05:58 -0700194// Install a file-based encryption key to the kernel, for use by encrypted files
Eric Biggers83a73d72019-09-30 13:06:47 -0700195// on the specified filesystem using the specified encryption policy version.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700196//
Eric Biggers83a73d72019-09-30 13:06:47 -0700197// For v1 policies, we use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it.
198// Otherwise we add the key to the legacy global session keyring.
199//
200// For v2 policies, we always use FS_IOC_ADD_ENCRYPTION_KEY; it's the only way
201// the kernel supports.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700202//
203// Returns %true on success, %false on failure. On success also sets *raw_ref
204// to the raw key reference for use in the encryption policy.
Eric Biggers83a73d72019-09-30 13:06:47 -0700205bool installKey(const KeyBuffer& key, const std::string& mountpoint, int policy_version,
206 std::string* raw_ref) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700207 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
208 // have to copy the raw key into it.
209 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
210 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
211
Eric Biggers83a73d72019-09-30 13:06:47 -0700212 // Initialize the "key specifier", which is like a name for the key.
213 switch (policy_version) {
214 case 1:
215 // A key for a v1 policy is specified by an arbitrary 8-byte
216 // "descriptor", which must be provided by userspace. We use the
217 // first 8 bytes from the double SHA-512 of the key itself.
218 *raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
219 if (!isFsKeyringSupported()) {
220 return installKeyLegacy(key, *raw_ref);
221 }
222 if (!buildKeySpecifier(&arg->key_spec, *raw_ref, policy_version)) {
223 return false;
224 }
225 break;
226 case 2:
227 // A key for a v2 policy is specified by an 16-byte "identifier",
228 // which is a cryptographic hash of the key itself which the kernel
229 // computes and returns. Any user-provided value is ignored; we
230 // just need to set the specifier type to indicate that we're adding
231 // this type of key.
232 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
233 break;
234 default:
235 LOG(ERROR) << "Invalid encryption policy version: " << policy_version;
236 return false;
237 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700238
Eric Biggers83a73d72019-09-30 13:06:47 -0700239 // Provide the raw key.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700240 arg->raw_size = key.size();
241 memcpy(arg->raw, key.data(), key.size());
242
243 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
244 if (fd == -1) {
245 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
246 return false;
247 }
248
249 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700250 PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700251 return false;
252 }
253
Eric Biggers83a73d72019-09-30 13:06:47 -0700254 if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
255 // Retrieve the key identifier that the kernel computed.
256 *raw_ref = std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
257 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700258 LOG(DEBUG) << "Installed fscrypt key with ref " << keyrefstring(*raw_ref) << " to "
259 << mountpoint;
260 return true;
261}
262
263// Remove an encryption key from the legacy global session keyring.
264static bool evictKeyLegacy(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700265 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700266 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700267 bool success = true;
268 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700269 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700270 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700271
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700272 // Unlink the key from the keyring. Prefer unlinking to revoking or
273 // invalidating, since unlinking is actually no less secure currently, and
274 // it avoids bugs in certain kernel versions where the keyring key is
275 // referenced from places it shouldn't be.
276 if (keyctl_unlink(key_serial, device_keyring) != 0) {
277 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
278 success = false;
279 } else {
280 LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
281 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700282 }
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700283 return success;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700284}
285
Eric Biggersf3dc4202019-09-30 13:05:58 -0700286// Evict a file-based encryption key from the kernel.
287//
288// We use FS_IOC_REMOVE_ENCRYPTION_KEY if the kernel supports it. Otherwise we
289// remove the key from the legacy global session keyring.
290//
291// In the latter case, the caller is responsible for dropping caches.
Eric Biggers83a73d72019-09-30 13:06:47 -0700292bool evictKey(const std::string& mountpoint, const std::string& raw_ref, int policy_version) {
293 if (policy_version == 1 && !isFsKeyringSupported()) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700294 return evictKeyLegacy(raw_ref);
295 }
296
297 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
298 if (fd == -1) {
299 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
300 return false;
301 }
302
303 struct fscrypt_remove_key_arg arg;
304 memset(&arg, 0, sizeof(arg));
305
Eric Biggers83a73d72019-09-30 13:06:47 -0700306 if (!buildKeySpecifier(&arg.key_spec, raw_ref, policy_version)) {
307 return false;
308 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700309
310 std::string ref = keyrefstring(raw_ref);
311
312 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
313 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
314 return false;
315 }
316
317 LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
318 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
319 // Should never happen because keys are only added/removed as root.
320 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
321 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
322 LOG(ERROR) << "Files still open after removing key with ref " << ref
323 << ". These files were not locked!";
324 }
325 return true;
326}
327
Paul Crowley26a53882017-10-26 11:16:39 -0700328bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
329 const std::string& key_path, const std::string& tmp_path,
Eric Biggers83a73d72019-09-30 13:06:47 -0700330 const std::string& volume_uuid, int policy_version,
331 std::string* key_ref) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100332 KeyBuffer key;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700333 if (pathExists(key_path)) {
334 LOG(DEBUG) << "Key exists, using: " << key_path;
Paul Crowley26a53882017-10-26 11:16:39 -0700335 if (!retrieveKey(key_path, key_authentication, &key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700336 } else {
337 if (!create_if_absent) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700338 LOG(ERROR) << "No key found in " << key_path;
339 return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700340 }
341 LOG(INFO) << "Creating new key in " << key_path;
342 if (!randomKey(&key)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700343 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700344 }
345
Eric Biggers83a73d72019-09-30 13:06:47 -0700346 if (!installKey(key, BuildDataPath(volume_uuid), policy_version, key_ref)) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700347 LOG(ERROR) << "Failed to install key in " << key_path;
348 return false;
349 }
350 return true;
351}
352
Paul Crowley14c8c072018-09-18 13:30:21 -0700353bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800354 KeyBuffer* key, bool keepOld) {
Paul Crowleyd5759812016-06-02 11:04:27 -0700355 if (pathExists(key_path)) {
356 LOG(DEBUG) << "Key exists, using: " << key_path;
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800357 if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700358 } else {
359 if (!create_if_absent) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700360 LOG(ERROR) << "No key found in " << key_path;
361 return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700362 }
363 LOG(INFO) << "Creating new key in " << key_path;
364 if (!randomKey(key)) return false;
Paul Crowley14c8c072018-09-18 13:30:21 -0700365 if (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700366 }
367 return true;
368}
369
Paul Crowleyf71ace32016-06-02 11:01:19 -0700370} // namespace vold
371} // namespace android