1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Filesystem-level keyring for fscrypt
4 *
5 * Copyright 2019 Google LLC
6 */
7
8 /*
9 * This file implements management of fscrypt master keys in the
10 * filesystem-level keyring, including the ioctls:
11 *
12 * - FS_IOC_ADD_ENCRYPTION_KEY
13 * - FS_IOC_REMOVE_ENCRYPTION_KEY
14 * - FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
15 * - FS_IOC_GET_ENCRYPTION_KEY_STATUS
16 *
17 * See the "User API" section of Documentation/filesystems/fscrypt.rst for more
18 * information about these ioctls.
19 */
20
21 #include <linux/unaligned.h>
22 #include <crypto/skcipher.h>
23 #include <linux/key-type.h>
24 #include <linux/random.h>
25 #include <linux/seq_file.h>
26
27 #include "fscrypt_private.h"
28
29 /* The master encryption keys for a filesystem (->s_master_keys) */
30 struct fscrypt_keyring {
31 /*
32 * Lock that protects ->key_hashtable. It does *not* protect the
33 * fscrypt_master_key structs themselves.
34 */
35 spinlock_t lock;
36
37 /* Hash table that maps fscrypt_key_specifier to fscrypt_master_key */
38 struct hlist_head key_hashtable[128];
39 };
40
wipe_master_key_secret(struct fscrypt_master_key_secret * secret)41 static void wipe_master_key_secret(struct fscrypt_master_key_secret *secret)
42 {
43 fscrypt_destroy_hkdf(&secret->hkdf);
44 memzero_explicit(secret, sizeof(*secret));
45 }
46
move_master_key_secret(struct fscrypt_master_key_secret * dst,struct fscrypt_master_key_secret * src)47 static void move_master_key_secret(struct fscrypt_master_key_secret *dst,
48 struct fscrypt_master_key_secret *src)
49 {
50 memcpy(dst, src, sizeof(*dst));
51 memzero_explicit(src, sizeof(*src));
52 }
53
fscrypt_free_master_key(struct rcu_head * head)54 static void fscrypt_free_master_key(struct rcu_head *head)
55 {
56 struct fscrypt_master_key *mk =
57 container_of(head, struct fscrypt_master_key, mk_rcu_head);
58 /*
59 * The master key secret and any embedded subkeys should have already
60 * been wiped when the last active reference to the fscrypt_master_key
61 * struct was dropped; doing it here would be unnecessarily late.
62 * Nevertheless, use kfree_sensitive() in case anything was missed.
63 */
64 kfree_sensitive(mk);
65 }
66
fscrypt_put_master_key(struct fscrypt_master_key * mk)67 void fscrypt_put_master_key(struct fscrypt_master_key *mk)
68 {
69 if (!refcount_dec_and_test(&mk->mk_struct_refs))
70 return;
71 /*
72 * No structural references left, so free ->mk_users, and also free the
73 * fscrypt_master_key struct itself after an RCU grace period ensures
74 * that concurrent keyring lookups can no longer find it.
75 */
76 WARN_ON_ONCE(refcount_read(&mk->mk_active_refs) != 0);
77 if (mk->mk_users) {
78 /* Clear the keyring so the quota gets released right away. */
79 keyring_clear(mk->mk_users);
80 key_put(mk->mk_users);
81 mk->mk_users = NULL;
82 }
83 call_rcu(&mk->mk_rcu_head, fscrypt_free_master_key);
84 }
85
fscrypt_put_master_key_activeref(struct super_block * sb,struct fscrypt_master_key * mk)86 void fscrypt_put_master_key_activeref(struct super_block *sb,
87 struct fscrypt_master_key *mk)
88 {
89 size_t i;
90
91 if (!refcount_dec_and_test(&mk->mk_active_refs))
92 return;
93 /*
94 * No active references left, so complete the full removal of this
95 * fscrypt_master_key struct by removing it from the keyring and
96 * destroying any subkeys embedded in it.
97 */
98
99 if (WARN_ON_ONCE(!sb->s_master_keys))
100 return;
101 spin_lock(&sb->s_master_keys->lock);
102 hlist_del_rcu(&mk->mk_node);
103 spin_unlock(&sb->s_master_keys->lock);
104
105 /*
106 * ->mk_active_refs == 0 implies that ->mk_present is false and
107 * ->mk_decrypted_inodes is empty.
108 */
109 WARN_ON_ONCE(mk->mk_present);
110 WARN_ON_ONCE(!list_empty(&mk->mk_decrypted_inodes));
111
112 for (i = 0; i <= FSCRYPT_MODE_MAX; i++) {
113 fscrypt_destroy_prepared_key(
114 sb, &mk->mk_direct_keys[i]);
115 fscrypt_destroy_prepared_key(
116 sb, &mk->mk_iv_ino_lblk_64_keys[i]);
117 fscrypt_destroy_prepared_key(
118 sb, &mk->mk_iv_ino_lblk_32_keys[i]);
119 }
120 memzero_explicit(&mk->mk_ino_hash_key,
121 sizeof(mk->mk_ino_hash_key));
122 mk->mk_ino_hash_key_initialized = false;
123
124 /* Drop the structural ref associated with the active refs. */
125 fscrypt_put_master_key(mk);
126 }
127
128 /*
129 * This transitions the key state from present to incompletely removed, and then
130 * potentially to absent (depending on whether inodes remain).
131 */
fscrypt_initiate_key_removal(struct super_block * sb,struct fscrypt_master_key * mk)132 static void fscrypt_initiate_key_removal(struct super_block *sb,
133 struct fscrypt_master_key *mk)
134 {
135 WRITE_ONCE(mk->mk_present, false);
136 wipe_master_key_secret(&mk->mk_secret);
137 fscrypt_put_master_key_activeref(sb, mk);
138 }
139
valid_key_spec(const struct fscrypt_key_specifier * spec)140 static inline bool valid_key_spec(const struct fscrypt_key_specifier *spec)
141 {
142 if (spec->__reserved)
143 return false;
144 return master_key_spec_len(spec) != 0;
145 }
146
fscrypt_user_key_instantiate(struct key * key,struct key_preparsed_payload * prep)147 static int fscrypt_user_key_instantiate(struct key *key,
148 struct key_preparsed_payload *prep)
149 {
150 /*
151 * We just charge FSCRYPT_MAX_STANDARD_KEY_SIZE bytes to the user's key
152 * quota for each key, regardless of the exact key size. The amount of
153 * memory actually used is greater than the size of the raw key anyway.
154 */
155 return key_payload_reserve(key, FSCRYPT_MAX_STANDARD_KEY_SIZE);
156 }
157
fscrypt_user_key_describe(const struct key * key,struct seq_file * m)158 static void fscrypt_user_key_describe(const struct key *key, struct seq_file *m)
159 {
160 seq_puts(m, key->description);
161 }
162
163 /*
164 * Type of key in ->mk_users. Each key of this type represents a particular
165 * user who has added a particular master key.
166 *
167 * Note that the name of this key type really should be something like
168 * ".fscrypt-user" instead of simply ".fscrypt". But the shorter name is chosen
169 * mainly for simplicity of presentation in /proc/keys when read by a non-root
170 * user. And it is expected to be rare that a key is actually added by multiple
171 * users, since users should keep their encryption keys confidential.
172 */
173 static struct key_type key_type_fscrypt_user = {
174 .name = ".fscrypt",
175 .instantiate = fscrypt_user_key_instantiate,
176 .describe = fscrypt_user_key_describe,
177 };
178
179 #define FSCRYPT_MK_USERS_DESCRIPTION_SIZE \
180 (CONST_STRLEN("fscrypt-") + 2 * FSCRYPT_KEY_IDENTIFIER_SIZE + \
181 CONST_STRLEN("-users") + 1)
182
183 #define FSCRYPT_MK_USER_DESCRIPTION_SIZE \
184 (2 * FSCRYPT_KEY_IDENTIFIER_SIZE + CONST_STRLEN(".uid.") + 10 + 1)
185
format_mk_users_keyring_description(char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE],const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])186 static void format_mk_users_keyring_description(
187 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE],
188 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
189 {
190 sprintf(description, "fscrypt-%*phN-users",
191 FSCRYPT_KEY_IDENTIFIER_SIZE, mk_identifier);
192 }
193
format_mk_user_description(char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE],const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])194 static void format_mk_user_description(
195 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE],
196 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
197 {
198
199 sprintf(description, "%*phN.uid.%u", FSCRYPT_KEY_IDENTIFIER_SIZE,
200 mk_identifier, __kuid_val(current_fsuid()));
201 }
202
203 /* Create ->s_master_keys if needed. Synchronized by fscrypt_add_key_mutex. */
allocate_filesystem_keyring(struct super_block * sb)204 static int allocate_filesystem_keyring(struct super_block *sb)
205 {
206 struct fscrypt_keyring *keyring;
207
208 if (sb->s_master_keys)
209 return 0;
210
211 keyring = kzalloc(sizeof(*keyring), GFP_KERNEL);
212 if (!keyring)
213 return -ENOMEM;
214 spin_lock_init(&keyring->lock);
215 /*
216 * Pairs with the smp_load_acquire() in fscrypt_find_master_key().
217 * I.e., here we publish ->s_master_keys with a RELEASE barrier so that
218 * concurrent tasks can ACQUIRE it.
219 */
220 smp_store_release(&sb->s_master_keys, keyring);
221 return 0;
222 }
223
224 /*
225 * Release all encryption keys that have been added to the filesystem, along
226 * with the keyring that contains them.
227 *
228 * This is called at unmount time, after all potentially-encrypted inodes have
229 * been evicted. The filesystem's underlying block device(s) are still
230 * available at this time; this is important because after user file accesses
231 * have been allowed, this function may need to evict keys from the keyslots of
232 * an inline crypto engine, which requires the block device(s).
233 */
fscrypt_destroy_keyring(struct super_block * sb)234 void fscrypt_destroy_keyring(struct super_block *sb)
235 {
236 struct fscrypt_keyring *keyring = sb->s_master_keys;
237 size_t i;
238
239 if (!keyring)
240 return;
241
242 for (i = 0; i < ARRAY_SIZE(keyring->key_hashtable); i++) {
243 struct hlist_head *bucket = &keyring->key_hashtable[i];
244 struct fscrypt_master_key *mk;
245 struct hlist_node *tmp;
246
247 hlist_for_each_entry_safe(mk, tmp, bucket, mk_node) {
248 /*
249 * Since all potentially-encrypted inodes were already
250 * evicted, every key remaining in the keyring should
251 * have an empty inode list, and should only still be in
252 * the keyring due to the single active ref associated
253 * with ->mk_present. There should be no structural
254 * refs beyond the one associated with the active ref.
255 */
256 WARN_ON_ONCE(refcount_read(&mk->mk_active_refs) != 1);
257 WARN_ON_ONCE(refcount_read(&mk->mk_struct_refs) != 1);
258 WARN_ON_ONCE(!mk->mk_present);
259 fscrypt_initiate_key_removal(sb, mk);
260 }
261 }
262 kfree_sensitive(keyring);
263 sb->s_master_keys = NULL;
264 }
265
266 static struct hlist_head *
fscrypt_mk_hash_bucket(struct fscrypt_keyring * keyring,const struct fscrypt_key_specifier * mk_spec)267 fscrypt_mk_hash_bucket(struct fscrypt_keyring *keyring,
268 const struct fscrypt_key_specifier *mk_spec)
269 {
270 /*
271 * Since key specifiers should be "random" values, it is sufficient to
272 * use a trivial hash function that just takes the first several bits of
273 * the key specifier.
274 */
275 unsigned long i = get_unaligned((unsigned long *)&mk_spec->u);
276
277 return &keyring->key_hashtable[i % ARRAY_SIZE(keyring->key_hashtable)];
278 }
279
280 /*
281 * Find the specified master key struct in ->s_master_keys and take a structural
282 * ref to it. The structural ref guarantees that the key struct continues to
283 * exist, but it does *not* guarantee that ->s_master_keys continues to contain
284 * the key struct. The structural ref needs to be dropped by
285 * fscrypt_put_master_key(). Returns NULL if the key struct is not found.
286 */
287 struct fscrypt_master_key *
fscrypt_find_master_key(struct super_block * sb,const struct fscrypt_key_specifier * mk_spec)288 fscrypt_find_master_key(struct super_block *sb,
289 const struct fscrypt_key_specifier *mk_spec)
290 {
291 struct fscrypt_keyring *keyring;
292 struct hlist_head *bucket;
293 struct fscrypt_master_key *mk;
294
295 /*
296 * Pairs with the smp_store_release() in allocate_filesystem_keyring().
297 * I.e., another task can publish ->s_master_keys concurrently,
298 * executing a RELEASE barrier. We need to use smp_load_acquire() here
299 * to safely ACQUIRE the memory the other task published.
300 */
301 keyring = smp_load_acquire(&sb->s_master_keys);
302 if (keyring == NULL)
303 return NULL; /* No keyring yet, so no keys yet. */
304
305 bucket = fscrypt_mk_hash_bucket(keyring, mk_spec);
306 rcu_read_lock();
307 switch (mk_spec->type) {
308 case FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
309 hlist_for_each_entry_rcu(mk, bucket, mk_node) {
310 if (mk->mk_spec.type ==
311 FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
312 memcmp(mk->mk_spec.u.descriptor,
313 mk_spec->u.descriptor,
314 FSCRYPT_KEY_DESCRIPTOR_SIZE) == 0 &&
315 refcount_inc_not_zero(&mk->mk_struct_refs))
316 goto out;
317 }
318 break;
319 case FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
320 hlist_for_each_entry_rcu(mk, bucket, mk_node) {
321 if (mk->mk_spec.type ==
322 FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
323 memcmp(mk->mk_spec.u.identifier,
324 mk_spec->u.identifier,
325 FSCRYPT_KEY_IDENTIFIER_SIZE) == 0 &&
326 refcount_inc_not_zero(&mk->mk_struct_refs))
327 goto out;
328 }
329 break;
330 }
331 mk = NULL;
332 out:
333 rcu_read_unlock();
334 return mk;
335 }
336
allocate_master_key_users_keyring(struct fscrypt_master_key * mk)337 static int allocate_master_key_users_keyring(struct fscrypt_master_key *mk)
338 {
339 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE];
340 struct key *keyring;
341
342 format_mk_users_keyring_description(description,
343 mk->mk_spec.u.identifier);
344 keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
345 current_cred(), KEY_POS_SEARCH |
346 KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
347 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
348 if (IS_ERR(keyring))
349 return PTR_ERR(keyring);
350
351 mk->mk_users = keyring;
352 return 0;
353 }
354
355 /*
356 * Find the current user's "key" in the master key's ->mk_users.
357 * Returns ERR_PTR(-ENOKEY) if not found.
358 */
find_master_key_user(struct fscrypt_master_key * mk)359 static struct key *find_master_key_user(struct fscrypt_master_key *mk)
360 {
361 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
362 key_ref_t keyref;
363
364 format_mk_user_description(description, mk->mk_spec.u.identifier);
365
366 /*
367 * We need to mark the keyring reference as "possessed" so that we
368 * acquire permission to search it, via the KEY_POS_SEARCH permission.
369 */
370 keyref = keyring_search(make_key_ref(mk->mk_users, true /*possessed*/),
371 &key_type_fscrypt_user, description, false);
372 if (IS_ERR(keyref)) {
373 if (PTR_ERR(keyref) == -EAGAIN || /* not found */
374 PTR_ERR(keyref) == -EKEYREVOKED) /* recently invalidated */
375 keyref = ERR_PTR(-ENOKEY);
376 return ERR_CAST(keyref);
377 }
378 return key_ref_to_ptr(keyref);
379 }
380
381 /*
382 * Give the current user a "key" in ->mk_users. This charges the user's quota
383 * and marks the master key as added by the current user, so that it cannot be
384 * removed by another user with the key. Either ->mk_sem must be held for
385 * write, or the master key must be still undergoing initialization.
386 */
add_master_key_user(struct fscrypt_master_key * mk)387 static int add_master_key_user(struct fscrypt_master_key *mk)
388 {
389 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
390 struct key *mk_user;
391 int err;
392
393 format_mk_user_description(description, mk->mk_spec.u.identifier);
394 mk_user = key_alloc(&key_type_fscrypt_user, description,
395 current_fsuid(), current_gid(), current_cred(),
396 KEY_POS_SEARCH | KEY_USR_VIEW, 0, NULL);
397 if (IS_ERR(mk_user))
398 return PTR_ERR(mk_user);
399
400 err = key_instantiate_and_link(mk_user, NULL, 0, mk->mk_users, NULL);
401 key_put(mk_user);
402 return err;
403 }
404
405 /*
406 * Remove the current user's "key" from ->mk_users.
407 * ->mk_sem must be held for write.
408 *
409 * Returns 0 if removed, -ENOKEY if not found, or another -errno code.
410 */
remove_master_key_user(struct fscrypt_master_key * mk)411 static int remove_master_key_user(struct fscrypt_master_key *mk)
412 {
413 struct key *mk_user;
414 int err;
415
416 mk_user = find_master_key_user(mk);
417 if (IS_ERR(mk_user))
418 return PTR_ERR(mk_user);
419 err = key_unlink(mk->mk_users, mk_user);
420 key_put(mk_user);
421 return err;
422 }
423
424 /*
425 * Allocate a new fscrypt_master_key, transfer the given secret over to it, and
426 * insert it into sb->s_master_keys.
427 */
add_new_master_key(struct super_block * sb,struct fscrypt_master_key_secret * secret,const struct fscrypt_key_specifier * mk_spec)428 static int add_new_master_key(struct super_block *sb,
429 struct fscrypt_master_key_secret *secret,
430 const struct fscrypt_key_specifier *mk_spec)
431 {
432 struct fscrypt_keyring *keyring = sb->s_master_keys;
433 struct fscrypt_master_key *mk;
434 int err;
435
436 mk = kzalloc(sizeof(*mk), GFP_KERNEL);
437 if (!mk)
438 return -ENOMEM;
439
440 init_rwsem(&mk->mk_sem);
441 refcount_set(&mk->mk_struct_refs, 1);
442 mk->mk_spec = *mk_spec;
443
444 INIT_LIST_HEAD(&mk->mk_decrypted_inodes);
445 spin_lock_init(&mk->mk_decrypted_inodes_lock);
446
447 if (mk_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
448 err = allocate_master_key_users_keyring(mk);
449 if (err)
450 goto out_put;
451 err = add_master_key_user(mk);
452 if (err)
453 goto out_put;
454 }
455
456 move_master_key_secret(&mk->mk_secret, secret);
457 mk->mk_present = true;
458 refcount_set(&mk->mk_active_refs, 1); /* ->mk_present is true */
459
460 spin_lock(&keyring->lock);
461 hlist_add_head_rcu(&mk->mk_node,
462 fscrypt_mk_hash_bucket(keyring, mk_spec));
463 spin_unlock(&keyring->lock);
464 return 0;
465
466 out_put:
467 fscrypt_put_master_key(mk);
468 return err;
469 }
470
471 #define KEY_DEAD 1
472
add_existing_master_key(struct fscrypt_master_key * mk,struct fscrypt_master_key_secret * secret)473 static int add_existing_master_key(struct fscrypt_master_key *mk,
474 struct fscrypt_master_key_secret *secret)
475 {
476 int err;
477
478 /*
479 * If the current user is already in ->mk_users, then there's nothing to
480 * do. Otherwise, we need to add the user to ->mk_users. (Neither is
481 * applicable for v1 policy keys, which have NULL ->mk_users.)
482 */
483 if (mk->mk_users) {
484 struct key *mk_user = find_master_key_user(mk);
485
486 if (mk_user != ERR_PTR(-ENOKEY)) {
487 if (IS_ERR(mk_user))
488 return PTR_ERR(mk_user);
489 key_put(mk_user);
490 return 0;
491 }
492 err = add_master_key_user(mk);
493 if (err)
494 return err;
495 }
496
497 /* If the key is incompletely removed, make it present again. */
498 if (!mk->mk_present) {
499 if (!refcount_inc_not_zero(&mk->mk_active_refs)) {
500 /*
501 * Raced with the last active ref being dropped, so the
502 * key has become, or is about to become, "absent".
503 * Therefore, we need to allocate a new key struct.
504 */
505 return KEY_DEAD;
506 }
507 move_master_key_secret(&mk->mk_secret, secret);
508 WRITE_ONCE(mk->mk_present, true);
509 }
510
511 return 0;
512 }
513
do_add_master_key(struct super_block * sb,struct fscrypt_master_key_secret * secret,const struct fscrypt_key_specifier * mk_spec)514 static int do_add_master_key(struct super_block *sb,
515 struct fscrypt_master_key_secret *secret,
516 const struct fscrypt_key_specifier *mk_spec)
517 {
518 static DEFINE_MUTEX(fscrypt_add_key_mutex);
519 struct fscrypt_master_key *mk;
520 int err;
521
522 mutex_lock(&fscrypt_add_key_mutex); /* serialize find + link */
523
524 mk = fscrypt_find_master_key(sb, mk_spec);
525 if (!mk) {
526 /* Didn't find the key in ->s_master_keys. Add it. */
527 err = allocate_filesystem_keyring(sb);
528 if (!err)
529 err = add_new_master_key(sb, secret, mk_spec);
530 } else {
531 /*
532 * Found the key in ->s_master_keys. Add the user to ->mk_users
533 * if needed, and make the key "present" again if possible.
534 */
535 down_write(&mk->mk_sem);
536 err = add_existing_master_key(mk, secret);
537 up_write(&mk->mk_sem);
538 if (err == KEY_DEAD) {
539 /*
540 * We found a key struct, but it's already been fully
541 * removed. Ignore the old struct and add a new one.
542 * fscrypt_add_key_mutex means we don't need to worry
543 * about concurrent adds.
544 */
545 err = add_new_master_key(sb, secret, mk_spec);
546 }
547 fscrypt_put_master_key(mk);
548 }
549 mutex_unlock(&fscrypt_add_key_mutex);
550 return err;
551 }
552
add_master_key(struct super_block * sb,struct fscrypt_master_key_secret * secret,struct fscrypt_key_specifier * key_spec)553 static int add_master_key(struct super_block *sb,
554 struct fscrypt_master_key_secret *secret,
555 struct fscrypt_key_specifier *key_spec)
556 {
557 int err;
558
559 if (key_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
560 u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE];
561 u8 *kdf_key = secret->raw;
562 unsigned int kdf_key_size = secret->size;
563 u8 keyid_kdf_ctx = HKDF_CONTEXT_KEY_IDENTIFIER;
564
565 /*
566 * For standard keys, the fscrypt master key is used directly as
567 * the fscrypt KDF key. For hardware-wrapped keys, we have to
568 * pass the master key to the hardware to derive the KDF key,
569 * which is then only used to derive non-file-contents subkeys.
570 */
571 if (secret->is_hw_wrapped) {
572 err = fscrypt_derive_sw_secret(sb, secret->raw,
573 secret->size, sw_secret);
574 if (err)
575 return err;
576 kdf_key = sw_secret;
577 kdf_key_size = sizeof(sw_secret);
578 }
579 err = fscrypt_init_hkdf(&secret->hkdf, kdf_key, kdf_key_size);
580 /*
581 * Now that the KDF context is initialized, the raw KDF key is
582 * no longer needed.
583 */
584 memzero_explicit(kdf_key, kdf_key_size);
585 if (err)
586 return err;
587
588 /* Calculate the key identifier */
589 err = fscrypt_hkdf_expand(&secret->hkdf, keyid_kdf_ctx, NULL, 0,
590 key_spec->u.identifier,
591 FSCRYPT_KEY_IDENTIFIER_SIZE);
592 if (err)
593 return err;
594 }
595 return do_add_master_key(sb, secret, key_spec);
596 }
597
fscrypt_provisioning_key_preparse(struct key_preparsed_payload * prep)598 static int fscrypt_provisioning_key_preparse(struct key_preparsed_payload *prep)
599 {
600 const struct fscrypt_provisioning_key_payload *payload = prep->data;
601
602 if (prep->datalen < sizeof(*payload) + FSCRYPT_MIN_KEY_SIZE ||
603 prep->datalen > sizeof(*payload) + FSCRYPT_MAX_ANY_KEY_SIZE)
604 return -EINVAL;
605
606 if (payload->type != FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
607 payload->type != FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER)
608 return -EINVAL;
609
610 if (payload->__reserved)
611 return -EINVAL;
612
613 prep->payload.data[0] = kmemdup(payload, prep->datalen, GFP_KERNEL);
614 if (!prep->payload.data[0])
615 return -ENOMEM;
616
617 prep->quotalen = prep->datalen;
618 return 0;
619 }
620
fscrypt_provisioning_key_free_preparse(struct key_preparsed_payload * prep)621 static void fscrypt_provisioning_key_free_preparse(
622 struct key_preparsed_payload *prep)
623 {
624 kfree_sensitive(prep->payload.data[0]);
625 }
626
fscrypt_provisioning_key_describe(const struct key * key,struct seq_file * m)627 static void fscrypt_provisioning_key_describe(const struct key *key,
628 struct seq_file *m)
629 {
630 seq_puts(m, key->description);
631 if (key_is_positive(key)) {
632 const struct fscrypt_provisioning_key_payload *payload =
633 key->payload.data[0];
634
635 seq_printf(m, ": %u [%u]", key->datalen, payload->type);
636 }
637 }
638
fscrypt_provisioning_key_destroy(struct key * key)639 static void fscrypt_provisioning_key_destroy(struct key *key)
640 {
641 kfree_sensitive(key->payload.data[0]);
642 }
643
644 static struct key_type key_type_fscrypt_provisioning = {
645 .name = "fscrypt-provisioning",
646 .preparse = fscrypt_provisioning_key_preparse,
647 .free_preparse = fscrypt_provisioning_key_free_preparse,
648 .instantiate = generic_key_instantiate,
649 .describe = fscrypt_provisioning_key_describe,
650 .destroy = fscrypt_provisioning_key_destroy,
651 };
652
653 /*
654 * Retrieve the raw key from the Linux keyring key specified by 'key_id', and
655 * store it into 'secret'.
656 *
657 * The key must be of type "fscrypt-provisioning" and must have the field
658 * fscrypt_provisioning_key_payload::type set to 'type', indicating that it's
659 * only usable with fscrypt with the particular KDF version identified by
660 * 'type'. We don't use the "logon" key type because there's no way to
661 * completely restrict the use of such keys; they can be used by any kernel API
662 * that accepts "logon" keys and doesn't require a specific service prefix.
663 *
664 * The ability to specify the key via Linux keyring key is intended for cases
665 * where userspace needs to re-add keys after the filesystem is unmounted and
666 * re-mounted. Most users should just provide the raw key directly instead.
667 */
get_keyring_key(u32 key_id,u32 type,struct fscrypt_master_key_secret * secret)668 static int get_keyring_key(u32 key_id, u32 type,
669 struct fscrypt_master_key_secret *secret)
670 {
671 key_ref_t ref;
672 struct key *key;
673 const struct fscrypt_provisioning_key_payload *payload;
674 int err;
675
676 ref = lookup_user_key(key_id, 0, KEY_NEED_SEARCH);
677 if (IS_ERR(ref))
678 return PTR_ERR(ref);
679 key = key_ref_to_ptr(ref);
680
681 if (key->type != &key_type_fscrypt_provisioning)
682 goto bad_key;
683 payload = key->payload.data[0];
684
685 /* Don't allow fscrypt v1 keys to be used as v2 keys and vice versa. */
686 if (payload->type != type)
687 goto bad_key;
688
689 secret->size = key->datalen - sizeof(*payload);
690 memcpy(secret->raw, payload->raw, secret->size);
691 err = 0;
692 goto out_put;
693
694 bad_key:
695 err = -EKEYREJECTED;
696 out_put:
697 key_ref_put(ref);
698 return err;
699 }
700
701 /*
702 * Add a master encryption key to the filesystem, causing all files which were
703 * encrypted with it to appear "unlocked" (decrypted) when accessed.
704 *
705 * When adding a key for use by v1 encryption policies, this ioctl is
706 * privileged, and userspace must provide the 'key_descriptor'.
707 *
708 * When adding a key for use by v2+ encryption policies, this ioctl is
709 * unprivileged. This is needed, in general, to allow non-root users to use
710 * encryption without encountering the visibility problems of process-subscribed
711 * keyrings and the inability to properly remove keys. This works by having
712 * each key identified by its cryptographically secure hash --- the
713 * 'key_identifier'. The cryptographic hash ensures that a malicious user
714 * cannot add the wrong key for a given identifier. Furthermore, each added key
715 * is charged to the appropriate user's quota for the keyrings service, which
716 * prevents a malicious user from adding too many keys. Finally, we forbid a
717 * user from removing a key while other users have added it too, which prevents
718 * a user who knows another user's key from causing a denial-of-service by
719 * removing it at an inopportune time. (We tolerate that a user who knows a key
720 * can prevent other users from removing it.)
721 *
722 * For more details, see the "FS_IOC_ADD_ENCRYPTION_KEY" section of
723 * Documentation/filesystems/fscrypt.rst.
724 */
fscrypt_ioctl_add_key(struct file * filp,void __user * _uarg)725 int fscrypt_ioctl_add_key(struct file *filp, void __user *_uarg)
726 {
727 struct super_block *sb = file_inode(filp)->i_sb;
728 struct fscrypt_add_key_arg __user *uarg = _uarg;
729 struct fscrypt_add_key_arg arg;
730 struct fscrypt_master_key_secret secret;
731 int err;
732
733 if (copy_from_user(&arg, uarg, sizeof(arg)))
734 return -EFAULT;
735
736 if (!valid_key_spec(&arg.key_spec))
737 return -EINVAL;
738
739 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
740 return -EINVAL;
741
742 /*
743 * Only root can add keys that are identified by an arbitrary descriptor
744 * rather than by a cryptographic hash --- since otherwise a malicious
745 * user could add the wrong key.
746 */
747 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
748 !capable(CAP_SYS_ADMIN))
749 return -EACCES;
750
751 memset(&secret, 0, sizeof(secret));
752
753 if (arg.__flags) {
754 if (arg.__flags & ~__FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED)
755 return -EINVAL;
756 if (arg.key_spec.type != FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER)
757 return -EINVAL;
758 secret.is_hw_wrapped = true;
759 }
760
761 if (arg.key_id) {
762 if (arg.raw_size != 0)
763 return -EINVAL;
764 err = get_keyring_key(arg.key_id, arg.key_spec.type, &secret);
765 if (err)
766 goto out_wipe_secret;
767 err = -EINVAL;
768 if (secret.size > FSCRYPT_MAX_STANDARD_KEY_SIZE &&
769 !secret.is_hw_wrapped)
770 goto out_wipe_secret;
771 } else {
772 if (arg.raw_size < FSCRYPT_MIN_KEY_SIZE ||
773 arg.raw_size > (secret.is_hw_wrapped ?
774 FSCRYPT_MAX_HW_WRAPPED_KEY_SIZE :
775 FSCRYPT_MAX_STANDARD_KEY_SIZE))
776 return -EINVAL;
777 secret.size = arg.raw_size;
778 err = -EFAULT;
779 if (copy_from_user(secret.raw, uarg->raw, secret.size))
780 goto out_wipe_secret;
781 }
782
783 err = add_master_key(sb, &secret, &arg.key_spec);
784 if (err)
785 goto out_wipe_secret;
786
787 /* Return the key identifier to userspace, if applicable */
788 err = -EFAULT;
789 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
790 copy_to_user(uarg->key_spec.u.identifier, arg.key_spec.u.identifier,
791 FSCRYPT_KEY_IDENTIFIER_SIZE))
792 goto out_wipe_secret;
793 err = 0;
794 out_wipe_secret:
795 wipe_master_key_secret(&secret);
796 return err;
797 }
798 EXPORT_SYMBOL_GPL(fscrypt_ioctl_add_key);
799
800 static void
fscrypt_get_test_dummy_secret(struct fscrypt_master_key_secret * secret)801 fscrypt_get_test_dummy_secret(struct fscrypt_master_key_secret *secret)
802 {
803 static u8 test_key[FSCRYPT_MAX_STANDARD_KEY_SIZE];
804
805 get_random_once(test_key, sizeof(test_key));
806
807 memset(secret, 0, sizeof(*secret));
808 secret->size = sizeof(test_key);
809 memcpy(secret->raw, test_key, sizeof(test_key));
810 }
811
fscrypt_get_test_dummy_key_identifier(u8 key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])812 int fscrypt_get_test_dummy_key_identifier(
813 u8 key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
814 {
815 struct fscrypt_master_key_secret secret;
816 int err;
817
818 fscrypt_get_test_dummy_secret(&secret);
819
820 err = fscrypt_init_hkdf(&secret.hkdf, secret.raw, secret.size);
821 if (err)
822 goto out;
823 err = fscrypt_hkdf_expand(&secret.hkdf, HKDF_CONTEXT_KEY_IDENTIFIER,
824 NULL, 0, key_identifier,
825 FSCRYPT_KEY_IDENTIFIER_SIZE);
826 out:
827 wipe_master_key_secret(&secret);
828 return err;
829 }
830
831 /**
832 * fscrypt_add_test_dummy_key() - add the test dummy encryption key
833 * @sb: the filesystem instance to add the key to
834 * @key_spec: the key specifier of the test dummy encryption key
835 *
836 * Add the key for the test_dummy_encryption mount option to the filesystem. To
837 * prevent misuse of this mount option, a per-boot random key is used instead of
838 * a hardcoded one. This makes it so that any encrypted files created using
839 * this option won't be accessible after a reboot.
840 *
841 * Return: 0 on success, -errno on failure
842 */
fscrypt_add_test_dummy_key(struct super_block * sb,struct fscrypt_key_specifier * key_spec)843 int fscrypt_add_test_dummy_key(struct super_block *sb,
844 struct fscrypt_key_specifier *key_spec)
845 {
846 struct fscrypt_master_key_secret secret;
847 int err;
848
849 fscrypt_get_test_dummy_secret(&secret);
850 err = add_master_key(sb, &secret, key_spec);
851 wipe_master_key_secret(&secret);
852 return err;
853 }
854
855 /*
856 * Verify that the current user has added a master key with the given identifier
857 * (returns -ENOKEY if not). This is needed to prevent a user from encrypting
858 * their files using some other user's key which they don't actually know.
859 * Cryptographically this isn't much of a problem, but the semantics of this
860 * would be a bit weird, so it's best to just forbid it.
861 *
862 * The system administrator (CAP_FOWNER) can override this, which should be
863 * enough for any use cases where encryption policies are being set using keys
864 * that were chosen ahead of time but aren't available at the moment.
865 *
866 * Note that the key may have already removed by the time this returns, but
867 * that's okay; we just care whether the key was there at some point.
868 *
869 * Return: 0 if the key is added, -ENOKEY if it isn't, or another -errno code
870 */
fscrypt_verify_key_added(struct super_block * sb,const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])871 int fscrypt_verify_key_added(struct super_block *sb,
872 const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
873 {
874 struct fscrypt_key_specifier mk_spec;
875 struct fscrypt_master_key *mk;
876 struct key *mk_user;
877 int err;
878
879 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
880 memcpy(mk_spec.u.identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
881
882 mk = fscrypt_find_master_key(sb, &mk_spec);
883 if (!mk) {
884 err = -ENOKEY;
885 goto out;
886 }
887 down_read(&mk->mk_sem);
888 mk_user = find_master_key_user(mk);
889 if (IS_ERR(mk_user)) {
890 err = PTR_ERR(mk_user);
891 } else {
892 key_put(mk_user);
893 err = 0;
894 }
895 up_read(&mk->mk_sem);
896 fscrypt_put_master_key(mk);
897 out:
898 if (err == -ENOKEY && capable(CAP_FOWNER))
899 err = 0;
900 return err;
901 }
902
903 /*
904 * Try to evict the inode's dentries from the dentry cache. If the inode is a
905 * directory, then it can have at most one dentry; however, that dentry may be
906 * pinned by child dentries, so first try to evict the children too.
907 */
shrink_dcache_inode(struct inode * inode)908 static void shrink_dcache_inode(struct inode *inode)
909 {
910 struct dentry *dentry;
911
912 if (S_ISDIR(inode->i_mode)) {
913 dentry = d_find_any_alias(inode);
914 if (dentry) {
915 shrink_dcache_parent(dentry);
916 dput(dentry);
917 }
918 }
919 d_prune_aliases(inode);
920 }
921
evict_dentries_for_decrypted_inodes(struct fscrypt_master_key * mk)922 static void evict_dentries_for_decrypted_inodes(struct fscrypt_master_key *mk)
923 {
924 struct fscrypt_inode_info *ci;
925 struct inode *inode;
926 struct inode *toput_inode = NULL;
927
928 spin_lock(&mk->mk_decrypted_inodes_lock);
929
930 list_for_each_entry(ci, &mk->mk_decrypted_inodes, ci_master_key_link) {
931 inode = ci->ci_inode;
932 spin_lock(&inode->i_lock);
933 if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
934 spin_unlock(&inode->i_lock);
935 continue;
936 }
937 __iget(inode);
938 spin_unlock(&inode->i_lock);
939 spin_unlock(&mk->mk_decrypted_inodes_lock);
940
941 shrink_dcache_inode(inode);
942 iput(toput_inode);
943 toput_inode = inode;
944
945 spin_lock(&mk->mk_decrypted_inodes_lock);
946 }
947
948 spin_unlock(&mk->mk_decrypted_inodes_lock);
949 iput(toput_inode);
950 }
951
check_for_busy_inodes(struct super_block * sb,struct fscrypt_master_key * mk)952 static int check_for_busy_inodes(struct super_block *sb,
953 struct fscrypt_master_key *mk)
954 {
955 struct list_head *pos;
956 size_t busy_count = 0;
957 unsigned long ino;
958 char ino_str[50] = "";
959
960 spin_lock(&mk->mk_decrypted_inodes_lock);
961
962 list_for_each(pos, &mk->mk_decrypted_inodes)
963 busy_count++;
964
965 if (busy_count == 0) {
966 spin_unlock(&mk->mk_decrypted_inodes_lock);
967 return 0;
968 }
969
970 {
971 /* select an example file to show for debugging purposes */
972 struct inode *inode =
973 list_first_entry(&mk->mk_decrypted_inodes,
974 struct fscrypt_inode_info,
975 ci_master_key_link)->ci_inode;
976 ino = inode->i_ino;
977 }
978 spin_unlock(&mk->mk_decrypted_inodes_lock);
979
980 /* If the inode is currently being created, ino may still be 0. */
981 if (ino)
982 snprintf(ino_str, sizeof(ino_str), ", including ino %lu", ino);
983
984 fscrypt_warn(NULL,
985 "%s: %zu inode(s) still busy after removing key with %s %*phN%s",
986 sb->s_id, busy_count, master_key_spec_type(&mk->mk_spec),
987 master_key_spec_len(&mk->mk_spec), (u8 *)&mk->mk_spec.u,
988 ino_str);
989 return -EBUSY;
990 }
991
try_to_lock_encrypted_files(struct super_block * sb,struct fscrypt_master_key * mk)992 static int try_to_lock_encrypted_files(struct super_block *sb,
993 struct fscrypt_master_key *mk)
994 {
995 int err1;
996 int err2;
997
998 /*
999 * An inode can't be evicted while it is dirty or has dirty pages.
1000 * Thus, we first have to clean the inodes in ->mk_decrypted_inodes.
1001 *
1002 * Just do it the easy way: call sync_filesystem(). It's overkill, but
1003 * it works, and it's more important to minimize the amount of caches we
1004 * drop than the amount of data we sync. Also, unprivileged users can
1005 * already call sync_filesystem() via sys_syncfs() or sys_sync().
1006 */
1007 down_read(&sb->s_umount);
1008 err1 = sync_filesystem(sb);
1009 up_read(&sb->s_umount);
1010 /* If a sync error occurs, still try to evict as much as possible. */
1011
1012 /*
1013 * Inodes are pinned by their dentries, so we have to evict their
1014 * dentries. shrink_dcache_sb() would suffice, but would be overkill
1015 * and inappropriate for use by unprivileged users. So instead go
1016 * through the inodes' alias lists and try to evict each dentry.
1017 */
1018 evict_dentries_for_decrypted_inodes(mk);
1019
1020 /*
1021 * evict_dentries_for_decrypted_inodes() already iput() each inode in
1022 * the list; any inodes for which that dropped the last reference will
1023 * have been evicted due to fscrypt_drop_inode() detecting the key
1024 * removal and telling the VFS to evict the inode. So to finish, we
1025 * just need to check whether any inodes couldn't be evicted.
1026 */
1027 err2 = check_for_busy_inodes(sb, mk);
1028
1029 return err1 ?: err2;
1030 }
1031
1032 /*
1033 * Try to remove an fscrypt master encryption key.
1034 *
1035 * FS_IOC_REMOVE_ENCRYPTION_KEY (all_users=false) removes the current user's
1036 * claim to the key, then removes the key itself if no other users have claims.
1037 * FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS (all_users=true) always removes the
1038 * key itself.
1039 *
1040 * To "remove the key itself", first we transition the key to the "incompletely
1041 * removed" state, so that no more inodes can be unlocked with it. Then we try
1042 * to evict all cached inodes that had been unlocked with the key.
1043 *
1044 * If all inodes were evicted, then we unlink the fscrypt_master_key from the
1045 * keyring. Otherwise it remains in the keyring in the "incompletely removed"
1046 * state where it tracks the list of remaining inodes. Userspace can execute
1047 * the ioctl again later to retry eviction, or alternatively can re-add the key.
1048 *
1049 * For more details, see the "Removing keys" section of
1050 * Documentation/filesystems/fscrypt.rst.
1051 */
do_remove_key(struct file * filp,void __user * _uarg,bool all_users)1052 static int do_remove_key(struct file *filp, void __user *_uarg, bool all_users)
1053 {
1054 struct super_block *sb = file_inode(filp)->i_sb;
1055 struct fscrypt_remove_key_arg __user *uarg = _uarg;
1056 struct fscrypt_remove_key_arg arg;
1057 struct fscrypt_master_key *mk;
1058 u32 status_flags = 0;
1059 int err;
1060 bool inodes_remain;
1061
1062 if (copy_from_user(&arg, uarg, sizeof(arg)))
1063 return -EFAULT;
1064
1065 if (!valid_key_spec(&arg.key_spec))
1066 return -EINVAL;
1067
1068 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
1069 return -EINVAL;
1070
1071 /*
1072 * Only root can add and remove keys that are identified by an arbitrary
1073 * descriptor rather than by a cryptographic hash.
1074 */
1075 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
1076 !capable(CAP_SYS_ADMIN))
1077 return -EACCES;
1078
1079 /* Find the key being removed. */
1080 mk = fscrypt_find_master_key(sb, &arg.key_spec);
1081 if (!mk)
1082 return -ENOKEY;
1083 down_write(&mk->mk_sem);
1084
1085 /* If relevant, remove current user's (or all users) claim to the key */
1086 if (mk->mk_users && mk->mk_users->keys.nr_leaves_on_tree != 0) {
1087 if (all_users)
1088 err = keyring_clear(mk->mk_users);
1089 else
1090 err = remove_master_key_user(mk);
1091 if (err) {
1092 up_write(&mk->mk_sem);
1093 goto out_put_key;
1094 }
1095 if (mk->mk_users->keys.nr_leaves_on_tree != 0) {
1096 /*
1097 * Other users have still added the key too. We removed
1098 * the current user's claim to the key, but we still
1099 * can't remove the key itself.
1100 */
1101 status_flags |=
1102 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS;
1103 err = 0;
1104 up_write(&mk->mk_sem);
1105 goto out_put_key;
1106 }
1107 }
1108
1109 /* No user claims remaining. Initiate removal of the key. */
1110 err = -ENOKEY;
1111 if (mk->mk_present) {
1112 fscrypt_initiate_key_removal(sb, mk);
1113 err = 0;
1114 }
1115 inodes_remain = refcount_read(&mk->mk_active_refs) > 0;
1116 up_write(&mk->mk_sem);
1117
1118 if (inodes_remain) {
1119 /* Some inodes still reference this key; try to evict them. */
1120 err = try_to_lock_encrypted_files(sb, mk);
1121 if (err == -EBUSY) {
1122 status_flags |=
1123 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY;
1124 err = 0;
1125 }
1126 }
1127 /*
1128 * We return 0 if we successfully did something: removed a claim to the
1129 * key, initiated removal of the key, or tried locking the files again.
1130 * Users need to check the informational status flags if they care
1131 * whether the key has been fully removed including all files locked.
1132 */
1133 out_put_key:
1134 fscrypt_put_master_key(mk);
1135 if (err == 0)
1136 err = put_user(status_flags, &uarg->removal_status_flags);
1137 return err;
1138 }
1139
fscrypt_ioctl_remove_key(struct file * filp,void __user * uarg)1140 int fscrypt_ioctl_remove_key(struct file *filp, void __user *uarg)
1141 {
1142 return do_remove_key(filp, uarg, false);
1143 }
1144 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key);
1145
fscrypt_ioctl_remove_key_all_users(struct file * filp,void __user * uarg)1146 int fscrypt_ioctl_remove_key_all_users(struct file *filp, void __user *uarg)
1147 {
1148 if (!capable(CAP_SYS_ADMIN))
1149 return -EACCES;
1150 return do_remove_key(filp, uarg, true);
1151 }
1152 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key_all_users);
1153
1154 /*
1155 * Retrieve the status of an fscrypt master encryption key.
1156 *
1157 * We set ->status to indicate whether the key is absent, present, or
1158 * incompletely removed. (For an explanation of what these statuses mean and
1159 * how they are represented internally, see struct fscrypt_master_key.) This
1160 * field allows applications to easily determine the status of an encrypted
1161 * directory without using a hack such as trying to open a regular file in it
1162 * (which can confuse the "incompletely removed" status with absent or present).
1163 *
1164 * In addition, for v2 policy keys we allow applications to determine, via
1165 * ->status_flags and ->user_count, whether the key has been added by the
1166 * current user, by other users, or by both. Most applications should not need
1167 * this, since ordinarily only one user should know a given key. However, if a
1168 * secret key is shared by multiple users, applications may wish to add an
1169 * already-present key to prevent other users from removing it. This ioctl can
1170 * be used to check whether that really is the case before the work is done to
1171 * add the key --- which might e.g. require prompting the user for a passphrase.
1172 *
1173 * For more details, see the "FS_IOC_GET_ENCRYPTION_KEY_STATUS" section of
1174 * Documentation/filesystems/fscrypt.rst.
1175 */
fscrypt_ioctl_get_key_status(struct file * filp,void __user * uarg)1176 int fscrypt_ioctl_get_key_status(struct file *filp, void __user *uarg)
1177 {
1178 struct super_block *sb = file_inode(filp)->i_sb;
1179 struct fscrypt_get_key_status_arg arg;
1180 struct fscrypt_master_key *mk;
1181 int err;
1182
1183 if (copy_from_user(&arg, uarg, sizeof(arg)))
1184 return -EFAULT;
1185
1186 if (!valid_key_spec(&arg.key_spec))
1187 return -EINVAL;
1188
1189 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
1190 return -EINVAL;
1191
1192 arg.status_flags = 0;
1193 arg.user_count = 0;
1194 memset(arg.__out_reserved, 0, sizeof(arg.__out_reserved));
1195
1196 mk = fscrypt_find_master_key(sb, &arg.key_spec);
1197 if (!mk) {
1198 arg.status = FSCRYPT_KEY_STATUS_ABSENT;
1199 err = 0;
1200 goto out;
1201 }
1202 down_read(&mk->mk_sem);
1203
1204 if (!mk->mk_present) {
1205 arg.status = refcount_read(&mk->mk_active_refs) > 0 ?
1206 FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED :
1207 FSCRYPT_KEY_STATUS_ABSENT /* raced with full removal */;
1208 err = 0;
1209 goto out_release_key;
1210 }
1211
1212 arg.status = FSCRYPT_KEY_STATUS_PRESENT;
1213 if (mk->mk_users) {
1214 struct key *mk_user;
1215
1216 arg.user_count = mk->mk_users->keys.nr_leaves_on_tree;
1217 mk_user = find_master_key_user(mk);
1218 if (!IS_ERR(mk_user)) {
1219 arg.status_flags |=
1220 FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF;
1221 key_put(mk_user);
1222 } else if (mk_user != ERR_PTR(-ENOKEY)) {
1223 err = PTR_ERR(mk_user);
1224 goto out_release_key;
1225 }
1226 }
1227 err = 0;
1228 out_release_key:
1229 up_read(&mk->mk_sem);
1230 fscrypt_put_master_key(mk);
1231 out:
1232 if (!err && copy_to_user(uarg, &arg, sizeof(arg)))
1233 err = -EFAULT;
1234 return err;
1235 }
1236 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_key_status);
1237
fscrypt_init_keyring(void)1238 int __init fscrypt_init_keyring(void)
1239 {
1240 int err;
1241
1242 err = register_key_type(&key_type_fscrypt_user);
1243 if (err)
1244 return err;
1245
1246 err = register_key_type(&key_type_fscrypt_provisioning);
1247 if (err)
1248 goto err_unregister_fscrypt_user;
1249
1250 return 0;
1251
1252 err_unregister_fscrypt_user:
1253 unregister_key_type(&key_type_fscrypt_user);
1254 return err;
1255 }
1256