blob: b7119a6dfaa091450e7231a57e3952f9072acda9 [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
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
bigbiff7ba75002020-04-11 20:47:09 -040019#include <iomanip>
20#include <sstream>
21#include <string>
22
bigbiffa957f072021-03-07 18:20:29 -050023#include <fcntl.h>
24#include <linux/fscrypt.h>
bigbiff7ba75002020-04-11 20:47:09 -040025#include <openssl/sha.h>
bigbiffa957f072021-03-07 18:20:29 -050026#include <sys/ioctl.h>
bigbiff7ba75002020-04-11 20:47:09 -040027
28#include <android-base/file.h>
29#include <android-base/logging.h>
bigbiffa957f072021-03-07 18:20:29 -050030#include <android-base/properties.h>
bigbiff7ba75002020-04-11 20:47:09 -040031#include <keyutils.h>
32
bigbiffa957f072021-03-07 18:20:29 -050033#include <fscrypt_uapi.h>
bigbiffbcd23d32021-09-22 18:22:13 -040034#include "FsCrypt.h"
bigbiff7ba75002020-04-11 20:47:09 -040035#include "KeyStorage.h"
36#include "Utils.h"
37
mauronofrio matarrese79820322020-05-25 19:48:56 +020038
bigbiffa957f072021-03-07 18:20:29 -050039const KeyGeneration neverGen() {
40 return KeyGeneration{0, false, false};
41}
bigbiff7ba75002020-04-11 20:47:09 -040042
bigbiffa957f072021-03-07 18:20:29 -050043static bool randomKey(size_t size, KeyBuffer* key) {
44 *key = KeyBuffer(size);
bigbiff7ba75002020-04-11 20:47:09 -040045 if (ReadRandomBytes(key->size(), key->data()) != 0) {
46 // TODO status_t plays badly with PLOG, fix it.
47 LOG(ERROR) << "Random read failed";
48 return false;
49 }
50 return true;
51}
52
bigbiffa957f072021-03-07 18:20:29 -050053bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key) {
54 if (!gen.allow_gen) return false;
55 if (gen.use_hw_wrapped_key) {
56 if (gen.keysize != FSCRYPT_MAX_KEY_SIZE) {
57 LOG(ERROR) << "Cannot generate a wrapped key " << gen.keysize << " bytes long";
58 return false;
59 }
60 return generateWrappedStorageKey(key);
61 } else {
62 return randomKey(gen.keysize, key);
63 }
64}
65
66// Return true if the kernel supports the ioctls to add/remove fscrypt keys
67// directly to/from the filesystem.
68bool isFsKeyringSupported(void) {
69 static bool initialized = false;
70 static bool supported;
71
72 if (!initialized) {
73 android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
74
75 // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY
76 // if the ioctl isn't supported. Otherwise it will fail with another
77 // error code such as EFAULT.
78 errno = 0;
79 (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
80 if (errno == ENOTTY) {
81 LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
82 "session keyring";
83 supported = false;
84 } else {
85 if (errno != EFAULT) {
86 PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
87 }
88 LOG(INFO) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
89 supported = true;
90 android::base::SetProperty("ro.crypto.uses_fs_ioc_add_encryption_key", "true");
91 }
92 // There's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY, since it's
93 // guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is. There's
94 // also no need to check for support on external volumes separately from
95 // /data, since either the kernel supports the ioctls on all
96 // fscrypt-capable filesystems or it doesn't.
97
98 initialized = true;
99 }
100 return supported;
101}
102
bigbiff7ba75002020-04-11 20:47:09 -0400103// Get raw keyref - used to make keyname and to pass to ioctl
104static std::string generateKeyRef(const uint8_t* key, int length) {
105 SHA512_CTX c;
106
107 SHA512_Init(&c);
108 SHA512_Update(&c, key, length);
109 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
110 SHA512_Final(key_ref1, &c);
111
112 SHA512_Init(&c);
113 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
114 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
115 SHA512_Final(key_ref2, &c);
116
bigbiffa957f072021-03-07 18:20:29 -0500117 static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
118 "Hash too short for descriptor");
119 return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
bigbiff7ba75002020-04-11 20:47:09 -0400120}
121
122static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
bigbiffa957f072021-03-07 18:20:29 -0500123 if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
bigbiff7ba75002020-04-11 20:47:09 -0400124 LOG(ERROR) << "Wrong size key " << key.size();
125 return false;
126 }
bigbiffa957f072021-03-07 18:20:29 -0500127 static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
128 fs_key->mode = 0; // unused by kernel
bigbiff7ba75002020-04-11 20:47:09 -0400129 memcpy(fs_key->raw, key.data(), key.size());
bigbiffa957f072021-03-07 18:20:29 -0500130 fs_key->size = key.size();
bigbiff7ba75002020-04-11 20:47:09 -0400131 return true;
132}
133
134static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
135
bigbiffa957f072021-03-07 18:20:29 -0500136static std::string keyrefstring(const std::string& raw_ref) {
bigbiff7ba75002020-04-11 20:47:09 -0400137 std::ostringstream o;
bigbiff7ba75002020-04-11 20:47:09 -0400138 for (unsigned char i : raw_ref) {
139 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
140 }
141 return o.str();
142}
143
bigbiffa957f072021-03-07 18:20:29 -0500144static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
145 return prefix + ":" + keyrefstring(raw_ref);
146}
147
148// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
149// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
bigbiff7ba75002020-04-11 20:47:09 -0400150static bool fscryptKeyring(key_serial_t* device_keyring) {
151 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
152 if (*device_keyring == -1) {
153 PLOG(ERROR) << "Unable to find device keyring";
154 return false;
155 }
156 return true;
157}
158
bigbiffa957f072021-03-07 18:20:29 -0500159// Add an encryption key of type "logon" to the global session keyring.
160static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
bigbiff7ba75002020-04-11 20:47:09 -0400161 // Place fscrypt_key into automatically zeroing buffer.
162 KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
163 fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
164
165 if (!fillKey(key, &fs_key)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400166 key_serial_t device_keyring;
167 if (!fscryptKeyring(&device_keyring)) return false;
168 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
bigbiffa957f072021-03-07 18:20:29 -0500169 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
bigbiff7ba75002020-04-11 20:47:09 -0400170 key_serial_t key_id =
171 add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
172 if (key_id == -1) {
173 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
174 return false;
175 }
bigbiffa957f072021-03-07 18:20:29 -0500176 LOG(INFO) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
bigbiff7ba75002020-04-11 20:47:09 -0400177 << " in process " << getpid();
178 }
179 return true;
180}
181
bigbiffa957f072021-03-07 18:20:29 -0500182// Installs fscrypt-provisioning key into session level kernel keyring.
183// This allows for the given key to be installed back into filesystem keyring.
184// For more context see reloadKeyFromSessionKeyring.
185static bool installProvisioningKey(const KeyBuffer& key, const std::string& ref,
186 const fscrypt_key_specifier& key_spec) {
187 key_serial_t device_keyring;
188 if (!fscryptKeyring(&device_keyring)) return false;
189
190 // Place fscrypt_provisioning_key_payload into automatically zeroing buffer.
191 KeyBuffer buf(sizeof(fscrypt_provisioning_key_payload) + key.size(), 0);
192 fscrypt_provisioning_key_payload& provisioning_key =
193 *reinterpret_cast<fscrypt_provisioning_key_payload*>(buf.data());
194 memcpy(provisioning_key.raw, key.data(), key.size());
195 provisioning_key.type = key_spec.type;
196
197 key_serial_t key_id = add_key("fscrypt-provisioning", ref.c_str(), (void*)&provisioning_key,
198 buf.size(), device_keyring);
199 if (key_id == -1) {
200 PLOG(ERROR) << "Failed to insert fscrypt-provisioning key for " << ref
201 << " into session keyring";
202 return false;
203 }
204 LOG(INFO) << "Added fscrypt-provisioning key for " << ref << " to session keyring";
205 return true;
206}
207
208// Build a struct fscrypt_key_specifier for use in the key management ioctls.
209static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
210 switch (policy.options.version) {
211 case 1:
212 if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
213 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
214 << policy.key_raw_ref.size();
215 return false;
216 }
217 spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
218 memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
219 return true;
220 case 2:
221 if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
222 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
223 << policy.key_raw_ref.size();
224 return false;
225 }
226 spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
227 memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
228 return true;
229 default:
230 LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
231 return false;
232 }
233}
234
235// Installs key into keyring of a filesystem mounted on |mountpoint|.
236//
237// It's callers responsibility to fill key specifier, and either arg->raw or arg->key_id.
238//
239// In case arg->key_spec.type equals to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER
240// arg->key_spec.u.identifier will be populated with raw key reference generated
241// by kernel.
242//
243// For documentation on difference between arg->raw and arg->key_id see
244// https://www.kernel.org/doc/html/latest/filesystems/fscrypt.html#fs-ioc-add-encryption-key
245static bool installFsKeyringKey(const std::string& mountpoint, const EncryptionOptions& options,
246 fscrypt_add_key_arg* arg) {
247 if (options.use_hw_wrapped_key) arg->flags |= FSCRYPT_ADD_KEY_FLAG_WRAPPED;
248
249 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
250 if (fd == -1) {
251 PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
252 return false;
253 }
254
255 if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
256 PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
257 return false;
258 }
259
260 return true;
261}
262
263bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
264 const KeyBuffer& key, EncryptionPolicy* policy) {
265 policy->options = options;
266 // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
267 // have to copy the raw key into it.
268 KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
269 struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
270
271 // Initialize the "key specifier", which is like a name for the key.
272 switch (options.version) {
273 case 1:
274 // A key for a v1 policy is specified by an arbitrary 8-byte
275 // "descriptor", which must be provided by userspace. We use the
276 // first 8 bytes from the double SHA-512 of the key itself.
bigbiffbcd23d32021-09-22 18:22:13 -0400277 if (options.use_hw_wrapped_key) {
278 // When wrapped key is supported, only the first 32 bytes are
279 // the same per boot. The second 32 bytes can change as the ephemeral
280 // key is different.
281 policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size()/2);
282 } else {
283 policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
284 }
bigbiffa957f072021-03-07 18:20:29 -0500285 if (!isFsKeyringSupported()) {
286 return installKeyLegacy(key, policy->key_raw_ref);
287 }
288 if (!buildKeySpecifier(&arg->key_spec, *policy)) {
289 return false;
290 }
291 break;
292 case 2:
293 // A key for a v2 policy is specified by an 16-byte "identifier",
294 // which is a cryptographic hash of the key itself which the kernel
295 // computes and returns. Any user-provided value is ignored; we
296 // just need to set the specifier type to indicate that we're adding
297 // this type of key.
298 arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
299 break;
300 default:
301 LOG(ERROR) << "Invalid encryption policy version: " << options.version;
302 return false;
303 }
304
305 arg->raw_size = key.size();
306 memcpy(arg->raw, key.data(), key.size());
307
308 if (!installFsKeyringKey(mountpoint, options, arg)) return false;
309
310 if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
311 // Retrieve the key identifier that the kernel computed.
312 policy->key_raw_ref =
313 std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
314 }
315 std::string ref = keyrefstring(policy->key_raw_ref);
316 LOG(INFO) << "Installed fscrypt key with ref " << ref << " to " << mountpoint;
317
318 if (!installProvisioningKey(key, ref, arg->key_spec)) return false;
319 return true;
320}
321
322// Remove an encryption key of type "logon" from the global session keyring.
323static bool evictKeyLegacy(const std::string& raw_ref) {
bigbiff7ba75002020-04-11 20:47:09 -0400324 key_serial_t device_keyring;
325 if (!fscryptKeyring(&device_keyring)) return false;
326 bool success = true;
327 for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
bigbiffa957f072021-03-07 18:20:29 -0500328 auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
bigbiff7ba75002020-04-11 20:47:09 -0400329 auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
330
331 // Unlink the key from the keyring. Prefer unlinking to revoking or
332 // invalidating, since unlinking is actually no less secure currently, and
333 // it avoids bugs in certain kernel versions where the keyring key is
334 // referenced from places it shouldn't be.
335 if (keyctl_unlink(key_serial, device_keyring) != 0) {
336 PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
337 success = false;
338 } else {
bigbiffa957f072021-03-07 18:20:29 -0500339 LOG(ERROR) << "Unlinked key with serial " << key_serial << " ref " << ref;
bigbiff7ba75002020-04-11 20:47:09 -0400340 }
341 }
342 return success;
343}
344
bigbiffa957f072021-03-07 18:20:29 -0500345static bool evictProvisioningKey(const std::string& ref) {
346 key_serial_t device_keyring;
347 if (!fscryptKeyring(&device_keyring)) {
348 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400349 }
350
bigbiffa957f072021-03-07 18:20:29 -0500351 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
352 if (key_serial == -1 && errno != ENOKEY) {
353 PLOG(ERROR) << "Error searching session keyring for fscrypt-provisioning key for " << ref;
354 return false;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200355 }
356
bigbiffa957f072021-03-07 18:20:29 -0500357 if (key_serial != -1 && keyctl_unlink(key_serial, device_keyring) != 0) {
358 PLOG(ERROR) << "Failed to unlink fscrypt-provisioning key for " << ref
359 << " from session keyring";
bigbiff7ba75002020-04-11 20:47:09 -0400360 return false;
361 }
362 return true;
363}
364
bigbiffa957f072021-03-07 18:20:29 -0500365bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
366 if (policy.options.version == 1 && !isFsKeyringSupported()) {
367 return evictKeyLegacy(policy.key_raw_ref);
368 }
369
370 android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
371 if (fd == -1) {
372 PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
373 return false;
374 }
375
376 struct fscrypt_remove_key_arg arg;
377 memset(&arg, 0, sizeof(arg));
378
379 if (!buildKeySpecifier(&arg.key_spec, policy)) {
380 return false;
381 }
382
383 std::string ref = keyrefstring(policy.key_raw_ref);
384
385 if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
386 PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
387 return false;
388 }
389
390 LOG(ERROR) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
391 if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
392 // Should never happen because keys are only added/removed as root.
393 LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
394 } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
395 LOG(ERROR) << "Files still open after removing key with ref " << ref
396 << ". These files were not locked!";
397 }
398
399 if (!evictProvisioningKey(ref)) return false;
400 return true;
401}
402
403bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
404 const KeyAuthentication& key_authentication, const KeyGeneration& gen,
405 KeyBuffer* key, bool keepOld) {
bigbiff7ba75002020-04-11 20:47:09 -0400406 if (pathExists(key_path)) {
bigbiffa957f072021-03-07 18:20:29 -0500407 LOG(INFO) << "Key exists, using: " << key_path;
408 if (!retrieveKey(key_path, key_authentication, key, keepOld)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400409 } else {
bigbiffa957f072021-03-07 18:20:29 -0500410 if (!gen.allow_gen) {
bigbiff7ba75002020-04-11 20:47:09 -0400411 LOG(ERROR) << "No key found in " << key_path;
412 return false;
413 }
bigbiffa957f072021-03-07 18:20:29 -0500414 LOG(INFO) << "Creating new key in " << key_path;
415 if (!::generateStorageKey(gen, key)) return false;
416 if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400417 }
418 return true;
419}
420
bigbiffa957f072021-03-07 18:20:29 -0500421bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy) {
422 key_serial_t device_keyring;
423 if (!fscryptKeyring(&device_keyring)) {
424 return false;
425 }
426
427 std::string ref = keyrefstring(policy.key_raw_ref);
428 auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
429 if (key_serial == -1) {
430 PLOG(ERROR) << "Failed to find fscrypt-provisioning key for " << ref
431 << " in session keyring";
432 return false;
433 }
434
435 LOG(INFO) << "Installing fscrypt-provisioning key for " << ref << " back into " << mountpoint
436 << " fs-keyring";
437
438 struct fscrypt_add_key_arg arg;
439 memset(&arg, 0, sizeof(arg));
440 if (!buildKeySpecifier(&arg.key_spec, policy)) return false;
441 arg.key_id = key_serial;
442 if (!installFsKeyringKey(mountpoint, policy.options, &arg)) return false;
443
444 return true;
445}