Whamcloud - gitweb
LU-13485 libcfs: FIELD_SIZEOF macro removed
[fs/lustre-release.git] / libcfs / libcfs / crypto / keyring.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Filesystem-level keyring for llcrypt
4  *
5  * Copyright 2019 Google LLC
6  */
7
8 /*
9  * This file implements management of llcrypt master keys in the
10  * filesystem-level keyring, including the ioctls:
11  *
12  * - LL_IOC_ADD_ENCRYPTION_KEY
13  * - LL_IOC_REMOVE_ENCRYPTION_KEY
14  * - LL_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
15  * - LL_IOC_GET_ENCRYPTION_KEY_STATUS
16  *
17  * See the "User API" section of Documentation/filesystems/llcrypt.rst for more
18  * information about these ioctls.
19  */
20 /*
21  * Linux commit 219d54332a09
22  * tags/v5.4
23  */
24
25 #include <crypto/skcipher.h>
26 #include <linux/key-type.h>
27 #include <linux/seq_file.h>
28 #include <libcfs/linux/linux-misc.h>
29
30 #include "llcrypt_private.h"
31
32 static void wipe_master_key_secret(struct llcrypt_master_key_secret *secret)
33 {
34         llcrypt_destroy_hkdf(&secret->hkdf);
35         memzero_explicit(secret, sizeof(*secret));
36 }
37
38 static void move_master_key_secret(struct llcrypt_master_key_secret *dst,
39                                    struct llcrypt_master_key_secret *src)
40 {
41         memcpy(dst, src, sizeof(*dst));
42         memzero_explicit(src, sizeof(*src));
43 }
44
45 static void free_master_key(struct llcrypt_master_key *mk)
46 {
47         size_t i;
48
49         wipe_master_key_secret(&mk->mk_secret);
50
51         for (i = 0; i < ARRAY_SIZE(mk->mk_mode_keys); i++)
52                 crypto_free_skcipher(mk->mk_mode_keys[i]);
53
54         key_put(mk->mk_users);
55         kzfree(mk);
56 }
57
58 static inline bool valid_key_spec(const struct llcrypt_key_specifier *spec)
59 {
60         if (spec->__reserved)
61                 return false;
62         return master_key_spec_len(spec) != 0;
63 }
64
65 static int llcrypt_key_instantiate(struct key *key,
66                                    struct key_preparsed_payload *prep)
67 {
68         key->payload.data[0] = (struct llcrypt_master_key *)prep->data;
69         return 0;
70 }
71
72 static void llcrypt_key_destroy(struct key *key)
73 {
74         free_master_key(key->payload.data[0]);
75 }
76
77 static void llcrypt_key_describe(const struct key *key, struct seq_file *m)
78 {
79         seq_puts(m, key->description);
80
81         if (key_is_positive(key)) {
82                 const struct llcrypt_master_key *mk = key->payload.data[0];
83
84                 if (!is_master_key_secret_present(&mk->mk_secret))
85                         seq_puts(m, ": secret removed");
86         }
87 }
88
89 /*
90  * Type of key in ->lsi_master_keys.  Each key of this type represents a master
91  * key which has been added to the filesystem.  Its payload is a
92  * 'struct llcrypt_master_key'.  The "." prefix in the key type name prevents
93  * users from adding keys of this type via the keyrings syscalls rather than via
94  * the intended method of LL_IOC_ADD_ENCRYPTION_KEY.
95  */
96 static struct key_type key_type_llcrypt = {
97         .name                   = "._llcrypt",
98         .instantiate            = llcrypt_key_instantiate,
99         .destroy                = llcrypt_key_destroy,
100         .describe               = llcrypt_key_describe,
101 };
102
103 static int llcrypt_user_key_instantiate(struct key *key,
104                                         struct key_preparsed_payload *prep)
105 {
106         /*
107          * We just charge LLCRYPT_MAX_KEY_SIZE bytes to the user's key quota for
108          * each key, regardless of the exact key size.  The amount of memory
109          * actually used is greater than the size of the raw key anyway.
110          */
111         return key_payload_reserve(key, LLCRYPT_MAX_KEY_SIZE);
112 }
113
114 static void llcrypt_user_key_describe(const struct key *key, struct seq_file *m)
115 {
116         seq_puts(m, key->description);
117 }
118
119 /*
120  * Type of key in ->mk_users.  Each key of this type represents a particular
121  * user who has added a particular master key.
122  *
123  * Note that the name of this key type really should be something like
124  * ".llcrypt-user" instead of simply ".llcrypt".  But the shorter name is chosen
125  * mainly for simplicity of presentation in /proc/keys when read by a non-root
126  * user.  And it is expected to be rare that a key is actually added by multiple
127  * users, since users should keep their encryption keys confidential.
128  */
129 static struct key_type key_type_llcrypt_user = {
130         .name                   = ".llcrypt",
131         .instantiate            = llcrypt_user_key_instantiate,
132         .describe               = llcrypt_user_key_describe,
133 };
134
135 /* Search ->lsi_master_keys or ->mk_users */
136 static struct key *search_llcrypt_keyring(struct key *keyring,
137                                           struct key_type *type,
138                                           const char *description)
139 {
140         /*
141          * We need to mark the keyring reference as "possessed" so that we
142          * acquire permission to search it, via the KEY_POS_SEARCH permission.
143          */
144         key_ref_t keyref = make_key_ref(keyring, true /* possessed */);
145
146 #ifdef HAVE_KEYRING_SEARCH_4ARGS
147         keyref = keyring_search(keyref, type, description, false);
148 #else
149         keyref = keyring_search(keyref, type, description);
150 #endif
151         if (IS_ERR(keyref)) {
152                 if (PTR_ERR(keyref) == -EAGAIN || /* not found */
153                     PTR_ERR(keyref) == -EKEYREVOKED) /* recently invalidated */
154                         keyref = ERR_PTR(-ENOKEY);
155                 return ERR_CAST(keyref);
156         }
157         return key_ref_to_ptr(keyref);
158 }
159
160 #define LLCRYPT_FS_KEYRING_DESCRIPTION_SIZE     \
161         (CONST_STRLEN("llcrypt-") + sizeof_field(struct super_block, s_id))
162
163 #define LLCRYPT_MK_DESCRIPTION_SIZE     (2 * LLCRYPT_KEY_IDENTIFIER_SIZE + 1)
164
165 #define LLCRYPT_MK_USERS_DESCRIPTION_SIZE       \
166         (CONST_STRLEN("llcrypt-") + 2 * LLCRYPT_KEY_IDENTIFIER_SIZE + \
167          CONST_STRLEN("-users") + 1)
168
169 #define LLCRYPT_MK_USER_DESCRIPTION_SIZE        \
170         (2 * LLCRYPT_KEY_IDENTIFIER_SIZE + CONST_STRLEN(".uid.") + 10 + 1)
171
172 static void format_fs_keyring_description(
173                         char description[LLCRYPT_FS_KEYRING_DESCRIPTION_SIZE],
174                         const struct super_block *sb)
175 {
176         sprintf(description, "llcrypt-%s", sb->s_id);
177 }
178
179 static void format_mk_description(
180                         char description[LLCRYPT_MK_DESCRIPTION_SIZE],
181                         const struct llcrypt_key_specifier *mk_spec)
182 {
183         sprintf(description, "%*phN",
184                 master_key_spec_len(mk_spec), (u8 *)&mk_spec->u);
185 }
186
187 static void format_mk_users_keyring_description(
188                         char description[LLCRYPT_MK_USERS_DESCRIPTION_SIZE],
189                         const u8 mk_identifier[LLCRYPT_KEY_IDENTIFIER_SIZE])
190 {
191         sprintf(description, "llcrypt-%*phN-users",
192                 LLCRYPT_KEY_IDENTIFIER_SIZE, mk_identifier);
193 }
194
195 static void format_mk_user_description(
196                         char description[LLCRYPT_MK_USER_DESCRIPTION_SIZE],
197                         const u8 mk_identifier[LLCRYPT_KEY_IDENTIFIER_SIZE])
198 {
199
200         sprintf(description, "%*phN.uid.%u", LLCRYPT_KEY_IDENTIFIER_SIZE,
201                 mk_identifier, __kuid_val(current_fsuid()));
202 }
203
204 /* Create ->lsi_master_keys if needed.  Synchronized by llcrypt_add_key_mutex. */
205 static int allocate_filesystem_keyring(struct super_block *sb)
206 {
207         char description[LLCRYPT_FS_KEYRING_DESCRIPTION_SIZE];
208         struct key *keyring;
209         struct lustre_sb_info *lsi = s2lsi(sb);
210
211         if (!lsi)
212                 return -EINVAL;
213
214         if (lsi->lsi_master_keys)
215                 return 0;
216
217         format_fs_keyring_description(description, sb);
218         keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
219                                 current_cred(), KEY_POS_SEARCH |
220                                   KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
221                                 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
222         if (IS_ERR(keyring))
223                 return PTR_ERR(keyring);
224
225         /* Pairs with READ_ONCE() in llcrypt_find_master_key() */
226         smp_store_release(&lsi->lsi_master_keys, keyring);
227         return 0;
228 }
229
230 void llcrypt_sb_free(struct super_block *sb)
231 {
232         struct lustre_sb_info *lsi = s2lsi(sb);
233
234         if (lsi != NULL) {
235                 key_put(lsi->lsi_master_keys);
236                 lsi->lsi_master_keys = NULL;
237         }
238 }
239 EXPORT_SYMBOL(llcrypt_sb_free);
240
241 /*
242  * Find the specified master key in ->lsi_master_keys.
243  * Returns ERR_PTR(-ENOKEY) if not found.
244  */
245 struct key *llcrypt_find_master_key(struct super_block *sb,
246                                     const struct llcrypt_key_specifier *mk_spec)
247 {
248         struct key *keyring;
249         char description[LLCRYPT_MK_DESCRIPTION_SIZE];
250         struct lustre_sb_info *lsi = s2lsi(sb);
251
252         if (!lsi)
253                 return ERR_PTR(-EINVAL);
254
255         /* pairs with smp_store_release() in allocate_filesystem_keyring() */
256         keyring = READ_ONCE(lsi->lsi_master_keys);
257         if (keyring == NULL)
258                 return ERR_PTR(-ENOKEY); /* No keyring yet, so no keys yet. */
259
260         format_mk_description(description, mk_spec);
261         return search_llcrypt_keyring(keyring, &key_type_llcrypt, description);
262 }
263
264 static int allocate_master_key_users_keyring(struct llcrypt_master_key *mk)
265 {
266         char description[LLCRYPT_MK_USERS_DESCRIPTION_SIZE];
267         struct key *keyring;
268
269         format_mk_users_keyring_description(description,
270                                             mk->mk_spec.u.identifier);
271         keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
272                                 current_cred(), KEY_POS_SEARCH |
273                                   KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
274                                 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
275         if (IS_ERR(keyring))
276                 return PTR_ERR(keyring);
277
278         mk->mk_users = keyring;
279         return 0;
280 }
281
282 /*
283  * Find the current user's "key" in the master key's ->mk_users.
284  * Returns ERR_PTR(-ENOKEY) if not found.
285  */
286 static struct key *find_master_key_user(struct llcrypt_master_key *mk)
287 {
288         char description[LLCRYPT_MK_USER_DESCRIPTION_SIZE];
289
290         format_mk_user_description(description, mk->mk_spec.u.identifier);
291         return search_llcrypt_keyring(mk->mk_users, &key_type_llcrypt_user,
292                                       description);
293 }
294
295 /*
296  * Give the current user a "key" in ->mk_users.  This charges the user's quota
297  * and marks the master key as added by the current user, so that it cannot be
298  * removed by another user with the key.  Either the master key's key->sem must
299  * be held for write, or the master key must be still undergoing initialization.
300  */
301 static int add_master_key_user(struct llcrypt_master_key *mk)
302 {
303         char description[LLCRYPT_MK_USER_DESCRIPTION_SIZE];
304         struct key *mk_user;
305         int err;
306
307         format_mk_user_description(description, mk->mk_spec.u.identifier);
308         mk_user = key_alloc(&key_type_llcrypt_user, description,
309                             current_fsuid(), current_gid(), current_cred(),
310                             KEY_POS_SEARCH | KEY_USR_VIEW, 0, NULL);
311         if (IS_ERR(mk_user))
312                 return PTR_ERR(mk_user);
313
314         err = key_instantiate_and_link(mk_user, NULL, 0, mk->mk_users, NULL);
315         key_put(mk_user);
316         return err;
317 }
318
319 /*
320  * Remove the current user's "key" from ->mk_users.
321  * The master key's key->sem must be held for write.
322  *
323  * Returns 0 if removed, -ENOKEY if not found, or another -errno code.
324  */
325 static int remove_master_key_user(struct llcrypt_master_key *mk)
326 {
327         struct key *mk_user;
328         int err;
329
330         mk_user = find_master_key_user(mk);
331         if (IS_ERR(mk_user))
332                 return PTR_ERR(mk_user);
333         err = key_unlink(mk->mk_users, mk_user);
334         key_put(mk_user);
335         return err;
336 }
337
338 /*
339  * Allocate a new llcrypt_master_key which contains the given secret, set it as
340  * the payload of a new 'struct key' of type llcrypt, and link the 'struct key'
341  * into the given keyring.  Synchronized by llcrypt_add_key_mutex.
342  */
343 static int add_new_master_key(struct llcrypt_master_key_secret *secret,
344                               const struct llcrypt_key_specifier *mk_spec,
345                               struct key *keyring)
346 {
347         struct llcrypt_master_key *mk;
348         char description[LLCRYPT_MK_DESCRIPTION_SIZE];
349         struct key *key;
350         int err;
351
352         mk = kzalloc(sizeof(*mk), GFP_KERNEL);
353         if (!mk)
354                 return -ENOMEM;
355
356         mk->mk_spec = *mk_spec;
357
358         move_master_key_secret(&mk->mk_secret, secret);
359         init_rwsem(&mk->mk_secret_sem);
360
361         refcount_set(&mk->mk_refcount, 1); /* secret is present */
362         INIT_LIST_HEAD(&mk->mk_decrypted_inodes);
363         spin_lock_init(&mk->mk_decrypted_inodes_lock);
364
365         if (mk_spec->type == LLCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
366                 err = allocate_master_key_users_keyring(mk);
367                 if (err)
368                         goto out_free_mk;
369                 err = add_master_key_user(mk);
370                 if (err)
371                         goto out_free_mk;
372         }
373
374         /*
375          * Note that we don't charge this key to anyone's quota, since when
376          * ->mk_users is in use those keys are charged instead, and otherwise
377          * (when ->mk_users isn't in use) only root can add these keys.
378          */
379         format_mk_description(description, mk_spec);
380         key = key_alloc(&key_type_llcrypt, description,
381                         GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),
382                         KEY_POS_SEARCH | KEY_USR_SEARCH | KEY_USR_VIEW,
383                         KEY_ALLOC_NOT_IN_QUOTA, NULL);
384         if (IS_ERR(key)) {
385                 err = PTR_ERR(key);
386                 goto out_free_mk;
387         }
388         err = key_instantiate_and_link(key, mk, sizeof(*mk), keyring, NULL);
389         key_put(key);
390         if (err)
391                 goto out_free_mk;
392
393         return 0;
394
395 out_free_mk:
396         free_master_key(mk);
397         return err;
398 }
399
400 #define KEY_DEAD        1
401
402 static int add_existing_master_key(struct llcrypt_master_key *mk,
403                                    struct llcrypt_master_key_secret *secret)
404 {
405         struct key *mk_user;
406         bool rekey;
407         int err;
408
409         /*
410          * If the current user is already in ->mk_users, then there's nothing to
411          * do.  (Not applicable for v1 policy keys, which have NULL ->mk_users.)
412          */
413         if (mk->mk_users) {
414                 mk_user = find_master_key_user(mk);
415                 if (mk_user != ERR_PTR(-ENOKEY)) {
416                         if (IS_ERR(mk_user))
417                                 return PTR_ERR(mk_user);
418                         key_put(mk_user);
419                         return 0;
420                 }
421         }
422
423         /* If we'll be re-adding ->mk_secret, try to take the reference. */
424         rekey = !is_master_key_secret_present(&mk->mk_secret);
425         if (rekey && !refcount_inc_not_zero(&mk->mk_refcount))
426                 return KEY_DEAD;
427
428         /* Add the current user to ->mk_users, if applicable. */
429         if (mk->mk_users) {
430                 err = add_master_key_user(mk);
431                 if (err) {
432                         if (rekey && refcount_dec_and_test(&mk->mk_refcount))
433                                 return KEY_DEAD;
434                         return err;
435                 }
436         }
437
438         /* Re-add the secret if needed. */
439         if (rekey) {
440                 down_write(&mk->mk_secret_sem);
441                 move_master_key_secret(&mk->mk_secret, secret);
442                 up_write(&mk->mk_secret_sem);
443         }
444         return 0;
445 }
446
447 static int add_master_key(struct super_block *sb,
448                           struct llcrypt_master_key_secret *secret,
449                           const struct llcrypt_key_specifier *mk_spec)
450 {
451         static DEFINE_MUTEX(llcrypt_add_key_mutex);
452         struct key *key;
453         struct lustre_sb_info *lsi = s2lsi(sb);
454         int err;
455
456         if (!lsi)
457                 return -EINVAL;
458
459         mutex_lock(&llcrypt_add_key_mutex); /* serialize find + link */
460 retry:
461         key = llcrypt_find_master_key(sb, mk_spec);
462         if (IS_ERR(key)) {
463                 err = PTR_ERR(key);
464                 if (err != -ENOKEY)
465                         goto out_unlock;
466                 /* Didn't find the key in ->lsi_master_keys.  Add it. */
467                 err = allocate_filesystem_keyring(sb);
468                 if (err)
469                         goto out_unlock;
470                 err = add_new_master_key(secret, mk_spec,
471                                          lsi->lsi_master_keys);
472         } else {
473                 /*
474                  * Found the key in ->lsi_master_keys.  Re-add the secret if
475                  * needed, and add the user to ->mk_users if needed.
476                  */
477                 down_write(&key->sem);
478                 err = add_existing_master_key(key->payload.data[0], secret);
479                 up_write(&key->sem);
480                 if (err == KEY_DEAD) {
481                         /* Key being removed or needs to be removed */
482                         key_invalidate(key);
483                         key_put(key);
484                         goto retry;
485                 }
486                 key_put(key);
487         }
488 out_unlock:
489         mutex_unlock(&llcrypt_add_key_mutex);
490         return err;
491 }
492
493 /*
494  * Add a master encryption key to the filesystem, causing all files which were
495  * encrypted with it to appear "unlocked" (decrypted) when accessed.
496  *
497  * When adding a key for use by v1 encryption policies, this ioctl is
498  * privileged, and userspace must provide the 'key_descriptor'.
499  *
500  * When adding a key for use by v2+ encryption policies, this ioctl is
501  * unprivileged.  This is needed, in general, to allow non-root users to use
502  * encryption without encountering the visibility problems of process-subscribed
503  * keyrings and the inability to properly remove keys.  This works by having
504  * each key identified by its cryptographically secure hash --- the
505  * 'key_identifier'.  The cryptographic hash ensures that a malicious user
506  * cannot add the wrong key for a given identifier.  Furthermore, each added key
507  * is charged to the appropriate user's quota for the keyrings service, which
508  * prevents a malicious user from adding too many keys.  Finally, we forbid a
509  * user from removing a key while other users have added it too, which prevents
510  * a user who knows another user's key from causing a denial-of-service by
511  * removing it at an inopportune time.  (We tolerate that a user who knows a key
512  * can prevent other users from removing it.)
513  *
514  * For more details, see the "LL_IOC_ADD_ENCRYPTION_KEY" section of
515  * Documentation/filesystems/llcrypt.rst.
516  */
517 int llcrypt_ioctl_add_key(struct file *filp, void __user *_uarg)
518 {
519         struct super_block *sb = file_inode(filp)->i_sb;
520         struct llcrypt_add_key_arg __user *uarg = _uarg;
521         struct llcrypt_add_key_arg arg;
522         struct llcrypt_master_key_secret secret;
523         int err;
524
525         if (copy_from_user(&arg, uarg, sizeof(arg)))
526                 return -EFAULT;
527
528         if (!valid_key_spec(&arg.key_spec))
529                 return -EINVAL;
530
531         if (arg.raw_size < LLCRYPT_MIN_KEY_SIZE ||
532             arg.raw_size > LLCRYPT_MAX_KEY_SIZE)
533                 return -EINVAL;
534
535         if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
536                 return -EINVAL;
537
538         memset(&secret, 0, sizeof(secret));
539         secret.size = arg.raw_size;
540         err = -EFAULT;
541         if (copy_from_user(secret.raw, uarg->raw, secret.size))
542                 goto out_wipe_secret;
543
544         switch (arg.key_spec.type) {
545         case LLCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
546                 /*
547                  * Only root can add keys that are identified by an arbitrary
548                  * descriptor rather than by a cryptographic hash --- since
549                  * otherwise a malicious user could add the wrong key.
550                  */
551                 err = -EACCES;
552                 if (!capable(CAP_SYS_ADMIN))
553                         goto out_wipe_secret;
554                 break;
555         case LLCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
556                 err = llcrypt_init_hkdf(&secret.hkdf, secret.raw, secret.size);
557                 if (err)
558                         goto out_wipe_secret;
559
560                 /*
561                  * Now that the HKDF context is initialized, the raw key is no
562                  * longer needed.
563                  */
564                 memzero_explicit(secret.raw, secret.size);
565
566                 /* Calculate the key identifier and return it to userspace. */
567                 err = llcrypt_hkdf_expand(&secret.hkdf,
568                                           HKDF_CONTEXT_KEY_IDENTIFIER,
569                                           NULL, 0, arg.key_spec.u.identifier,
570                                           LLCRYPT_KEY_IDENTIFIER_SIZE);
571                 if (err)
572                         goto out_wipe_secret;
573                 err = -EFAULT;
574                 if (copy_to_user(uarg->key_spec.u.identifier,
575                                  arg.key_spec.u.identifier,
576                                  LLCRYPT_KEY_IDENTIFIER_SIZE))
577                         goto out_wipe_secret;
578                 break;
579         default:
580                 WARN_ON(1);
581                 err = -EINVAL;
582                 goto out_wipe_secret;
583         }
584
585         err = add_master_key(sb, &secret, &arg.key_spec);
586 out_wipe_secret:
587         wipe_master_key_secret(&secret);
588         return err;
589 }
590 EXPORT_SYMBOL_GPL(llcrypt_ioctl_add_key);
591
592 /*
593  * Verify that the current user has added a master key with the given identifier
594  * (returns -ENOKEY if not).  This is needed to prevent a user from encrypting
595  * their files using some other user's key which they don't actually know.
596  * Cryptographically this isn't much of a problem, but the semantics of this
597  * would be a bit weird, so it's best to just forbid it.
598  *
599  * The system administrator (CAP_FOWNER) can override this, which should be
600  * enough for any use cases where encryption policies are being set using keys
601  * that were chosen ahead of time but aren't available at the moment.
602  *
603  * Note that the key may have already removed by the time this returns, but
604  * that's okay; we just care whether the key was there at some point.
605  *
606  * Return: 0 if the key is added, -ENOKEY if it isn't, or another -errno code
607  */
608 int llcrypt_verify_key_added(struct super_block *sb,
609                              const u8 identifier[LLCRYPT_KEY_IDENTIFIER_SIZE])
610 {
611         struct llcrypt_key_specifier mk_spec;
612         struct key *key, *mk_user;
613         struct llcrypt_master_key *mk;
614         int err;
615
616         mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
617         memcpy(mk_spec.u.identifier, identifier, LLCRYPT_KEY_IDENTIFIER_SIZE);
618
619         key = llcrypt_find_master_key(sb, &mk_spec);
620         if (IS_ERR(key)) {
621                 err = PTR_ERR(key);
622                 goto out;
623         }
624         mk = key->payload.data[0];
625         mk_user = find_master_key_user(mk);
626         if (IS_ERR(mk_user)) {
627                 err = PTR_ERR(mk_user);
628         } else {
629                 key_put(mk_user);
630                 err = 0;
631         }
632         key_put(key);
633 out:
634         if (err == -ENOKEY && capable(CAP_FOWNER))
635                 err = 0;
636         return err;
637 }
638
639 /*
640  * Try to evict the inode's dentries from the dentry cache.  If the inode is a
641  * directory, then it can have at most one dentry; however, that dentry may be
642  * pinned by child dentries, so first try to evict the children too.
643  */
644 static void shrink_dcache_inode(struct inode *inode)
645 {
646         struct dentry *dentry;
647
648         if (S_ISDIR(inode->i_mode)) {
649                 dentry = d_find_any_alias(inode);
650                 if (dentry) {
651                         shrink_dcache_parent(dentry);
652                         dput(dentry);
653                 }
654         }
655         d_prune_aliases(inode);
656 }
657
658 static void evict_dentries_for_decrypted_inodes(struct llcrypt_master_key *mk)
659 {
660         struct llcrypt_info *ci;
661         struct inode *inode;
662         struct inode *toput_inode = NULL;
663
664         spin_lock(&mk->mk_decrypted_inodes_lock);
665
666         list_for_each_entry(ci, &mk->mk_decrypted_inodes, ci_master_key_link) {
667                 inode = ci->ci_inode;
668                 if (igrab(inode) == NULL)
669                         continue;
670                 spin_unlock(&mk->mk_decrypted_inodes_lock);
671
672                 shrink_dcache_inode(inode);
673                 iput(toput_inode);
674                 toput_inode = inode;
675
676                 spin_lock(&mk->mk_decrypted_inodes_lock);
677         }
678
679         spin_unlock(&mk->mk_decrypted_inodes_lock);
680         iput(toput_inode);
681 }
682
683 static int check_for_busy_inodes(struct super_block *sb,
684                                  struct llcrypt_master_key *mk)
685 {
686         struct list_head *pos;
687         size_t busy_count = 0;
688         unsigned long ino;
689         struct dentry *dentry;
690         char _path[256];
691         char *path = NULL;
692
693         spin_lock(&mk->mk_decrypted_inodes_lock);
694
695         list_for_each(pos, &mk->mk_decrypted_inodes)
696                 busy_count++;
697
698         if (busy_count == 0) {
699                 spin_unlock(&mk->mk_decrypted_inodes_lock);
700                 return 0;
701         }
702
703         {
704                 /* select an example file to show for debugging purposes */
705                 struct inode *inode =
706                         list_first_entry(&mk->mk_decrypted_inodes,
707                                          struct llcrypt_info,
708                                          ci_master_key_link)->ci_inode;
709                 ino = inode->i_ino;
710                 dentry = d_find_alias(inode);
711         }
712         spin_unlock(&mk->mk_decrypted_inodes_lock);
713
714         if (dentry) {
715                 path = dentry_path_raw(dentry, _path, sizeof(_path));
716                 dput(dentry);
717         }
718         if (IS_ERR_OR_NULL(path))
719                 path = "(unknown)";
720
721         llcrypt_warn(NULL,
722                      "%s: %zu inode(s) still busy after removing key with %s %*phN, including ino %lu (%s)",
723                      sb->s_id, busy_count, master_key_spec_type(&mk->mk_spec),
724                      master_key_spec_len(&mk->mk_spec), (u8 *)&mk->mk_spec.u,
725                      ino, path);
726         return -EBUSY;
727 }
728
729 static int try_to_lock_encrypted_files(struct super_block *sb,
730                                        struct llcrypt_master_key *mk)
731 {
732         int err1;
733         int err2;
734
735         /*
736          * An inode can't be evicted while it is dirty or has dirty pages.
737          * Thus, we first have to clean the inodes in ->mk_decrypted_inodes.
738          *
739          * Just do it the easy way: call sync_filesystem().  It's overkill, but
740          * it works, and it's more important to minimize the amount of caches we
741          * drop than the amount of data we sync.  Also, unprivileged users can
742          * already call sync_filesystem() via sys_syncfs() or sys_sync().
743          */
744         down_read(&sb->s_umount);
745         err1 = sync_filesystem(sb);
746         up_read(&sb->s_umount);
747         /* If a sync error occurs, still try to evict as much as possible. */
748
749         /*
750          * Inodes are pinned by their dentries, so we have to evict their
751          * dentries.  shrink_dcache_sb() would suffice, but would be overkill
752          * and inappropriate for use by unprivileged users.  So instead go
753          * through the inodes' alias lists and try to evict each dentry.
754          */
755         evict_dentries_for_decrypted_inodes(mk);
756
757         /*
758          * evict_dentries_for_decrypted_inodes() already iput() each inode in
759          * the list; any inodes for which that dropped the last reference will
760          * have been evicted due to llcrypt_drop_inode() detecting the key
761          * removal and telling the VFS to evict the inode.  So to finish, we
762          * just need to check whether any inodes couldn't be evicted.
763          */
764         err2 = check_for_busy_inodes(sb, mk);
765
766         return err1 ?: err2;
767 }
768
769 /*
770  * Try to remove an llcrypt master encryption key.
771  *
772  * LL_IOC_REMOVE_ENCRYPTION_KEY (all_users=false) removes the current user's
773  * claim to the key, then removes the key itself if no other users have claims.
774  * LL_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS (all_users=true) always removes the
775  * key itself.
776  *
777  * To "remove the key itself", first we wipe the actual master key secret, so
778  * that no more inodes can be unlocked with it.  Then we try to evict all cached
779  * inodes that had been unlocked with the key.
780  *
781  * If all inodes were evicted, then we unlink the llcrypt_master_key from the
782  * keyring.  Otherwise it remains in the keyring in the "incompletely removed"
783  * state (without the actual secret key) where it tracks the list of remaining
784  * inodes.  Userspace can execute the ioctl again later to retry eviction, or
785  * alternatively can re-add the secret key again.
786  *
787  * For more details, see the "Removing keys" section of
788  * Documentation/filesystems/llcrypt.rst.
789  */
790 static int do_remove_key(struct file *filp, void __user *_uarg, bool all_users)
791 {
792         struct super_block *sb = file_inode(filp)->i_sb;
793         struct llcrypt_remove_key_arg __user *uarg = _uarg;
794         struct llcrypt_remove_key_arg arg;
795         struct key *key;
796         struct llcrypt_master_key *mk;
797         u32 status_flags = 0;
798         int err;
799         bool dead;
800
801         if (copy_from_user(&arg, uarg, sizeof(arg)))
802                 return -EFAULT;
803
804         if (!valid_key_spec(&arg.key_spec))
805                 return -EINVAL;
806
807         if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
808                 return -EINVAL;
809
810         /*
811          * Only root can add and remove keys that are identified by an arbitrary
812          * descriptor rather than by a cryptographic hash.
813          */
814         if (arg.key_spec.type == LLCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
815             !capable(CAP_SYS_ADMIN))
816                 return -EACCES;
817
818         /* Find the key being removed. */
819         key = llcrypt_find_master_key(sb, &arg.key_spec);
820         if (IS_ERR(key))
821                 return PTR_ERR(key);
822         mk = key->payload.data[0];
823
824         down_write(&key->sem);
825
826         /* If relevant, remove current user's (or all users) claim to the key */
827         if (mk->mk_users && mk->mk_users->keys.nr_leaves_on_tree != 0) {
828                 if (all_users)
829                         err = keyring_clear(mk->mk_users);
830                 else
831                         err = remove_master_key_user(mk);
832                 if (err) {
833                         up_write(&key->sem);
834                         goto out_put_key;
835                 }
836                 if (mk->mk_users->keys.nr_leaves_on_tree != 0) {
837                         /*
838                          * Other users have still added the key too.  We removed
839                          * the current user's claim to the key, but we still
840                          * can't remove the key itself.
841                          */
842                         status_flags |=
843                                 LLCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS;
844                         err = 0;
845                         up_write(&key->sem);
846                         goto out_put_key;
847                 }
848         }
849
850         /* No user claims remaining.  Go ahead and wipe the secret. */
851         dead = false;
852         if (is_master_key_secret_present(&mk->mk_secret)) {
853                 down_write(&mk->mk_secret_sem);
854                 wipe_master_key_secret(&mk->mk_secret);
855                 dead = refcount_dec_and_test(&mk->mk_refcount);
856                 up_write(&mk->mk_secret_sem);
857         }
858         up_write(&key->sem);
859         if (dead) {
860                 /*
861                  * No inodes reference the key, and we wiped the secret, so the
862                  * key object is free to be removed from the keyring.
863                  */
864                 key_invalidate(key);
865                 err = 0;
866         } else {
867                 /* Some inodes still reference this key; try to evict them. */
868                 err = try_to_lock_encrypted_files(sb, mk);
869                 if (err == -EBUSY) {
870                         status_flags |=
871                                 LLCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY;
872                         err = 0;
873                 }
874         }
875         /*
876          * We return 0 if we successfully did something: removed a claim to the
877          * key, wiped the secret, or tried locking the files again.  Users need
878          * to check the informational status flags if they care whether the key
879          * has been fully removed including all files locked.
880          */
881 out_put_key:
882         key_put(key);
883         if (err == 0)
884                 err = put_user(status_flags, &uarg->removal_status_flags);
885         return err;
886 }
887
888 int llcrypt_ioctl_remove_key(struct file *filp, void __user *uarg)
889 {
890         return do_remove_key(filp, uarg, false);
891 }
892 EXPORT_SYMBOL_GPL(llcrypt_ioctl_remove_key);
893
894 int llcrypt_ioctl_remove_key_all_users(struct file *filp, void __user *uarg)
895 {
896         if (!capable(CAP_SYS_ADMIN))
897                 return -EACCES;
898         return do_remove_key(filp, uarg, true);
899 }
900 EXPORT_SYMBOL_GPL(llcrypt_ioctl_remove_key_all_users);
901
902 /*
903  * Retrieve the status of an llcrypt master encryption key.
904  *
905  * We set ->status to indicate whether the key is absent, present, or
906  * incompletely removed.  "Incompletely removed" means that the master key
907  * secret has been removed, but some files which had been unlocked with it are
908  * still in use.  This field allows applications to easily determine the state
909  * of an encrypted directory without using a hack such as trying to open a
910  * regular file in it (which can confuse the "incompletely removed" state with
911  * absent or present).
912  *
913  * In addition, for v2 policy keys we allow applications to determine, via
914  * ->status_flags and ->user_count, whether the key has been added by the
915  * current user, by other users, or by both.  Most applications should not need
916  * this, since ordinarily only one user should know a given key.  However, if a
917  * secret key is shared by multiple users, applications may wish to add an
918  * already-present key to prevent other users from removing it.  This ioctl can
919  * be used to check whether that really is the case before the work is done to
920  * add the key --- which might e.g. require prompting the user for a passphrase.
921  *
922  * For more details, see the "LL_IOC_GET_ENCRYPTION_KEY_STATUS" section of
923  * Documentation/filesystems/llcrypt.rst.
924  */
925 int llcrypt_ioctl_get_key_status(struct file *filp, void __user *uarg)
926 {
927         struct super_block *sb = file_inode(filp)->i_sb;
928         struct llcrypt_get_key_status_arg arg;
929         struct key *key;
930         struct llcrypt_master_key *mk;
931         int err;
932
933         if (copy_from_user(&arg, uarg, sizeof(arg)))
934                 return -EFAULT;
935
936         if (!valid_key_spec(&arg.key_spec))
937                 return -EINVAL;
938
939         if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
940                 return -EINVAL;
941
942         arg.status_flags = 0;
943         arg.user_count = 0;
944         memset(arg.__out_reserved, 0, sizeof(arg.__out_reserved));
945
946         key = llcrypt_find_master_key(sb, &arg.key_spec);
947         if (IS_ERR(key)) {
948                 if (key != ERR_PTR(-ENOKEY))
949                         return PTR_ERR(key);
950                 arg.status = LLCRYPT_KEY_STATUS_ABSENT;
951                 err = 0;
952                 goto out;
953         }
954         mk = key->payload.data[0];
955         down_read(&key->sem);
956
957         if (!is_master_key_secret_present(&mk->mk_secret)) {
958                 arg.status = LLCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED;
959                 err = 0;
960                 goto out_release_key;
961         }
962
963         arg.status = LLCRYPT_KEY_STATUS_PRESENT;
964         if (mk->mk_users) {
965                 struct key *mk_user;
966
967                 arg.user_count = mk->mk_users->keys.nr_leaves_on_tree;
968                 mk_user = find_master_key_user(mk);
969                 if (!IS_ERR(mk_user)) {
970                         arg.status_flags |=
971                                 LLCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF;
972                         key_put(mk_user);
973                 } else if (mk_user != ERR_PTR(-ENOKEY)) {
974                         err = PTR_ERR(mk_user);
975                         goto out_release_key;
976                 }
977         }
978         err = 0;
979 out_release_key:
980         up_read(&key->sem);
981         key_put(key);
982 out:
983         if (!err && copy_to_user(uarg, &arg, sizeof(arg)))
984                 err = -EFAULT;
985         return err;
986 }
987 EXPORT_SYMBOL_GPL(llcrypt_ioctl_get_key_status);
988
989 int __init llcrypt_init_keyring(void)
990 {
991         int err;
992
993         err = register_key_type(&key_type_llcrypt);
994         if (err)
995                 return err;
996
997         err = register_key_type(&key_type_llcrypt_user);
998         if (err)
999                 goto err_unregister_llcrypt;
1000
1001         return 0;
1002
1003 err_unregister_llcrypt:
1004         unregister_key_type(&key_type_llcrypt);
1005         return err;
1006 }
1007
1008 void __exit llcrypt_exit_keyring(void)
1009 {
1010         unregister_key_type(&key_type_llcrypt_user);
1011         unregister_key_type(&key_type_llcrypt);
1012 }