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