Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Key setup facility for FS encryption support.
0004  *
0005  * Copyright (C) 2015, Google, Inc.
0006  *
0007  * Originally written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar.
0008  * Heavily modified since then.
0009  */
0010 
0011 #include <crypto/skcipher.h>
0012 #include <linux/key.h>
0013 #include <linux/random.h>
0014 
0015 #include "fscrypt_private.h"
0016 
0017 struct fscrypt_mode fscrypt_modes[] = {
0018     [FSCRYPT_MODE_AES_256_XTS] = {
0019         .friendly_name = "AES-256-XTS",
0020         .cipher_str = "xts(aes)",
0021         .keysize = 64,
0022         .security_strength = 32,
0023         .ivsize = 16,
0024         .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_256_XTS,
0025     },
0026     [FSCRYPT_MODE_AES_256_CTS] = {
0027         .friendly_name = "AES-256-CTS-CBC",
0028         .cipher_str = "cts(cbc(aes))",
0029         .keysize = 32,
0030         .security_strength = 32,
0031         .ivsize = 16,
0032     },
0033     [FSCRYPT_MODE_AES_128_CBC] = {
0034         .friendly_name = "AES-128-CBC-ESSIV",
0035         .cipher_str = "essiv(cbc(aes),sha256)",
0036         .keysize = 16,
0037         .security_strength = 16,
0038         .ivsize = 16,
0039         .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV,
0040     },
0041     [FSCRYPT_MODE_AES_128_CTS] = {
0042         .friendly_name = "AES-128-CTS-CBC",
0043         .cipher_str = "cts(cbc(aes))",
0044         .keysize = 16,
0045         .security_strength = 16,
0046         .ivsize = 16,
0047     },
0048     [FSCRYPT_MODE_ADIANTUM] = {
0049         .friendly_name = "Adiantum",
0050         .cipher_str = "adiantum(xchacha12,aes)",
0051         .keysize = 32,
0052         .security_strength = 32,
0053         .ivsize = 32,
0054         .blk_crypto_mode = BLK_ENCRYPTION_MODE_ADIANTUM,
0055     },
0056     [FSCRYPT_MODE_AES_256_HCTR2] = {
0057         .friendly_name = "AES-256-HCTR2",
0058         .cipher_str = "hctr2(aes)",
0059         .keysize = 32,
0060         .security_strength = 32,
0061         .ivsize = 32,
0062     },
0063 };
0064 
0065 static DEFINE_MUTEX(fscrypt_mode_key_setup_mutex);
0066 
0067 static struct fscrypt_mode *
0068 select_encryption_mode(const union fscrypt_policy *policy,
0069                const struct inode *inode)
0070 {
0071     BUILD_BUG_ON(ARRAY_SIZE(fscrypt_modes) != FSCRYPT_MODE_MAX + 1);
0072 
0073     if (S_ISREG(inode->i_mode))
0074         return &fscrypt_modes[fscrypt_policy_contents_mode(policy)];
0075 
0076     if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
0077         return &fscrypt_modes[fscrypt_policy_fnames_mode(policy)];
0078 
0079     WARN_ONCE(1, "fscrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
0080           inode->i_ino, (inode->i_mode & S_IFMT));
0081     return ERR_PTR(-EINVAL);
0082 }
0083 
0084 /* Create a symmetric cipher object for the given encryption mode and key */
0085 static struct crypto_skcipher *
0086 fscrypt_allocate_skcipher(struct fscrypt_mode *mode, const u8 *raw_key,
0087               const struct inode *inode)
0088 {
0089     struct crypto_skcipher *tfm;
0090     int err;
0091 
0092     tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
0093     if (IS_ERR(tfm)) {
0094         if (PTR_ERR(tfm) == -ENOENT) {
0095             fscrypt_warn(inode,
0096                      "Missing crypto API support for %s (API name: \"%s\")",
0097                      mode->friendly_name, mode->cipher_str);
0098             return ERR_PTR(-ENOPKG);
0099         }
0100         fscrypt_err(inode, "Error allocating '%s' transform: %ld",
0101                 mode->cipher_str, PTR_ERR(tfm));
0102         return tfm;
0103     }
0104     if (!xchg(&mode->logged_cryptoapi_impl, 1)) {
0105         /*
0106          * fscrypt performance can vary greatly depending on which
0107          * crypto algorithm implementation is used.  Help people debug
0108          * performance problems by logging the ->cra_driver_name the
0109          * first time a mode is used.
0110          */
0111         pr_info("fscrypt: %s using implementation \"%s\"\n",
0112             mode->friendly_name, crypto_skcipher_driver_name(tfm));
0113     }
0114     if (WARN_ON(crypto_skcipher_ivsize(tfm) != mode->ivsize)) {
0115         err = -EINVAL;
0116         goto err_free_tfm;
0117     }
0118     crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
0119     err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
0120     if (err)
0121         goto err_free_tfm;
0122 
0123     return tfm;
0124 
0125 err_free_tfm:
0126     crypto_free_skcipher(tfm);
0127     return ERR_PTR(err);
0128 }
0129 
0130 /*
0131  * Prepare the crypto transform object or blk-crypto key in @prep_key, given the
0132  * raw key, encryption mode (@ci->ci_mode), flag indicating which encryption
0133  * implementation (fs-layer or blk-crypto) will be used (@ci->ci_inlinecrypt),
0134  * and IV generation method (@ci->ci_policy.flags).
0135  */
0136 int fscrypt_prepare_key(struct fscrypt_prepared_key *prep_key,
0137             const u8 *raw_key, const struct fscrypt_info *ci)
0138 {
0139     struct crypto_skcipher *tfm;
0140 
0141     if (fscrypt_using_inline_encryption(ci))
0142         return fscrypt_prepare_inline_crypt_key(prep_key, raw_key, ci);
0143 
0144     tfm = fscrypt_allocate_skcipher(ci->ci_mode, raw_key, ci->ci_inode);
0145     if (IS_ERR(tfm))
0146         return PTR_ERR(tfm);
0147     /*
0148      * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
0149      * I.e., here we publish ->tfm with a RELEASE barrier so that
0150      * concurrent tasks can ACQUIRE it.  Note that this concurrency is only
0151      * possible for per-mode keys, not for per-file keys.
0152      */
0153     smp_store_release(&prep_key->tfm, tfm);
0154     return 0;
0155 }
0156 
0157 /* Destroy a crypto transform object and/or blk-crypto key. */
0158 void fscrypt_destroy_prepared_key(struct fscrypt_prepared_key *prep_key)
0159 {
0160     crypto_free_skcipher(prep_key->tfm);
0161     fscrypt_destroy_inline_crypt_key(prep_key);
0162 }
0163 
0164 /* Given a per-file encryption key, set up the file's crypto transform object */
0165 int fscrypt_set_per_file_enc_key(struct fscrypt_info *ci, const u8 *raw_key)
0166 {
0167     ci->ci_owns_key = true;
0168     return fscrypt_prepare_key(&ci->ci_enc_key, raw_key, ci);
0169 }
0170 
0171 static int setup_per_mode_enc_key(struct fscrypt_info *ci,
0172                   struct fscrypt_master_key *mk,
0173                   struct fscrypt_prepared_key *keys,
0174                   u8 hkdf_context, bool include_fs_uuid)
0175 {
0176     const struct inode *inode = ci->ci_inode;
0177     const struct super_block *sb = inode->i_sb;
0178     struct fscrypt_mode *mode = ci->ci_mode;
0179     const u8 mode_num = mode - fscrypt_modes;
0180     struct fscrypt_prepared_key *prep_key;
0181     u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
0182     u8 hkdf_info[sizeof(mode_num) + sizeof(sb->s_uuid)];
0183     unsigned int hkdf_infolen = 0;
0184     int err;
0185 
0186     if (WARN_ON(mode_num > FSCRYPT_MODE_MAX))
0187         return -EINVAL;
0188 
0189     prep_key = &keys[mode_num];
0190     if (fscrypt_is_key_prepared(prep_key, ci)) {
0191         ci->ci_enc_key = *prep_key;
0192         return 0;
0193     }
0194 
0195     mutex_lock(&fscrypt_mode_key_setup_mutex);
0196 
0197     if (fscrypt_is_key_prepared(prep_key, ci))
0198         goto done_unlock;
0199 
0200     BUILD_BUG_ON(sizeof(mode_num) != 1);
0201     BUILD_BUG_ON(sizeof(sb->s_uuid) != 16);
0202     BUILD_BUG_ON(sizeof(hkdf_info) != 17);
0203     hkdf_info[hkdf_infolen++] = mode_num;
0204     if (include_fs_uuid) {
0205         memcpy(&hkdf_info[hkdf_infolen], &sb->s_uuid,
0206                sizeof(sb->s_uuid));
0207         hkdf_infolen += sizeof(sb->s_uuid);
0208     }
0209     err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
0210                   hkdf_context, hkdf_info, hkdf_infolen,
0211                   mode_key, mode->keysize);
0212     if (err)
0213         goto out_unlock;
0214     err = fscrypt_prepare_key(prep_key, mode_key, ci);
0215     memzero_explicit(mode_key, mode->keysize);
0216     if (err)
0217         goto out_unlock;
0218 done_unlock:
0219     ci->ci_enc_key = *prep_key;
0220     err = 0;
0221 out_unlock:
0222     mutex_unlock(&fscrypt_mode_key_setup_mutex);
0223     return err;
0224 }
0225 
0226 /*
0227  * Derive a SipHash key from the given fscrypt master key and the given
0228  * application-specific information string.
0229  *
0230  * Note that the KDF produces a byte array, but the SipHash APIs expect the key
0231  * as a pair of 64-bit words.  Therefore, on big endian CPUs we have to do an
0232  * endianness swap in order to get the same results as on little endian CPUs.
0233  */
0234 static int fscrypt_derive_siphash_key(const struct fscrypt_master_key *mk,
0235                       u8 context, const u8 *info,
0236                       unsigned int infolen, siphash_key_t *key)
0237 {
0238     int err;
0239 
0240     err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf, context, info, infolen,
0241                   (u8 *)key, sizeof(*key));
0242     if (err)
0243         return err;
0244 
0245     BUILD_BUG_ON(sizeof(*key) != 16);
0246     BUILD_BUG_ON(ARRAY_SIZE(key->key) != 2);
0247     le64_to_cpus(&key->key[0]);
0248     le64_to_cpus(&key->key[1]);
0249     return 0;
0250 }
0251 
0252 int fscrypt_derive_dirhash_key(struct fscrypt_info *ci,
0253                    const struct fscrypt_master_key *mk)
0254 {
0255     int err;
0256 
0257     err = fscrypt_derive_siphash_key(mk, HKDF_CONTEXT_DIRHASH_KEY,
0258                      ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
0259                      &ci->ci_dirhash_key);
0260     if (err)
0261         return err;
0262     ci->ci_dirhash_key_initialized = true;
0263     return 0;
0264 }
0265 
0266 void fscrypt_hash_inode_number(struct fscrypt_info *ci,
0267                    const struct fscrypt_master_key *mk)
0268 {
0269     WARN_ON(ci->ci_inode->i_ino == 0);
0270     WARN_ON(!mk->mk_ino_hash_key_initialized);
0271 
0272     ci->ci_hashed_ino = (u32)siphash_1u64(ci->ci_inode->i_ino,
0273                           &mk->mk_ino_hash_key);
0274 }
0275 
0276 static int fscrypt_setup_iv_ino_lblk_32_key(struct fscrypt_info *ci,
0277                         struct fscrypt_master_key *mk)
0278 {
0279     int err;
0280 
0281     err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_32_keys,
0282                      HKDF_CONTEXT_IV_INO_LBLK_32_KEY, true);
0283     if (err)
0284         return err;
0285 
0286     /* pairs with smp_store_release() below */
0287     if (!smp_load_acquire(&mk->mk_ino_hash_key_initialized)) {
0288 
0289         mutex_lock(&fscrypt_mode_key_setup_mutex);
0290 
0291         if (mk->mk_ino_hash_key_initialized)
0292             goto unlock;
0293 
0294         err = fscrypt_derive_siphash_key(mk,
0295                          HKDF_CONTEXT_INODE_HASH_KEY,
0296                          NULL, 0, &mk->mk_ino_hash_key);
0297         if (err)
0298             goto unlock;
0299         /* pairs with smp_load_acquire() above */
0300         smp_store_release(&mk->mk_ino_hash_key_initialized, true);
0301 unlock:
0302         mutex_unlock(&fscrypt_mode_key_setup_mutex);
0303         if (err)
0304             return err;
0305     }
0306 
0307     /*
0308      * New inodes may not have an inode number assigned yet.
0309      * Hashing their inode number is delayed until later.
0310      */
0311     if (ci->ci_inode->i_ino)
0312         fscrypt_hash_inode_number(ci, mk);
0313     return 0;
0314 }
0315 
0316 static int fscrypt_setup_v2_file_key(struct fscrypt_info *ci,
0317                      struct fscrypt_master_key *mk,
0318                      bool need_dirhash_key)
0319 {
0320     int err;
0321 
0322     if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
0323         /*
0324          * DIRECT_KEY: instead of deriving per-file encryption keys, the
0325          * per-file nonce will be included in all the IVs.  But unlike
0326          * v1 policies, for v2 policies in this case we don't encrypt
0327          * with the master key directly but rather derive a per-mode
0328          * encryption key.  This ensures that the master key is
0329          * consistently used only for HKDF, avoiding key reuse issues.
0330          */
0331         err = setup_per_mode_enc_key(ci, mk, mk->mk_direct_keys,
0332                          HKDF_CONTEXT_DIRECT_KEY, false);
0333     } else if (ci->ci_policy.v2.flags &
0334            FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
0335         /*
0336          * IV_INO_LBLK_64: encryption keys are derived from (master_key,
0337          * mode_num, filesystem_uuid), and inode number is included in
0338          * the IVs.  This format is optimized for use with inline
0339          * encryption hardware compliant with the UFS standard.
0340          */
0341         err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_64_keys,
0342                          HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
0343                          true);
0344     } else if (ci->ci_policy.v2.flags &
0345            FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
0346         err = fscrypt_setup_iv_ino_lblk_32_key(ci, mk);
0347     } else {
0348         u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
0349 
0350         err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
0351                       HKDF_CONTEXT_PER_FILE_ENC_KEY,
0352                       ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
0353                       derived_key, ci->ci_mode->keysize);
0354         if (err)
0355             return err;
0356 
0357         err = fscrypt_set_per_file_enc_key(ci, derived_key);
0358         memzero_explicit(derived_key, ci->ci_mode->keysize);
0359     }
0360     if (err)
0361         return err;
0362 
0363     /* Derive a secret dirhash key for directories that need it. */
0364     if (need_dirhash_key) {
0365         err = fscrypt_derive_dirhash_key(ci, mk);
0366         if (err)
0367             return err;
0368     }
0369 
0370     return 0;
0371 }
0372 
0373 /*
0374  * Check whether the size of the given master key (@mk) is appropriate for the
0375  * encryption settings which a particular file will use (@ci).
0376  *
0377  * If the file uses a v1 encryption policy, then the master key must be at least
0378  * as long as the derived key, as this is a requirement of the v1 KDF.
0379  *
0380  * Otherwise, the KDF can accept any size key, so we enforce a slightly looser
0381  * requirement: we require that the size of the master key be at least the
0382  * maximum security strength of any algorithm whose key will be derived from it
0383  * (but in practice we only need to consider @ci->ci_mode, since any other
0384  * possible subkeys such as DIRHASH and INODE_HASH will never increase the
0385  * required key size over @ci->ci_mode).  This allows AES-256-XTS keys to be
0386  * derived from a 256-bit master key, which is cryptographically sufficient,
0387  * rather than requiring a 512-bit master key which is unnecessarily long.  (We
0388  * still allow 512-bit master keys if the user chooses to use them, though.)
0389  */
0390 static bool fscrypt_valid_master_key_size(const struct fscrypt_master_key *mk,
0391                       const struct fscrypt_info *ci)
0392 {
0393     unsigned int min_keysize;
0394 
0395     if (ci->ci_policy.version == FSCRYPT_POLICY_V1)
0396         min_keysize = ci->ci_mode->keysize;
0397     else
0398         min_keysize = ci->ci_mode->security_strength;
0399 
0400     if (mk->mk_secret.size < min_keysize) {
0401         fscrypt_warn(NULL,
0402                  "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
0403                  master_key_spec_type(&mk->mk_spec),
0404                  master_key_spec_len(&mk->mk_spec),
0405                  (u8 *)&mk->mk_spec.u,
0406                  mk->mk_secret.size, min_keysize);
0407         return false;
0408     }
0409     return true;
0410 }
0411 
0412 /*
0413  * Find the master key, then set up the inode's actual encryption key.
0414  *
0415  * If the master key is found in the filesystem-level keyring, then the
0416  * corresponding 'struct key' is returned in *master_key_ret with its semaphore
0417  * read-locked.  This is needed to ensure that only one task links the
0418  * fscrypt_info into ->mk_decrypted_inodes (as multiple tasks may race to create
0419  * an fscrypt_info for the same inode), and to synchronize the master key being
0420  * removed with a new inode starting to use it.
0421  */
0422 static int setup_file_encryption_key(struct fscrypt_info *ci,
0423                      bool need_dirhash_key,
0424                      struct key **master_key_ret)
0425 {
0426     struct key *key;
0427     struct fscrypt_master_key *mk = NULL;
0428     struct fscrypt_key_specifier mk_spec;
0429     int err;
0430 
0431     err = fscrypt_select_encryption_impl(ci);
0432     if (err)
0433         return err;
0434 
0435     err = fscrypt_policy_to_key_spec(&ci->ci_policy, &mk_spec);
0436     if (err)
0437         return err;
0438 
0439     key = fscrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
0440     if (IS_ERR(key)) {
0441         if (key != ERR_PTR(-ENOKEY) ||
0442             ci->ci_policy.version != FSCRYPT_POLICY_V1)
0443             return PTR_ERR(key);
0444 
0445         /*
0446          * As a legacy fallback for v1 policies, search for the key in
0447          * the current task's subscribed keyrings too.  Don't move this
0448          * to before the search of ->s_master_keys, since users
0449          * shouldn't be able to override filesystem-level keys.
0450          */
0451         return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
0452     }
0453 
0454     mk = key->payload.data[0];
0455     down_read(&key->sem);
0456 
0457     /* Has the secret been removed (via FS_IOC_REMOVE_ENCRYPTION_KEY)? */
0458     if (!is_master_key_secret_present(&mk->mk_secret)) {
0459         err = -ENOKEY;
0460         goto out_release_key;
0461     }
0462 
0463     if (!fscrypt_valid_master_key_size(mk, ci)) {
0464         err = -ENOKEY;
0465         goto out_release_key;
0466     }
0467 
0468     switch (ci->ci_policy.version) {
0469     case FSCRYPT_POLICY_V1:
0470         err = fscrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
0471         break;
0472     case FSCRYPT_POLICY_V2:
0473         err = fscrypt_setup_v2_file_key(ci, mk, need_dirhash_key);
0474         break;
0475     default:
0476         WARN_ON(1);
0477         err = -EINVAL;
0478         break;
0479     }
0480     if (err)
0481         goto out_release_key;
0482 
0483     *master_key_ret = key;
0484     return 0;
0485 
0486 out_release_key:
0487     up_read(&key->sem);
0488     key_put(key);
0489     return err;
0490 }
0491 
0492 static void put_crypt_info(struct fscrypt_info *ci)
0493 {
0494     struct key *key;
0495 
0496     if (!ci)
0497         return;
0498 
0499     if (ci->ci_direct_key)
0500         fscrypt_put_direct_key(ci->ci_direct_key);
0501     else if (ci->ci_owns_key)
0502         fscrypt_destroy_prepared_key(&ci->ci_enc_key);
0503 
0504     key = ci->ci_master_key;
0505     if (key) {
0506         struct fscrypt_master_key *mk = key->payload.data[0];
0507 
0508         /*
0509          * Remove this inode from the list of inodes that were unlocked
0510          * with the master key.
0511          *
0512          * In addition, if we're removing the last inode from a key that
0513          * already had its secret removed, invalidate the key so that it
0514          * gets removed from ->s_master_keys.
0515          */
0516         spin_lock(&mk->mk_decrypted_inodes_lock);
0517         list_del(&ci->ci_master_key_link);
0518         spin_unlock(&mk->mk_decrypted_inodes_lock);
0519         if (refcount_dec_and_test(&mk->mk_refcount))
0520             key_invalidate(key);
0521         key_put(key);
0522     }
0523     memzero_explicit(ci, sizeof(*ci));
0524     kmem_cache_free(fscrypt_info_cachep, ci);
0525 }
0526 
0527 static int
0528 fscrypt_setup_encryption_info(struct inode *inode,
0529                   const union fscrypt_policy *policy,
0530                   const u8 nonce[FSCRYPT_FILE_NONCE_SIZE],
0531                   bool need_dirhash_key)
0532 {
0533     struct fscrypt_info *crypt_info;
0534     struct fscrypt_mode *mode;
0535     struct key *master_key = NULL;
0536     int res;
0537 
0538     res = fscrypt_initialize(inode->i_sb->s_cop->flags);
0539     if (res)
0540         return res;
0541 
0542     crypt_info = kmem_cache_zalloc(fscrypt_info_cachep, GFP_KERNEL);
0543     if (!crypt_info)
0544         return -ENOMEM;
0545 
0546     crypt_info->ci_inode = inode;
0547     crypt_info->ci_policy = *policy;
0548     memcpy(crypt_info->ci_nonce, nonce, FSCRYPT_FILE_NONCE_SIZE);
0549 
0550     mode = select_encryption_mode(&crypt_info->ci_policy, inode);
0551     if (IS_ERR(mode)) {
0552         res = PTR_ERR(mode);
0553         goto out;
0554     }
0555     WARN_ON(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
0556     crypt_info->ci_mode = mode;
0557 
0558     res = setup_file_encryption_key(crypt_info, need_dirhash_key,
0559                     &master_key);
0560     if (res)
0561         goto out;
0562 
0563     /*
0564      * For existing inodes, multiple tasks may race to set ->i_crypt_info.
0565      * So use cmpxchg_release().  This pairs with the smp_load_acquire() in
0566      * fscrypt_get_info().  I.e., here we publish ->i_crypt_info with a
0567      * RELEASE barrier so that other tasks can ACQUIRE it.
0568      */
0569     if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
0570         /*
0571          * We won the race and set ->i_crypt_info to our crypt_info.
0572          * Now link it into the master key's inode list.
0573          */
0574         if (master_key) {
0575             struct fscrypt_master_key *mk =
0576                 master_key->payload.data[0];
0577 
0578             refcount_inc(&mk->mk_refcount);
0579             crypt_info->ci_master_key = key_get(master_key);
0580             spin_lock(&mk->mk_decrypted_inodes_lock);
0581             list_add(&crypt_info->ci_master_key_link,
0582                  &mk->mk_decrypted_inodes);
0583             spin_unlock(&mk->mk_decrypted_inodes_lock);
0584         }
0585         crypt_info = NULL;
0586     }
0587     res = 0;
0588 out:
0589     if (master_key) {
0590         up_read(&master_key->sem);
0591         key_put(master_key);
0592     }
0593     put_crypt_info(crypt_info);
0594     return res;
0595 }
0596 
0597 /**
0598  * fscrypt_get_encryption_info() - set up an inode's encryption key
0599  * @inode: the inode to set up the key for.  Must be encrypted.
0600  * @allow_unsupported: if %true, treat an unsupported encryption policy (or
0601  *             unrecognized encryption context) the same way as the key
0602  *             being unavailable, instead of returning an error.  Use
0603  *             %false unless the operation being performed is needed in
0604  *             order for files (or directories) to be deleted.
0605  *
0606  * Set up ->i_crypt_info, if it hasn't already been done.
0607  *
0608  * Note: unless ->i_crypt_info is already set, this isn't %GFP_NOFS-safe.  So
0609  * generally this shouldn't be called from within a filesystem transaction.
0610  *
0611  * Return: 0 if ->i_crypt_info was set or was already set, *or* if the
0612  *     encryption key is unavailable.  (Use fscrypt_has_encryption_key() to
0613  *     distinguish these cases.)  Also can return another -errno code.
0614  */
0615 int fscrypt_get_encryption_info(struct inode *inode, bool allow_unsupported)
0616 {
0617     int res;
0618     union fscrypt_context ctx;
0619     union fscrypt_policy policy;
0620 
0621     if (fscrypt_has_encryption_key(inode))
0622         return 0;
0623 
0624     res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
0625     if (res < 0) {
0626         if (res == -ERANGE && allow_unsupported)
0627             return 0;
0628         fscrypt_warn(inode, "Error %d getting encryption context", res);
0629         return res;
0630     }
0631 
0632     res = fscrypt_policy_from_context(&policy, &ctx, res);
0633     if (res) {
0634         if (allow_unsupported)
0635             return 0;
0636         fscrypt_warn(inode,
0637                  "Unrecognized or corrupt encryption context");
0638         return res;
0639     }
0640 
0641     if (!fscrypt_supported_policy(&policy, inode)) {
0642         if (allow_unsupported)
0643             return 0;
0644         return -EINVAL;
0645     }
0646 
0647     res = fscrypt_setup_encryption_info(inode, &policy,
0648                         fscrypt_context_nonce(&ctx),
0649                         IS_CASEFOLDED(inode) &&
0650                         S_ISDIR(inode->i_mode));
0651 
0652     if (res == -ENOPKG && allow_unsupported) /* Algorithm unavailable? */
0653         res = 0;
0654     if (res == -ENOKEY)
0655         res = 0;
0656     return res;
0657 }
0658 
0659 /**
0660  * fscrypt_prepare_new_inode() - prepare to create a new inode in a directory
0661  * @dir: a possibly-encrypted directory
0662  * @inode: the new inode.  ->i_mode must be set already.
0663  *     ->i_ino doesn't need to be set yet.
0664  * @encrypt_ret: (output) set to %true if the new inode will be encrypted
0665  *
0666  * If the directory is encrypted, set up its ->i_crypt_info in preparation for
0667  * encrypting the name of the new file.  Also, if the new inode will be
0668  * encrypted, set up its ->i_crypt_info and set *encrypt_ret=true.
0669  *
0670  * This isn't %GFP_NOFS-safe, and therefore it should be called before starting
0671  * any filesystem transaction to create the inode.  For this reason, ->i_ino
0672  * isn't required to be set yet, as the filesystem may not have set it yet.
0673  *
0674  * This doesn't persist the new inode's encryption context.  That still needs to
0675  * be done later by calling fscrypt_set_context().
0676  *
0677  * Return: 0 on success, -ENOKEY if the encryption key is missing, or another
0678  *     -errno code
0679  */
0680 int fscrypt_prepare_new_inode(struct inode *dir, struct inode *inode,
0681                   bool *encrypt_ret)
0682 {
0683     const union fscrypt_policy *policy;
0684     u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
0685 
0686     policy = fscrypt_policy_to_inherit(dir);
0687     if (policy == NULL)
0688         return 0;
0689     if (IS_ERR(policy))
0690         return PTR_ERR(policy);
0691 
0692     if (WARN_ON_ONCE(inode->i_mode == 0))
0693         return -EINVAL;
0694 
0695     /*
0696      * Only regular files, directories, and symlinks are encrypted.
0697      * Special files like device nodes and named pipes aren't.
0698      */
0699     if (!S_ISREG(inode->i_mode) &&
0700         !S_ISDIR(inode->i_mode) &&
0701         !S_ISLNK(inode->i_mode))
0702         return 0;
0703 
0704     *encrypt_ret = true;
0705 
0706     get_random_bytes(nonce, FSCRYPT_FILE_NONCE_SIZE);
0707     return fscrypt_setup_encryption_info(inode, policy, nonce,
0708                          IS_CASEFOLDED(dir) &&
0709                          S_ISDIR(inode->i_mode));
0710 }
0711 EXPORT_SYMBOL_GPL(fscrypt_prepare_new_inode);
0712 
0713 /**
0714  * fscrypt_put_encryption_info() - free most of an inode's fscrypt data
0715  * @inode: an inode being evicted
0716  *
0717  * Free the inode's fscrypt_info.  Filesystems must call this when the inode is
0718  * being evicted.  An RCU grace period need not have elapsed yet.
0719  */
0720 void fscrypt_put_encryption_info(struct inode *inode)
0721 {
0722     put_crypt_info(inode->i_crypt_info);
0723     inode->i_crypt_info = NULL;
0724 }
0725 EXPORT_SYMBOL(fscrypt_put_encryption_info);
0726 
0727 /**
0728  * fscrypt_free_inode() - free an inode's fscrypt data requiring RCU delay
0729  * @inode: an inode being freed
0730  *
0731  * Free the inode's cached decrypted symlink target, if any.  Filesystems must
0732  * call this after an RCU grace period, just before they free the inode.
0733  */
0734 void fscrypt_free_inode(struct inode *inode)
0735 {
0736     if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
0737         kfree(inode->i_link);
0738         inode->i_link = NULL;
0739     }
0740 }
0741 EXPORT_SYMBOL(fscrypt_free_inode);
0742 
0743 /**
0744  * fscrypt_drop_inode() - check whether the inode's master key has been removed
0745  * @inode: an inode being considered for eviction
0746  *
0747  * Filesystems supporting fscrypt must call this from their ->drop_inode()
0748  * method so that encrypted inodes are evicted as soon as they're no longer in
0749  * use and their master key has been removed.
0750  *
0751  * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
0752  */
0753 int fscrypt_drop_inode(struct inode *inode)
0754 {
0755     const struct fscrypt_info *ci = fscrypt_get_info(inode);
0756     const struct fscrypt_master_key *mk;
0757 
0758     /*
0759      * If ci is NULL, then the inode doesn't have an encryption key set up
0760      * so it's irrelevant.  If ci_master_key is NULL, then the master key
0761      * was provided via the legacy mechanism of the process-subscribed
0762      * keyrings, so we don't know whether it's been removed or not.
0763      */
0764     if (!ci || !ci->ci_master_key)
0765         return 0;
0766     mk = ci->ci_master_key->payload.data[0];
0767 
0768     /*
0769      * With proper, non-racy use of FS_IOC_REMOVE_ENCRYPTION_KEY, all inodes
0770      * protected by the key were cleaned by sync_filesystem().  But if
0771      * userspace is still using the files, inodes can be dirtied between
0772      * then and now.  We mustn't lose any writes, so skip dirty inodes here.
0773      */
0774     if (inode->i_state & I_DIRTY_ALL)
0775         return 0;
0776 
0777     /*
0778      * Note: since we aren't holding the key semaphore, the result here can
0779      * immediately become outdated.  But there's no correctness problem with
0780      * unnecessarily evicting.  Nor is there a correctness problem with not
0781      * evicting while iput() is racing with the key being removed, since
0782      * then the thread removing the key will either evict the inode itself
0783      * or will correctly detect that it wasn't evicted due to the race.
0784      */
0785     return !is_master_key_secret_present(&mk->mk_secret);
0786 }
0787 EXPORT_SYMBOL_GPL(fscrypt_drop_inode);