blob: c1a82fb1e4645e011d16ace6e38fd3bc3059ab28 [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 Biggersf3dc4202019-09-30 13:05:58 -0700166// Install a file-based encryption key to the kernel, for use by encrypted files
167// on the specified filesystem.
168//
169// We use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it. Otherwise we add
170// the key to the legacy global session keyring.
171//
172// Returns %true on success, %false on failure. On success also sets *raw_ref
173// to the raw key reference for use in the encryption policy.
174bool installKey(const KeyBuffer& key, const std::string& mountpoint, std::string* raw_ref) {
175 *raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
176 if (!isFsKeyringSupported()) {
177 return installKeyLegacy(key, *raw_ref);
178 }
179
180 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
181 // have to copy the raw key into it.
182 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
183 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
184
185 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
186 memcpy(arg->key_spec.u.descriptor, raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
187
188 arg->raw_size = key.size();
189 memcpy(arg->raw, key.data(), key.size());
190
191 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
192 if (fd == -1) {
193 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
194 return false;
195 }
196
197 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
198 PLOG(ERROR) << "Failed to install fscrypt key with ref " << keyrefstring(*raw_ref) << " to "
199 << mountpoint;
200 return false;
201 }
202
203 LOG(DEBUG) << "Installed fscrypt key with ref " << keyrefstring(*raw_ref) << " to "
204 << mountpoint;
205 return true;
206}
207
208// Remove an encryption key from the legacy global session keyring.
209static bool evictKeyLegacy(const std::string& raw_ref) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700210 key_serial_t device_keyring;
Eric Biggersa701c452018-10-23 13:06:55 -0700211 if (!fscryptKeyring(&device_keyring)) return false;
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700212 bool success = true;
213 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
Eric Biggersf3dc4202019-09-30 13:05:58 -0700214 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700215 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
Paul Crowleyf71ace32016-06-02 11:01:19 -0700216
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700217 // Unlink the key from the keyring. Prefer unlinking to revoking or
218 // invalidating, since unlinking is actually no less secure currently, and
219 // it avoids bugs in certain kernel versions where the keyring key is
220 // referenced from places it shouldn't be.
221 if (keyctl_unlink(key_serial, device_keyring) != 0) {
222 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
223 success = false;
224 } else {
225 LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
226 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700227 }
Paul Crowleycd8bfe32017-06-19 16:05:55 -0700228 return success;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700229}
230
Eric Biggersf3dc4202019-09-30 13:05:58 -0700231// Evict a file-based encryption key from the kernel.
232//
233// We use FS_IOC_REMOVE_ENCRYPTION_KEY if the kernel supports it. Otherwise we
234// remove the key from the legacy global session keyring.
235//
236// In the latter case, the caller is responsible for dropping caches.
237bool evictKey(const std::string& mountpoint, const std::string& raw_ref) {
238 if (!isFsKeyringSupported()) {
239 return evictKeyLegacy(raw_ref);
240 }
241
242 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
243 if (fd == -1) {
244 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
245 return false;
246 }
247
248 struct fscrypt_remove_key_arg arg;
249 memset(&arg, 0, sizeof(arg));
250
251 arg.key_spec.type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
252 memcpy(arg.key_spec.u.descriptor, raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
253
254 std::string ref = keyrefstring(raw_ref);
255
256 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
257 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
258 return false;
259 }
260
261 LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
262 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
263 // Should never happen because keys are only added/removed as root.
264 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
265 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
266 LOG(ERROR) << "Files still open after removing key with ref " << ref
267 << ". These files were not locked!";
268 }
269 return true;
270}
271
Paul Crowley26a53882017-10-26 11:16:39 -0700272bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
273 const std::string& key_path, const std::string& tmp_path,
Eric Biggersf3dc4202019-09-30 13:05:58 -0700274 const std::string& volume_uuid, std::string* key_ref) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100275 KeyBuffer key;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700276 if (pathExists(key_path)) {
277 LOG(DEBUG) << "Key exists, using: " << key_path;
Paul Crowley26a53882017-10-26 11:16:39 -0700278 if (!retrieveKey(key_path, key_authentication, &key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700279 } else {
280 if (!create_if_absent) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700281 LOG(ERROR) << "No key found in " << key_path;
282 return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700283 }
284 LOG(INFO) << "Creating new key in " << key_path;
285 if (!randomKey(&key)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700286 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, key)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700287 }
288
Eric Biggersf3dc4202019-09-30 13:05:58 -0700289 if (!installKey(key, BuildDataPath(volume_uuid), key_ref)) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700290 LOG(ERROR) << "Failed to install key in " << key_path;
291 return false;
292 }
293 return true;
294}
295
Paul Crowley14c8c072018-09-18 13:30:21 -0700296bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800297 KeyBuffer* key, bool keepOld) {
Paul Crowleyd5759812016-06-02 11:04:27 -0700298 if (pathExists(key_path)) {
299 LOG(DEBUG) << "Key exists, using: " << key_path;
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800300 if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700301 } else {
302 if (!create_if_absent) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700303 LOG(ERROR) << "No key found in " << key_path;
304 return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700305 }
306 LOG(INFO) << "Creating new key in " << key_path;
307 if (!randomKey(key)) return false;
Paul Crowley14c8c072018-09-18 13:30:21 -0700308 if (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false;
Paul Crowleyd5759812016-06-02 11:04:27 -0700309 }
310 return true;
311}
312
Paul Crowleyf71ace32016-06-02 11:01:19 -0700313} // namespace vold
314} // namespace android