Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * fs/crypto/hooks.c
0004  *
0005  * Encryption hooks for higher-level filesystem operations.
0006  */
0007 
0008 #include <linux/key.h>
0009 
0010 #include "fscrypt_private.h"
0011 
0012 /**
0013  * fscrypt_file_open() - prepare to open a possibly-encrypted regular file
0014  * @inode: the inode being opened
0015  * @filp: the struct file being set up
0016  *
0017  * Currently, an encrypted regular file can only be opened if its encryption key
0018  * is available; access to the raw encrypted contents is not supported.
0019  * Therefore, we first set up the inode's encryption key (if not already done)
0020  * and return an error if it's unavailable.
0021  *
0022  * We also verify that if the parent directory (from the path via which the file
0023  * is being opened) is encrypted, then the inode being opened uses the same
0024  * encryption policy.  This is needed as part of the enforcement that all files
0025  * in an encrypted directory tree use the same encryption policy, as a
0026  * protection against certain types of offline attacks.  Note that this check is
0027  * needed even when opening an *unencrypted* file, since it's forbidden to have
0028  * an unencrypted file in an encrypted directory.
0029  *
0030  * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
0031  */
0032 int fscrypt_file_open(struct inode *inode, struct file *filp)
0033 {
0034     int err;
0035     struct dentry *dir;
0036 
0037     err = fscrypt_require_key(inode);
0038     if (err)
0039         return err;
0040 
0041     dir = dget_parent(file_dentry(filp));
0042     if (IS_ENCRYPTED(d_inode(dir)) &&
0043         !fscrypt_has_permitted_context(d_inode(dir), inode)) {
0044         fscrypt_warn(inode,
0045                  "Inconsistent encryption context (parent directory: %lu)",
0046                  d_inode(dir)->i_ino);
0047         err = -EPERM;
0048     }
0049     dput(dir);
0050     return err;
0051 }
0052 EXPORT_SYMBOL_GPL(fscrypt_file_open);
0053 
0054 int __fscrypt_prepare_link(struct inode *inode, struct inode *dir,
0055                struct dentry *dentry)
0056 {
0057     if (fscrypt_is_nokey_name(dentry))
0058         return -ENOKEY;
0059     /*
0060      * We don't need to separately check that the directory inode's key is
0061      * available, as it's implied by the dentry not being a no-key name.
0062      */
0063 
0064     if (!fscrypt_has_permitted_context(dir, inode))
0065         return -EXDEV;
0066 
0067     return 0;
0068 }
0069 EXPORT_SYMBOL_GPL(__fscrypt_prepare_link);
0070 
0071 int __fscrypt_prepare_rename(struct inode *old_dir, struct dentry *old_dentry,
0072                  struct inode *new_dir, struct dentry *new_dentry,
0073                  unsigned int flags)
0074 {
0075     if (fscrypt_is_nokey_name(old_dentry) ||
0076         fscrypt_is_nokey_name(new_dentry))
0077         return -ENOKEY;
0078     /*
0079      * We don't need to separately check that the directory inodes' keys are
0080      * available, as it's implied by the dentries not being no-key names.
0081      */
0082 
0083     if (old_dir != new_dir) {
0084         if (IS_ENCRYPTED(new_dir) &&
0085             !fscrypt_has_permitted_context(new_dir,
0086                            d_inode(old_dentry)))
0087             return -EXDEV;
0088 
0089         if ((flags & RENAME_EXCHANGE) &&
0090             IS_ENCRYPTED(old_dir) &&
0091             !fscrypt_has_permitted_context(old_dir,
0092                            d_inode(new_dentry)))
0093             return -EXDEV;
0094     }
0095     return 0;
0096 }
0097 EXPORT_SYMBOL_GPL(__fscrypt_prepare_rename);
0098 
0099 int __fscrypt_prepare_lookup(struct inode *dir, struct dentry *dentry,
0100                  struct fscrypt_name *fname)
0101 {
0102     int err = fscrypt_setup_filename(dir, &dentry->d_name, 1, fname);
0103 
0104     if (err && err != -ENOENT)
0105         return err;
0106 
0107     if (fname->is_nokey_name) {
0108         spin_lock(&dentry->d_lock);
0109         dentry->d_flags |= DCACHE_NOKEY_NAME;
0110         spin_unlock(&dentry->d_lock);
0111     }
0112     return err;
0113 }
0114 EXPORT_SYMBOL_GPL(__fscrypt_prepare_lookup);
0115 
0116 int __fscrypt_prepare_readdir(struct inode *dir)
0117 {
0118     return fscrypt_get_encryption_info(dir, true);
0119 }
0120 EXPORT_SYMBOL_GPL(__fscrypt_prepare_readdir);
0121 
0122 int __fscrypt_prepare_setattr(struct dentry *dentry, struct iattr *attr)
0123 {
0124     if (attr->ia_valid & ATTR_SIZE)
0125         return fscrypt_require_key(d_inode(dentry));
0126     return 0;
0127 }
0128 EXPORT_SYMBOL_GPL(__fscrypt_prepare_setattr);
0129 
0130 /**
0131  * fscrypt_prepare_setflags() - prepare to change flags with FS_IOC_SETFLAGS
0132  * @inode: the inode on which flags are being changed
0133  * @oldflags: the old flags
0134  * @flags: the new flags
0135  *
0136  * The caller should be holding i_rwsem for write.
0137  *
0138  * Return: 0 on success; -errno if the flags change isn't allowed or if
0139  *     another error occurs.
0140  */
0141 int fscrypt_prepare_setflags(struct inode *inode,
0142                  unsigned int oldflags, unsigned int flags)
0143 {
0144     struct fscrypt_info *ci;
0145     struct key *key;
0146     struct fscrypt_master_key *mk;
0147     int err;
0148 
0149     /*
0150      * When the CASEFOLD flag is set on an encrypted directory, we must
0151      * derive the secret key needed for the dirhash.  This is only possible
0152      * if the directory uses a v2 encryption policy.
0153      */
0154     if (IS_ENCRYPTED(inode) && (flags & ~oldflags & FS_CASEFOLD_FL)) {
0155         err = fscrypt_require_key(inode);
0156         if (err)
0157             return err;
0158         ci = inode->i_crypt_info;
0159         if (ci->ci_policy.version != FSCRYPT_POLICY_V2)
0160             return -EINVAL;
0161         key = ci->ci_master_key;
0162         mk = key->payload.data[0];
0163         down_read(&key->sem);
0164         if (is_master_key_secret_present(&mk->mk_secret))
0165             err = fscrypt_derive_dirhash_key(ci, mk);
0166         else
0167             err = -ENOKEY;
0168         up_read(&key->sem);
0169         return err;
0170     }
0171     return 0;
0172 }
0173 
0174 /**
0175  * fscrypt_prepare_symlink() - prepare to create a possibly-encrypted symlink
0176  * @dir: directory in which the symlink is being created
0177  * @target: plaintext symlink target
0178  * @len: length of @target excluding null terminator
0179  * @max_len: space the filesystem has available to store the symlink target
0180  * @disk_link: (out) the on-disk symlink target being prepared
0181  *
0182  * This function computes the size the symlink target will require on-disk,
0183  * stores it in @disk_link->len, and validates it against @max_len.  An
0184  * encrypted symlink may be longer than the original.
0185  *
0186  * Additionally, @disk_link->name is set to @target if the symlink will be
0187  * unencrypted, but left NULL if the symlink will be encrypted.  For encrypted
0188  * symlinks, the filesystem must call fscrypt_encrypt_symlink() to create the
0189  * on-disk target later.  (The reason for the two-step process is that some
0190  * filesystems need to know the size of the symlink target before creating the
0191  * inode, e.g. to determine whether it will be a "fast" or "slow" symlink.)
0192  *
0193  * Return: 0 on success, -ENAMETOOLONG if the symlink target is too long,
0194  * -ENOKEY if the encryption key is missing, or another -errno code if a problem
0195  * occurred while setting up the encryption key.
0196  */
0197 int fscrypt_prepare_symlink(struct inode *dir, const char *target,
0198                 unsigned int len, unsigned int max_len,
0199                 struct fscrypt_str *disk_link)
0200 {
0201     const union fscrypt_policy *policy;
0202 
0203     /*
0204      * To calculate the size of the encrypted symlink target we need to know
0205      * the amount of NUL padding, which is determined by the flags set in
0206      * the encryption policy which will be inherited from the directory.
0207      */
0208     policy = fscrypt_policy_to_inherit(dir);
0209     if (policy == NULL) {
0210         /* Not encrypted */
0211         disk_link->name = (unsigned char *)target;
0212         disk_link->len = len + 1;
0213         if (disk_link->len > max_len)
0214             return -ENAMETOOLONG;
0215         return 0;
0216     }
0217     if (IS_ERR(policy))
0218         return PTR_ERR(policy);
0219 
0220     /*
0221      * Calculate the size of the encrypted symlink and verify it won't
0222      * exceed max_len.  Note that for historical reasons, encrypted symlink
0223      * targets are prefixed with the ciphertext length, despite this
0224      * actually being redundant with i_size.  This decreases by 2 bytes the
0225      * longest symlink target we can accept.
0226      *
0227      * We could recover 1 byte by not counting a null terminator, but
0228      * counting it (even though it is meaningless for ciphertext) is simpler
0229      * for now since filesystems will assume it is there and subtract it.
0230      */
0231     if (!__fscrypt_fname_encrypted_size(policy, len,
0232                         max_len - sizeof(struct fscrypt_symlink_data),
0233                         &disk_link->len))
0234         return -ENAMETOOLONG;
0235     disk_link->len += sizeof(struct fscrypt_symlink_data);
0236 
0237     disk_link->name = NULL;
0238     return 0;
0239 }
0240 EXPORT_SYMBOL_GPL(fscrypt_prepare_symlink);
0241 
0242 int __fscrypt_encrypt_symlink(struct inode *inode, const char *target,
0243                   unsigned int len, struct fscrypt_str *disk_link)
0244 {
0245     int err;
0246     struct qstr iname = QSTR_INIT(target, len);
0247     struct fscrypt_symlink_data *sd;
0248     unsigned int ciphertext_len;
0249 
0250     /*
0251      * fscrypt_prepare_new_inode() should have already set up the new
0252      * symlink inode's encryption key.  We don't wait until now to do it,
0253      * since we may be in a filesystem transaction now.
0254      */
0255     if (WARN_ON_ONCE(!fscrypt_has_encryption_key(inode)))
0256         return -ENOKEY;
0257 
0258     if (disk_link->name) {
0259         /* filesystem-provided buffer */
0260         sd = (struct fscrypt_symlink_data *)disk_link->name;
0261     } else {
0262         sd = kmalloc(disk_link->len, GFP_NOFS);
0263         if (!sd)
0264             return -ENOMEM;
0265     }
0266     ciphertext_len = disk_link->len - sizeof(*sd);
0267     sd->len = cpu_to_le16(ciphertext_len);
0268 
0269     err = fscrypt_fname_encrypt(inode, &iname, sd->encrypted_path,
0270                     ciphertext_len);
0271     if (err)
0272         goto err_free_sd;
0273 
0274     /*
0275      * Null-terminating the ciphertext doesn't make sense, but we still
0276      * count the null terminator in the length, so we might as well
0277      * initialize it just in case the filesystem writes it out.
0278      */
0279     sd->encrypted_path[ciphertext_len] = '\0';
0280 
0281     /* Cache the plaintext symlink target for later use by get_link() */
0282     err = -ENOMEM;
0283     inode->i_link = kmemdup(target, len + 1, GFP_NOFS);
0284     if (!inode->i_link)
0285         goto err_free_sd;
0286 
0287     if (!disk_link->name)
0288         disk_link->name = (unsigned char *)sd;
0289     return 0;
0290 
0291 err_free_sd:
0292     if (!disk_link->name)
0293         kfree(sd);
0294     return err;
0295 }
0296 EXPORT_SYMBOL_GPL(__fscrypt_encrypt_symlink);
0297 
0298 /**
0299  * fscrypt_get_symlink() - get the target of an encrypted symlink
0300  * @inode: the symlink inode
0301  * @caddr: the on-disk contents of the symlink
0302  * @max_size: size of @caddr buffer
0303  * @done: if successful, will be set up to free the returned target if needed
0304  *
0305  * If the symlink's encryption key is available, we decrypt its target.
0306  * Otherwise, we encode its target for presentation.
0307  *
0308  * This may sleep, so the filesystem must have dropped out of RCU mode already.
0309  *
0310  * Return: the presentable symlink target or an ERR_PTR()
0311  */
0312 const char *fscrypt_get_symlink(struct inode *inode, const void *caddr,
0313                 unsigned int max_size,
0314                 struct delayed_call *done)
0315 {
0316     const struct fscrypt_symlink_data *sd;
0317     struct fscrypt_str cstr, pstr;
0318     bool has_key;
0319     int err;
0320 
0321     /* This is for encrypted symlinks only */
0322     if (WARN_ON(!IS_ENCRYPTED(inode)))
0323         return ERR_PTR(-EINVAL);
0324 
0325     /* If the decrypted target is already cached, just return it. */
0326     pstr.name = READ_ONCE(inode->i_link);
0327     if (pstr.name)
0328         return pstr.name;
0329 
0330     /*
0331      * Try to set up the symlink's encryption key, but we can continue
0332      * regardless of whether the key is available or not.
0333      */
0334     err = fscrypt_get_encryption_info(inode, false);
0335     if (err)
0336         return ERR_PTR(err);
0337     has_key = fscrypt_has_encryption_key(inode);
0338 
0339     /*
0340      * For historical reasons, encrypted symlink targets are prefixed with
0341      * the ciphertext length, even though this is redundant with i_size.
0342      */
0343 
0344     if (max_size < sizeof(*sd))
0345         return ERR_PTR(-EUCLEAN);
0346     sd = caddr;
0347     cstr.name = (unsigned char *)sd->encrypted_path;
0348     cstr.len = le16_to_cpu(sd->len);
0349 
0350     if (cstr.len == 0)
0351         return ERR_PTR(-EUCLEAN);
0352 
0353     if (cstr.len + sizeof(*sd) - 1 > max_size)
0354         return ERR_PTR(-EUCLEAN);
0355 
0356     err = fscrypt_fname_alloc_buffer(cstr.len, &pstr);
0357     if (err)
0358         return ERR_PTR(err);
0359 
0360     err = fscrypt_fname_disk_to_usr(inode, 0, 0, &cstr, &pstr);
0361     if (err)
0362         goto err_kfree;
0363 
0364     err = -EUCLEAN;
0365     if (pstr.name[0] == '\0')
0366         goto err_kfree;
0367 
0368     pstr.name[pstr.len] = '\0';
0369 
0370     /*
0371      * Cache decrypted symlink targets in i_link for later use.  Don't cache
0372      * symlink targets encoded without the key, since those become outdated
0373      * once the key is added.  This pairs with the READ_ONCE() above and in
0374      * the VFS path lookup code.
0375      */
0376     if (!has_key ||
0377         cmpxchg_release(&inode->i_link, NULL, pstr.name) != NULL)
0378         set_delayed_call(done, kfree_link, pstr.name);
0379 
0380     return pstr.name;
0381 
0382 err_kfree:
0383     kfree(pstr.name);
0384     return ERR_PTR(err);
0385 }
0386 EXPORT_SYMBOL_GPL(fscrypt_get_symlink);
0387 
0388 /**
0389  * fscrypt_symlink_getattr() - set the correct st_size for encrypted symlinks
0390  * @path: the path for the encrypted symlink being queried
0391  * @stat: the struct being filled with the symlink's attributes
0392  *
0393  * Override st_size of encrypted symlinks to be the length of the decrypted
0394  * symlink target (or the no-key encoded symlink target, if the key is
0395  * unavailable) rather than the length of the encrypted symlink target.  This is
0396  * necessary for st_size to match the symlink target that userspace actually
0397  * sees.  POSIX requires this, and some userspace programs depend on it.
0398  *
0399  * This requires reading the symlink target from disk if needed, setting up the
0400  * inode's encryption key if possible, and then decrypting or encoding the
0401  * symlink target.  This makes lstat() more heavyweight than is normally the
0402  * case.  However, decrypted symlink targets will be cached in ->i_link, so
0403  * usually the symlink won't have to be read and decrypted again later if/when
0404  * it is actually followed, readlink() is called, or lstat() is called again.
0405  *
0406  * Return: 0 on success, -errno on failure
0407  */
0408 int fscrypt_symlink_getattr(const struct path *path, struct kstat *stat)
0409 {
0410     struct dentry *dentry = path->dentry;
0411     struct inode *inode = d_inode(dentry);
0412     const char *link;
0413     DEFINE_DELAYED_CALL(done);
0414 
0415     /*
0416      * To get the symlink target that userspace will see (whether it's the
0417      * decrypted target or the no-key encoded target), we can just get it in
0418      * the same way the VFS does during path resolution and readlink().
0419      */
0420     link = READ_ONCE(inode->i_link);
0421     if (!link) {
0422         link = inode->i_op->get_link(dentry, inode, &done);
0423         if (IS_ERR(link))
0424             return PTR_ERR(link);
0425     }
0426     stat->size = strlen(link);
0427     do_delayed_call(&done);
0428     return 0;
0429 }
0430 EXPORT_SYMBOL_GPL(fscrypt_symlink_getattr);