blob: d2d51e121811200e740f84b62c43fa3903b5f2a9 [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>
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"
34
35namespace android {
36namespace vold {
37
Pavel Grafove2e2d302017-08-01 17:15:53 +010038bool randomKey(KeyBuffer* key) {
Eric Biggers506342f2019-12-17 13:11:25 -080039 *key = KeyBuffer(FSCRYPT_MAX_KEY_SIZE);
Pavel Grafove2e2d302017-08-01 17:15:53 +010040 if (ReadRandomBytes(key->size(), key->data()) != 0) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070041 // TODO status_t plays badly with PLOG, fix it.
42 LOG(ERROR) << "Random read failed";
43 return false;
44 }
45 return true;
46}
47
Eric Biggersf3dc4202019-09-30 13:05:58 -070048// Return true if the kernel supports the ioctls to add/remove fscrypt keys
49// directly to/from the filesystem.
50bool isFsKeyringSupported(void) {
51 static bool initialized = false;
52 static bool supported;
53
54 if (!initialized) {
55 android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
56
57 // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY
58 // if the ioctl isn't supported. Otherwise it will fail with another
59 // error code such as EFAULT.
60 errno = 0;
61 (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
62 if (errno == ENOTTY) {
63 LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
64 "session keyring";
65 supported = false;
66 } else {
67 if (errno != EFAULT) {
68 PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
69 }
70 LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
71 supported = true;
72 }
73 // There's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY, since it's
74 // guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is. There's
75 // also no need to check for support on external volumes separately from
76 // /data, since either the kernel supports the ioctls on all
77 // fscrypt-capable filesystems or it doesn't.
78
79 initialized = true;
80 }
81 return supported;
82}
83
Paul Crowleyf71ace32016-06-02 11:01:19 -070084// Get raw keyref - used to make keyname and to pass to ioctl
Eric Biggersba997ee2018-10-23 13:07:43 -070085static std::string generateKeyRef(const uint8_t* key, int length) {
Paul Crowleyf71ace32016-06-02 11:01:19 -070086 SHA512_CTX c;
87
88 SHA512_Init(&c);
89 SHA512_Update(&c, key, length);
90 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
91 SHA512_Final(key_ref1, &c);
92
93 SHA512_Init(&c);
94 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
95 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
96 SHA512_Final(key_ref2, &c);
97
Eric Biggers506342f2019-12-17 13:11:25 -080098 static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
99 "Hash too short for descriptor");
100 return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700101}
102
Eric Biggersa701c452018-10-23 13:06:55 -0700103static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
Eric Biggers506342f2019-12-17 13:11:25 -0800104 if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700105 LOG(ERROR) << "Wrong size key " << key.size();
106 return false;
107 }
Eric Biggers506342f2019-12-17 13:11:25 -0800108 static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
109 fs_key->mode = 0; // unused by kernel
Eric Biggersa701c452018-10-23 13:06:55 -0700110 memcpy(fs_key->raw, key.data(), key.size());
Eric Biggers506342f2019-12-17 13:11:25 -0800111 fs_key->size = key.size();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700112 return true;
113}
114
Paul Crowley14c8c072018-09-18 13:30:21 -0700115static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700116
Eric Biggersf3dc4202019-09-30 13:05:58 -0700117static std::string keyrefstring(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700118 std::ostringstream o;
Chen, Luhai5744dfe2017-08-18 14:49:45 +0800119 for (unsigned char i : raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700120 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
121 }
122 return o.str();
123}
124
Eric Biggersf3dc4202019-09-30 13:05:58 -0700125static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
126 return prefix + ":" + keyrefstring(raw_ref);
127}
128
129// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
130// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
Eric Biggersa701c452018-10-23 13:06:55 -0700131static bool fscryptKeyring(key_serial_t* device_keyring) {
132 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700133 if (*device_keyring == -1) {
134 PLOG(ERROR) << "Unable to find device keyring";
135 return false;
136 }
137 return true;
138}
139
Eric Biggersf3dc4202019-09-30 13:05:58 -0700140// Add an encryption key to the legacy global session keyring.
141static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
Eric Biggersa701c452018-10-23 13:06:55 -0700142 // Place fscrypt_key into automatically zeroing buffer.
143 KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
144 fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
Pavel Grafove2e2d302017-08-01 17:15:53 +0100145
Eric Biggersa701c452018-10-23 13:06:55 -0700146 if (!fillKey(key, &fs_key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700147 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700148 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700149 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700150 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700151 key_serial_t key_id =
Eric Biggersa701c452018-10-23 13:06:55 -0700152 add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700153 if (key_id == -1) {
154 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
155 return false;
156 }
157 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
158 << " in process " << getpid();
Paul Crowleyf71ace32016-06-02 11:01:19 -0700159 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700160 return true;
161}
162
Eric Biggers83a73d72019-09-30 13:06:47 -0700163// Build a struct fscrypt_key_specifier for use in the key management ioctls.
164static bool buildKeySpecifier(fscrypt_key_specifier* spec, const std::string& raw_ref,
165 int policy_version) {
166 switch (policy_version) {
167 case 1:
168 if (raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
169 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
170 << raw_ref.size();
171 return false;
172 }
173 spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
174 memcpy(spec->u.descriptor, raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
175 return true;
176 case 2:
177 if (raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
178 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
179 << raw_ref.size();
180 return false;
181 }
182 spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
183 memcpy(spec->u.identifier, raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
184 return true;
185 default:
186 LOG(ERROR) << "Invalid encryption policy version: " << policy_version;
187 return false;
188 }
189}
190
Eric Biggersf3dc4202019-09-30 13:05:58 -0700191// Install a file-based encryption key to the kernel, for use by encrypted files
Eric Biggers83a73d72019-09-30 13:06:47 -0700192// on the specified filesystem using the specified encryption policy version.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700193//
Eric Biggers83a73d72019-09-30 13:06:47 -0700194// For v1 policies, we use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it.
195// Otherwise we add the key to the legacy global session keyring.
196//
197// For v2 policies, we always use FS_IOC_ADD_ENCRYPTION_KEY; it's the only way
198// the kernel supports.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700199//
200// Returns %true on success, %false on failure. On success also sets *raw_ref
201// to the raw key reference for use in the encryption policy.
Eric Biggers83a73d72019-09-30 13:06:47 -0700202bool installKey(const KeyBuffer& key, const std::string& mountpoint, int policy_version,
203 std::string* raw_ref) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700204 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
205 // have to copy the raw key into it.
206 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
207 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
208
Eric Biggers83a73d72019-09-30 13:06:47 -0700209 // Initialize the "key specifier", which is like a name for the key.
210 switch (policy_version) {
211 case 1:
212 // A key for a v1 policy is specified by an arbitrary 8-byte
213 // "descriptor", which must be provided by userspace. We use the
214 // first 8 bytes from the double SHA-512 of the key itself.
215 *raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
216 if (!isFsKeyringSupported()) {
217 return installKeyLegacy(key, *raw_ref);
218 }
219 if (!buildKeySpecifier(&arg->key_spec, *raw_ref, policy_version)) {
220 return false;
221 }
222 break;
223 case 2:
224 // A key for a v2 policy is specified by an 16-byte "identifier",
225 // which is a cryptographic hash of the key itself which the kernel
226 // computes and returns. Any user-provided value is ignored; we
227 // just need to set the specifier type to indicate that we're adding
228 // this type of key.
229 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
230 break;
231 default:
232 LOG(ERROR) << "Invalid encryption policy version: " << policy_version;
233 return false;
234 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700235
Eric Biggers83a73d72019-09-30 13:06:47 -0700236 // Provide the raw key.
Eric Biggersf3dc4202019-09-30 13:05:58 -0700237 arg->raw_size = key.size();
238 memcpy(arg->raw, key.data(), key.size());
239
240 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
241 if (fd == -1) {
242 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
243 return false;
244 }
245
246 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
Eric Biggers83a73d72019-09-30 13:06:47 -0700247 PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
Eric Biggersf3dc4202019-09-30 13:05:58 -0700248 return false;
249 }
250
Eric Biggers83a73d72019-09-30 13:06:47 -0700251 if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
252 // Retrieve the key identifier that the kernel computed.
253 *raw_ref = std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
254 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700255 LOG(DEBUG) << "Installed fscrypt key with ref " << keyrefstring(*raw_ref) << " to "
256 << mountpoint;
257 return true;
258}
259
260// Remove an encryption key from the legacy global session keyring.
261static bool evictKeyLegacy(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700262 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700263 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700264 bool success = true;
265 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700266 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700267 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700268
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700269 // Unlink the key from the keyring. Prefer unlinking to revoking or
270 // invalidating, since unlinking is actually no less secure currently, and
271 // it avoids bugs in certain kernel versions where the keyring key is
272 // referenced from places it shouldn't be.
273 if (keyctl_unlink(key_serial, device_keyring) != 0) {
274 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
275 success = false;
276 } else {
277 LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
278 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700279 }
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700280 return success;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700281}
282
Eric Biggersf3dc4202019-09-30 13:05:58 -0700283// Evict a file-based encryption key from the kernel.
284//
285// We use FS_IOC_REMOVE_ENCRYPTION_KEY if the kernel supports it. Otherwise we
286// remove the key from the legacy global session keyring.
287//
288// In the latter case, the caller is responsible for dropping caches.
Eric Biggers83a73d72019-09-30 13:06:47 -0700289bool evictKey(const std::string& mountpoint, const std::string& raw_ref, int policy_version) {
290 if (policy_version == 1 && !isFsKeyringSupported()) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700291 return evictKeyLegacy(raw_ref);
292 }
293
294 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
295 if (fd == -1) {
296 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
297 return false;
298 }
299
300 struct fscrypt_remove_key_arg arg;
301 memset(&arg, 0, sizeof(arg));
302
Eric Biggers83a73d72019-09-30 13:06:47 -0700303 if (!buildKeySpecifier(&arg.key_spec, raw_ref, policy_version)) {
304 return false;
305 }
Eric Biggersf3dc4202019-09-30 13:05:58 -0700306
307 std::string ref = keyrefstring(raw_ref);
308
309 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
310 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
311 return false;
312 }
313
314 LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
315 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
316 // Should never happen because keys are only added/removed as root.
317 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
318 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
319 LOG(ERROR) << "Files still open after removing key with ref " << ref
320 << ". These files were not locked!";
321 }
322 return true;
323}
324
Paul Crowley26a53882017-10-26 11:16:39 -0700325bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
326 const std::string& key_path, const std::string& tmp_path,
Eric Biggers83a73d72019-09-30 13:06:47 -0700327 const std::string& volume_uuid, int policy_version,
328 std::string* key_ref) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100329 KeyBuffer key;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700330 if (pathExists(key_path)) {
331 LOG(DEBUG) << "Key exists, using: " << key_path;
Paul Crowley26a53882017-10-26 11:16:39 -0700332 if (!retrieveKey(key_path, key_authentication, &key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700333 } else {
334 if (!create_if_absent) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700335 LOG(ERROR) << "No key found in " << key_path;
336 return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700337 }
338 LOG(INFO) << "Creating new key in " << key_path;
339 if (!randomKey(&key)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700340 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700341 }
342
Eric Biggers83a73d72019-09-30 13:06:47 -0700343 if (!installKey(key, BuildDataPath(volume_uuid), policy_version, key_ref)) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700344 LOG(ERROR) << "Failed to install key in " << key_path;
345 return false;
346 }
347 return true;
348}
349
Paul Crowley14c8c072018-09-18 13:30:21 -0700350bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800351 KeyBuffer* key, bool keepOld) {
Paul Crowleyd5759812016-06-02 11:04:27 -0700352 if (pathExists(key_path)) {
353 LOG(DEBUG) << "Key exists, using: " << key_path;
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800354 if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700355 } else {
356 if (!create_if_absent) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700357 LOG(ERROR) << "No key found in " << key_path;
358 return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700359 }
360 LOG(INFO) << "Creating new key in " << key_path;
361 if (!randomKey(key)) return false;
Paul Crowley14c8c072018-09-18 13:30:21 -0700362 if (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700363 }
364 return true;
365}
366
Paul Crowleyf71ace32016-06-02 11:01:19 -0700367} // namespace vold
368} // namespace android