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