xref: /linux/fs/crypto/hooks.c (revision 283564a43383d6f26a55546fe9ae345b5fa95e66)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * fs/crypto/hooks.c
4  *
5  * Encryption hooks for higher-level filesystem operations.
6  */
7 
8 #include <linux/export.h>
9 
10 #include "fscrypt_private.h"
11 
12 /**
13  * fscrypt_file_open() - prepare to open a possibly-encrypted regular file
14  * @inode: the inode being opened
15  * @filp: the struct file being set up
16  *
17  * Currently, an encrypted regular file can only be opened if its encryption key
18  * is available; access to the raw encrypted contents is not supported.
19  * Therefore, we first set up the inode's encryption key (if not already done)
20  * and return an error if it's unavailable.
21  *
22  * We also verify that if the parent directory (from the path via which the file
23  * is being opened) is encrypted, then the inode being opened uses the same
24  * encryption policy.  This is needed as part of the enforcement that all files
25  * in an encrypted directory tree use the same encryption policy, as a
26  * protection against certain types of offline attacks.  Note that this check is
27  * needed even when opening an *unencrypted* file, since it's forbidden to have
28  * an unencrypted file in an encrypted directory.
29  *
30  * Return: 0 on success, -ENOKEY if the key is missing, or another -errno code
31  */
fscrypt_file_open(struct inode * inode,struct file * filp)32 int fscrypt_file_open(struct inode *inode, struct file *filp)
33 {
34 	int err;
35 	struct dentry *dentry, *dentry_parent;
36 	struct inode *inode_parent;
37 
38 	err = fscrypt_require_key(inode);
39 	if (err)
40 		return err;
41 
42 	dentry = file_dentry(filp);
43 
44 	/*
45 	 * Getting a reference to the parent dentry is needed for the actual
46 	 * encryption policy comparison, but it's expensive on multi-core
47 	 * systems.  Since this function runs on unencrypted files too, start
48 	 * with a lightweight RCU-mode check for the parent directory being
49 	 * unencrypted (in which case it's fine for the child to be either
50 	 * unencrypted, or encrypted with any policy).  Only continue on to the
51 	 * full policy check if the parent directory is actually encrypted.
52 	 */
53 	rcu_read_lock();
54 	dentry_parent = READ_ONCE(dentry->d_parent);
55 	inode_parent = d_inode_rcu(dentry_parent);
56 	if (inode_parent != NULL && !IS_ENCRYPTED(inode_parent)) {
57 		rcu_read_unlock();
58 		return 0;
59 	}
60 	rcu_read_unlock();
61 
62 	dentry_parent = dget_parent(dentry);
63 	if (!fscrypt_has_permitted_context(d_inode(dentry_parent), inode)) {
64 		fscrypt_warn(inode,
65 			     "Inconsistent encryption context (parent directory: %lu)",
66 			     d_inode(dentry_parent)->i_ino);
67 		err = -EPERM;
68 	}
69 	dput(dentry_parent);
70 	return err;
71 }
72 EXPORT_SYMBOL_GPL(fscrypt_file_open);
73 
__fscrypt_prepare_link(struct inode * inode,struct inode * dir,struct dentry * dentry)74 int __fscrypt_prepare_link(struct inode *inode, struct inode *dir,
75 			   struct dentry *dentry)
76 {
77 	if (fscrypt_is_nokey_name(dentry))
78 		return -ENOKEY;
79 	/*
80 	 * We don't need to separately check that the directory inode's key is
81 	 * available, as it's implied by the dentry not being a no-key name.
82 	 */
83 
84 	if (!fscrypt_has_permitted_context(dir, inode))
85 		return -EXDEV;
86 
87 	return 0;
88 }
89 EXPORT_SYMBOL_GPL(__fscrypt_prepare_link);
90 
__fscrypt_prepare_rename(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry,unsigned int flags)91 int __fscrypt_prepare_rename(struct inode *old_dir, struct dentry *old_dentry,
92 			     struct inode *new_dir, struct dentry *new_dentry,
93 			     unsigned int flags)
94 {
95 	if (fscrypt_is_nokey_name(old_dentry) ||
96 	    fscrypt_is_nokey_name(new_dentry))
97 		return -ENOKEY;
98 	/*
99 	 * We don't need to separately check that the directory inodes' keys are
100 	 * available, as it's implied by the dentries not being no-key names.
101 	 */
102 
103 	if (old_dir != new_dir) {
104 		if (IS_ENCRYPTED(new_dir) &&
105 		    !fscrypt_has_permitted_context(new_dir,
106 						   d_inode(old_dentry)))
107 			return -EXDEV;
108 
109 		if ((flags & RENAME_EXCHANGE) &&
110 		    IS_ENCRYPTED(old_dir) &&
111 		    !fscrypt_has_permitted_context(old_dir,
112 						   d_inode(new_dentry)))
113 			return -EXDEV;
114 	}
115 	return 0;
116 }
117 EXPORT_SYMBOL_GPL(__fscrypt_prepare_rename);
118 
__fscrypt_prepare_lookup(struct inode * dir,struct dentry * dentry,struct fscrypt_name * fname)119 int __fscrypt_prepare_lookup(struct inode *dir, struct dentry *dentry,
120 			     struct fscrypt_name *fname)
121 {
122 	int err = fscrypt_setup_filename(dir, &dentry->d_name, 1, fname);
123 
124 	if (err && err != -ENOENT)
125 		return err;
126 
127 	fscrypt_prepare_dentry(dentry, fname->is_nokey_name);
128 
129 	return err;
130 }
131 EXPORT_SYMBOL_GPL(__fscrypt_prepare_lookup);
132 
133 /**
134  * fscrypt_prepare_lookup_partial() - prepare lookup without filename setup
135  * @dir: the encrypted directory being searched
136  * @dentry: the dentry being looked up in @dir
137  *
138  * This function should be used by the ->lookup and ->atomic_open methods of
139  * filesystems that handle filename encryption and no-key name encoding
140  * themselves and thus can't use fscrypt_prepare_lookup().  Like
141  * fscrypt_prepare_lookup(), this will try to set up the directory's encryption
142  * key and will set DCACHE_NOKEY_NAME on the dentry if the key is unavailable.
143  * However, this function doesn't set up a struct fscrypt_name for the filename.
144  *
145  * Return: 0 on success; -errno on error.  Note that the encryption key being
146  *	   unavailable is not considered an error.  It is also not an error if
147  *	   the encryption policy is unsupported by this kernel; that is treated
148  *	   like the key being unavailable, so that files can still be deleted.
149  */
fscrypt_prepare_lookup_partial(struct inode * dir,struct dentry * dentry)150 int fscrypt_prepare_lookup_partial(struct inode *dir, struct dentry *dentry)
151 {
152 	int err = fscrypt_get_encryption_info(dir, true);
153 	bool is_nokey_name = (!err && !fscrypt_has_encryption_key(dir));
154 
155 	fscrypt_prepare_dentry(dentry, is_nokey_name);
156 
157 	return err;
158 }
159 EXPORT_SYMBOL_GPL(fscrypt_prepare_lookup_partial);
160 
__fscrypt_prepare_readdir(struct inode * dir)161 int __fscrypt_prepare_readdir(struct inode *dir)
162 {
163 	return fscrypt_get_encryption_info(dir, true);
164 }
165 EXPORT_SYMBOL_GPL(__fscrypt_prepare_readdir);
166 
__fscrypt_prepare_setattr(struct dentry * dentry,struct iattr * attr)167 int __fscrypt_prepare_setattr(struct dentry *dentry, struct iattr *attr)
168 {
169 	if (attr->ia_valid & ATTR_SIZE)
170 		return fscrypt_require_key(d_inode(dentry));
171 	return 0;
172 }
173 EXPORT_SYMBOL_GPL(__fscrypt_prepare_setattr);
174 
175 /**
176  * fscrypt_prepare_setflags() - prepare to change flags with FS_IOC_SETFLAGS
177  * @inode: the inode on which flags are being changed
178  * @oldflags: the old flags
179  * @flags: the new flags
180  *
181  * The caller should be holding i_rwsem for write.
182  *
183  * Return: 0 on success; -errno if the flags change isn't allowed or if
184  *	   another error occurs.
185  */
fscrypt_prepare_setflags(struct inode * inode,unsigned int oldflags,unsigned int flags)186 int fscrypt_prepare_setflags(struct inode *inode,
187 			     unsigned int oldflags, unsigned int flags)
188 {
189 	struct fscrypt_inode_info *ci;
190 	struct fscrypt_master_key *mk;
191 	int err;
192 
193 	/*
194 	 * When the CASEFOLD flag is set on an encrypted directory, we must
195 	 * derive the secret key needed for the dirhash.  This is only possible
196 	 * if the directory uses a v2 encryption policy.
197 	 */
198 	if (IS_ENCRYPTED(inode) && (flags & ~oldflags & FS_CASEFOLD_FL)) {
199 		err = fscrypt_require_key(inode);
200 		if (err)
201 			return err;
202 		ci = inode->i_crypt_info;
203 		if (ci->ci_policy.version != FSCRYPT_POLICY_V2)
204 			return -EINVAL;
205 		mk = ci->ci_master_key;
206 		down_read(&mk->mk_sem);
207 		if (mk->mk_present)
208 			err = fscrypt_derive_dirhash_key(ci, mk);
209 		else
210 			err = -ENOKEY;
211 		up_read(&mk->mk_sem);
212 		return err;
213 	}
214 	return 0;
215 }
216 
217 /**
218  * fscrypt_prepare_symlink() - prepare to create a possibly-encrypted symlink
219  * @dir: directory in which the symlink is being created
220  * @target: plaintext symlink target
221  * @len: length of @target excluding null terminator
222  * @max_len: space the filesystem has available to store the symlink target
223  * @disk_link: (out) the on-disk symlink target being prepared
224  *
225  * This function computes the size the symlink target will require on-disk,
226  * stores it in @disk_link->len, and validates it against @max_len.  An
227  * encrypted symlink may be longer than the original.
228  *
229  * Additionally, @disk_link->name is set to @target if the symlink will be
230  * unencrypted, but left NULL if the symlink will be encrypted.  For encrypted
231  * symlinks, the filesystem must call fscrypt_encrypt_symlink() to create the
232  * on-disk target later.  (The reason for the two-step process is that some
233  * filesystems need to know the size of the symlink target before creating the
234  * inode, e.g. to determine whether it will be a "fast" or "slow" symlink.)
235  *
236  * Return: 0 on success, -ENAMETOOLONG if the symlink target is too long,
237  * -ENOKEY if the encryption key is missing, or another -errno code if a problem
238  * occurred while setting up the encryption key.
239  */
fscrypt_prepare_symlink(struct inode * dir,const char * target,unsigned int len,unsigned int max_len,struct fscrypt_str * disk_link)240 int fscrypt_prepare_symlink(struct inode *dir, const char *target,
241 			    unsigned int len, unsigned int max_len,
242 			    struct fscrypt_str *disk_link)
243 {
244 	const union fscrypt_policy *policy;
245 
246 	/*
247 	 * To calculate the size of the encrypted symlink target we need to know
248 	 * the amount of NUL padding, which is determined by the flags set in
249 	 * the encryption policy which will be inherited from the directory.
250 	 */
251 	policy = fscrypt_policy_to_inherit(dir);
252 	if (policy == NULL) {
253 		/* Not encrypted */
254 		disk_link->name = (unsigned char *)target;
255 		disk_link->len = len + 1;
256 		if (disk_link->len > max_len)
257 			return -ENAMETOOLONG;
258 		return 0;
259 	}
260 	if (IS_ERR(policy))
261 		return PTR_ERR(policy);
262 
263 	/*
264 	 * Calculate the size of the encrypted symlink and verify it won't
265 	 * exceed max_len.  Note that for historical reasons, encrypted symlink
266 	 * targets are prefixed with the ciphertext length, despite this
267 	 * actually being redundant with i_size.  This decreases by 2 bytes the
268 	 * longest symlink target we can accept.
269 	 *
270 	 * We could recover 1 byte by not counting a null terminator, but
271 	 * counting it (even though it is meaningless for ciphertext) is simpler
272 	 * for now since filesystems will assume it is there and subtract it.
273 	 */
274 	if (!__fscrypt_fname_encrypted_size(policy, len,
275 					    max_len - sizeof(struct fscrypt_symlink_data) - 1,
276 					    &disk_link->len))
277 		return -ENAMETOOLONG;
278 	disk_link->len += sizeof(struct fscrypt_symlink_data) + 1;
279 
280 	disk_link->name = NULL;
281 	return 0;
282 }
283 EXPORT_SYMBOL_GPL(fscrypt_prepare_symlink);
284 
__fscrypt_encrypt_symlink(struct inode * inode,const char * target,unsigned int len,struct fscrypt_str * disk_link)285 int __fscrypt_encrypt_symlink(struct inode *inode, const char *target,
286 			      unsigned int len, struct fscrypt_str *disk_link)
287 {
288 	int err;
289 	struct qstr iname = QSTR_INIT(target, len);
290 	struct fscrypt_symlink_data *sd;
291 	unsigned int ciphertext_len;
292 
293 	/*
294 	 * fscrypt_prepare_new_inode() should have already set up the new
295 	 * symlink inode's encryption key.  We don't wait until now to do it,
296 	 * since we may be in a filesystem transaction now.
297 	 */
298 	if (WARN_ON_ONCE(!fscrypt_has_encryption_key(inode)))
299 		return -ENOKEY;
300 
301 	if (disk_link->name) {
302 		/* filesystem-provided buffer */
303 		sd = (struct fscrypt_symlink_data *)disk_link->name;
304 	} else {
305 		sd = kmalloc(disk_link->len, GFP_NOFS);
306 		if (!sd)
307 			return -ENOMEM;
308 	}
309 	ciphertext_len = disk_link->len - sizeof(*sd) - 1;
310 	sd->len = cpu_to_le16(ciphertext_len);
311 
312 	err = fscrypt_fname_encrypt(inode, &iname, sd->encrypted_path,
313 				    ciphertext_len);
314 	if (err)
315 		goto err_free_sd;
316 
317 	/*
318 	 * Null-terminating the ciphertext doesn't make sense, but we still
319 	 * count the null terminator in the length, so we might as well
320 	 * initialize it just in case the filesystem writes it out.
321 	 */
322 	sd->encrypted_path[ciphertext_len] = '\0';
323 
324 	/* Cache the plaintext symlink target for later use by get_link() */
325 	err = -ENOMEM;
326 	inode->i_link = kmemdup(target, len + 1, GFP_NOFS);
327 	if (!inode->i_link)
328 		goto err_free_sd;
329 
330 	if (!disk_link->name)
331 		disk_link->name = (unsigned char *)sd;
332 	return 0;
333 
334 err_free_sd:
335 	if (!disk_link->name)
336 		kfree(sd);
337 	return err;
338 }
339 EXPORT_SYMBOL_GPL(__fscrypt_encrypt_symlink);
340 
341 /**
342  * fscrypt_get_symlink() - get the target of an encrypted symlink
343  * @inode: the symlink inode
344  * @caddr: the on-disk contents of the symlink
345  * @max_size: size of @caddr buffer
346  * @done: if successful, will be set up to free the returned target if needed
347  *
348  * If the symlink's encryption key is available, we decrypt its target.
349  * Otherwise, we encode its target for presentation.
350  *
351  * This may sleep, so the filesystem must have dropped out of RCU mode already.
352  *
353  * Return: the presentable symlink target or an ERR_PTR()
354  */
fscrypt_get_symlink(struct inode * inode,const void * caddr,unsigned int max_size,struct delayed_call * done)355 const char *fscrypt_get_symlink(struct inode *inode, const void *caddr,
356 				unsigned int max_size,
357 				struct delayed_call *done)
358 {
359 	const struct fscrypt_symlink_data *sd;
360 	struct fscrypt_str cstr, pstr;
361 	bool has_key;
362 	int err;
363 
364 	/* This is for encrypted symlinks only */
365 	if (WARN_ON_ONCE(!IS_ENCRYPTED(inode)))
366 		return ERR_PTR(-EINVAL);
367 
368 	/* If the decrypted target is already cached, just return it. */
369 	pstr.name = READ_ONCE(inode->i_link);
370 	if (pstr.name)
371 		return pstr.name;
372 
373 	/*
374 	 * Try to set up the symlink's encryption key, but we can continue
375 	 * regardless of whether the key is available or not.
376 	 */
377 	err = fscrypt_get_encryption_info(inode, false);
378 	if (err)
379 		return ERR_PTR(err);
380 	has_key = fscrypt_has_encryption_key(inode);
381 
382 	/*
383 	 * For historical reasons, encrypted symlink targets are prefixed with
384 	 * the ciphertext length, even though this is redundant with i_size.
385 	 */
386 
387 	if (max_size < sizeof(*sd) + 1)
388 		return ERR_PTR(-EUCLEAN);
389 	sd = caddr;
390 	cstr.name = (unsigned char *)sd->encrypted_path;
391 	cstr.len = le16_to_cpu(sd->len);
392 
393 	if (cstr.len == 0)
394 		return ERR_PTR(-EUCLEAN);
395 
396 	if (cstr.len + sizeof(*sd) > max_size)
397 		return ERR_PTR(-EUCLEAN);
398 
399 	err = fscrypt_fname_alloc_buffer(cstr.len, &pstr);
400 	if (err)
401 		return ERR_PTR(err);
402 
403 	err = fscrypt_fname_disk_to_usr(inode, 0, 0, &cstr, &pstr);
404 	if (err)
405 		goto err_kfree;
406 
407 	err = -EUCLEAN;
408 	if (pstr.name[0] == '\0')
409 		goto err_kfree;
410 
411 	pstr.name[pstr.len] = '\0';
412 
413 	/*
414 	 * Cache decrypted symlink targets in i_link for later use.  Don't cache
415 	 * symlink targets encoded without the key, since those become outdated
416 	 * once the key is added.  This pairs with the READ_ONCE() above and in
417 	 * the VFS path lookup code.
418 	 */
419 	if (!has_key ||
420 	    cmpxchg_release(&inode->i_link, NULL, pstr.name) != NULL)
421 		set_delayed_call(done, kfree_link, pstr.name);
422 
423 	return pstr.name;
424 
425 err_kfree:
426 	kfree(pstr.name);
427 	return ERR_PTR(err);
428 }
429 EXPORT_SYMBOL_GPL(fscrypt_get_symlink);
430 
431 /**
432  * fscrypt_symlink_getattr() - set the correct st_size for encrypted symlinks
433  * @path: the path for the encrypted symlink being queried
434  * @stat: the struct being filled with the symlink's attributes
435  *
436  * Override st_size of encrypted symlinks to be the length of the decrypted
437  * symlink target (or the no-key encoded symlink target, if the key is
438  * unavailable) rather than the length of the encrypted symlink target.  This is
439  * necessary for st_size to match the symlink target that userspace actually
440  * sees.  POSIX requires this, and some userspace programs depend on it.
441  *
442  * This requires reading the symlink target from disk if needed, setting up the
443  * inode's encryption key if possible, and then decrypting or encoding the
444  * symlink target.  This makes lstat() more heavyweight than is normally the
445  * case.  However, decrypted symlink targets will be cached in ->i_link, so
446  * usually the symlink won't have to be read and decrypted again later if/when
447  * it is actually followed, readlink() is called, or lstat() is called again.
448  *
449  * Return: 0 on success, -errno on failure
450  */
fscrypt_symlink_getattr(const struct path * path,struct kstat * stat)451 int fscrypt_symlink_getattr(const struct path *path, struct kstat *stat)
452 {
453 	struct dentry *dentry = path->dentry;
454 	struct inode *inode = d_inode(dentry);
455 	const char *link;
456 	DEFINE_DELAYED_CALL(done);
457 
458 	/*
459 	 * To get the symlink target that userspace will see (whether it's the
460 	 * decrypted target or the no-key encoded target), we can just get it in
461 	 * the same way the VFS does during path resolution and readlink().
462 	 */
463 	link = READ_ONCE(inode->i_link);
464 	if (!link) {
465 		link = inode->i_op->get_link(dentry, inode, &done);
466 		if (IS_ERR(link))
467 			return PTR_ERR(link);
468 	}
469 	stat->size = strlen(link);
470 	do_delayed_call(&done);
471 	return 0;
472 }
473 EXPORT_SYMBOL_GPL(fscrypt_symlink_getattr);
474