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