xref: /linux/security/landlock/fs.c (revision 7199989f3f3194d653b024ce8e79cea6b15e38b9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Landlock - Filesystem management and hooks
4  *
5  * Copyright © 2016-2020 Mickaël Salaün <mic@digikod.net>
6  * Copyright © 2018-2020 ANSSI
7  * Copyright © 2021-2025 Microsoft Corporation
8  * Copyright © 2022 Günther Noack <gnoack3000@gmail.com>
9  * Copyright © 2023-2024 Google LLC
10  */
11 
12 #include <asm/ioctls.h>
13 #include <kunit/test.h>
14 #include <linux/atomic.h>
15 #include <linux/bitops.h>
16 #include <linux/bits.h>
17 #include <linux/compiler_types.h>
18 #include <linux/dcache.h>
19 #include <linux/err.h>
20 #include <linux/falloc.h>
21 #include <linux/fs.h>
22 #include <linux/init.h>
23 #include <linux/kdev_t.h>
24 #include <linux/kernel.h>
25 #include <linux/limits.h>
26 #include <linux/list.h>
27 #include <linux/lsm_audit.h>
28 #include <linux/lsm_hooks.h>
29 #include <linux/mount.h>
30 #include <linux/namei.h>
31 #include <linux/net.h>
32 #include <linux/path.h>
33 #include <linux/pid.h>
34 #include <linux/rcupdate.h>
35 #include <linux/sched/signal.h>
36 #include <linux/spinlock.h>
37 #include <linux/stat.h>
38 #include <linux/types.h>
39 #include <linux/wait_bit.h>
40 #include <linux/workqueue.h>
41 #include <net/af_unix.h>
42 #include <uapi/linux/fiemap.h>
43 #include <uapi/linux/landlock.h>
44 
45 #include "access.h"
46 #include "common.h"
47 #include "cred.h"
48 #include "domain.h"
49 #include "fs.h"
50 #include "limits.h"
51 #include "log.h"
52 #include "object.h"
53 #include "ruleset.h"
54 #include "setup.h"
55 
56 #include <trace/events/landlock.h>
57 
58 /* Underlying object management */
59 
60 static void release_inode(struct landlock_object *const object)
61 	__releases(object->lock)
62 {
63 	struct inode *const inode = object->underobj;
64 	struct super_block *sb;
65 
66 	if (!inode) {
67 		spin_unlock(&object->lock);
68 		return;
69 	}
70 
71 	/*
72 	 * Protects against concurrent use by hook_sb_delete() of the reference
73 	 * to the underlying inode.
74 	 */
75 	object->underobj = NULL;
76 	/*
77 	 * Makes sure that if the filesystem is concurrently unmounted,
78 	 * hook_sb_delete() will wait for us to finish iput().
79 	 */
80 	sb = inode->i_sb;
81 	atomic_long_inc(&landlock_superblock(sb)->inode_refs);
82 	spin_unlock(&object->lock);
83 	/*
84 	 * Because object->underobj was not NULL, hook_sb_delete() and
85 	 * get_inode_object() guarantee that it is safe to reset
86 	 * landlock_inode(inode)->object while it is not NULL.  It is therefore
87 	 * not necessary to lock inode->i_lock.
88 	 */
89 	rcu_assign_pointer(landlock_inode(inode)->object, NULL);
90 	/*
91 	 * Now, new rules can safely be tied to @inode with get_inode_object().
92 	 */
93 
94 	iput(inode);
95 	if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
96 		wake_up_var(&landlock_superblock(sb)->inode_refs);
97 }
98 
99 static const struct landlock_object_underops landlock_fs_underops = {
100 	.release = release_inode
101 };
102 
103 /* IOCTL helpers */
104 
105 /**
106  * is_masked_device_ioctl - Determine whether an IOCTL command is always
107  * permitted with Landlock for device files.  These commands can not be
108  * restricted on device files by enforcing a Landlock policy.
109  *
110  * @cmd: The IOCTL command that is supposed to be run.
111  *
112  * By default, any IOCTL on a device file requires the
113  * LANDLOCK_ACCESS_FS_IOCTL_DEV right.  However, we blanket-permit some
114  * commands, if:
115  *
116  * 1. The command is implemented in fs/ioctl.c's do_vfs_ioctl(),
117  *    not in f_ops->unlocked_ioctl() or f_ops->compat_ioctl().
118  *
119  * 2. The command is harmless when invoked on devices.
120  *
121  * We also permit commands that do not make sense for devices, but where the
122  * do_vfs_ioctl() implementation returns a more conventional error code.
123  *
124  * Any new IOCTL commands that are implemented in fs/ioctl.c's do_vfs_ioctl()
125  * should be considered for inclusion here.
126  *
127  * Return: True if the IOCTL @cmd can not be restricted with Landlock for
128  * device files, false otherwise.
129  */
130 static __attribute_const__ bool is_masked_device_ioctl(const unsigned int cmd)
131 {
132 	switch (cmd) {
133 	/*
134 	 * FIOCLEX, FIONCLEX, FIONBIO and FIOASYNC manipulate the FD's
135 	 * close-on-exec and the file's buffered-IO and async flags.  These
136 	 * operations are also available through fcntl(2), and are
137 	 * unconditionally permitted in Landlock.
138 	 */
139 	case FIOCLEX:
140 	case FIONCLEX:
141 	case FIONBIO:
142 	case FIOASYNC:
143 	/*
144 	 * FIOQSIZE queries the size of a regular file, directory, or link.
145 	 *
146 	 * We still permit it, because it always returns -ENOTTY for
147 	 * other file types.
148 	 */
149 	case FIOQSIZE:
150 	/*
151 	 * FIFREEZE and FITHAW freeze and thaw the file system which the
152 	 * given file belongs to.  Requires CAP_SYS_ADMIN.
153 	 *
154 	 * These commands operate on the file system's superblock rather
155 	 * than on the file itself.  The same operations can also be
156 	 * done through any other file or directory on the same file
157 	 * system, so it is safe to permit these.
158 	 */
159 	case FIFREEZE:
160 	case FITHAW:
161 	/*
162 	 * FS_IOC_FIEMAP queries information about the allocation of
163 	 * blocks within a file.
164 	 *
165 	 * This IOCTL command only makes sense for regular files and is
166 	 * not implemented by devices. It is harmless to permit.
167 	 */
168 	case FS_IOC_FIEMAP:
169 	/*
170 	 * FIGETBSZ queries the file system's block size for a file or
171 	 * directory.
172 	 *
173 	 * This command operates on the file system's superblock rather
174 	 * than on the file itself.  The same operation can also be done
175 	 * through any other file or directory on the same file system,
176 	 * so it is safe to permit it.
177 	 */
178 	case FIGETBSZ:
179 	/*
180 	 * FICLONE, FICLONERANGE and FIDEDUPERANGE make files share
181 	 * their underlying storage ("reflink") between source and
182 	 * destination FDs, on file systems which support that.
183 	 *
184 	 * These IOCTL commands only apply to regular files
185 	 * and are harmless to permit for device files.
186 	 */
187 	case FICLONE:
188 	case FICLONERANGE:
189 	case FIDEDUPERANGE:
190 	/*
191 	 * FS_IOC_GETFSUUID and FS_IOC_GETFSSYSFSPATH both operate on
192 	 * the file system superblock, not on the specific file, so
193 	 * these operations are available through any other file on the
194 	 * same file system as well.
195 	 */
196 	case FS_IOC_GETFSUUID:
197 	case FS_IOC_GETFSSYSFSPATH:
198 		return true;
199 
200 	/*
201 	 * FIONREAD, FS_IOC_GETFLAGS, FS_IOC_SETFLAGS, FS_IOC_FSGETXATTR and
202 	 * FS_IOC_FSSETXATTR are forwarded to device implementations.
203 	 */
204 
205 	/*
206 	 * file_ioctl() commands (FIBMAP, FS_IOC_RESVSP, FS_IOC_RESVSP64,
207 	 * FS_IOC_UNRESVSP, FS_IOC_UNRESVSP64 and FS_IOC_ZERO_RANGE) are
208 	 * forwarded to device implementations, so not permitted.
209 	 */
210 
211 	/* Other commands are guarded by the access right. */
212 	default:
213 		return false;
214 	}
215 }
216 
217 /*
218  * is_masked_device_ioctl_compat - same as the helper above, but checking the
219  * "compat" IOCTL commands.
220  *
221  * The IOCTL commands with special handling in compat-mode should behave the
222  * same as their non-compat counterparts.
223  */
224 static __attribute_const__ bool
225 is_masked_device_ioctl_compat(const unsigned int cmd)
226 {
227 	switch (cmd) {
228 	/* FICLONE is permitted, same as in the non-compat variant. */
229 	case FICLONE:
230 		return true;
231 
232 #if defined(CONFIG_X86_64)
233 	/*
234 	 * FS_IOC_RESVSP_32, FS_IOC_RESVSP64_32, FS_IOC_UNRESVSP_32,
235 	 * FS_IOC_UNRESVSP64_32, FS_IOC_ZERO_RANGE_32: not blanket-permitted,
236 	 * for consistency with their non-compat variants.
237 	 */
238 	case FS_IOC_RESVSP_32:
239 	case FS_IOC_RESVSP64_32:
240 	case FS_IOC_UNRESVSP_32:
241 	case FS_IOC_UNRESVSP64_32:
242 	case FS_IOC_ZERO_RANGE_32:
243 #endif
244 
245 	/*
246 	 * FS_IOC32_GETFLAGS, FS_IOC32_SETFLAGS are forwarded to their device
247 	 * implementations.
248 	 */
249 	case FS_IOC32_GETFLAGS:
250 	case FS_IOC32_SETFLAGS:
251 		return false;
252 	default:
253 		return is_masked_device_ioctl(cmd);
254 	}
255 }
256 
257 /* Ruleset management */
258 
259 static struct landlock_object *get_inode_object(struct inode *const inode)
260 {
261 	struct landlock_object *object, *new_object;
262 	struct landlock_inode_security *inode_sec = landlock_inode(inode);
263 
264 	rcu_read_lock();
265 retry:
266 	object = rcu_dereference(inode_sec->object);
267 	if (object) {
268 		if (likely(refcount_inc_not_zero(&object->usage))) {
269 			rcu_read_unlock();
270 			return object;
271 		}
272 		/*
273 		 * We are racing with release_inode(), the object is going
274 		 * away.  Wait for release_inode(), then retry.
275 		 */
276 		spin_lock(&object->lock);
277 		spin_unlock(&object->lock);
278 		goto retry;
279 	}
280 	rcu_read_unlock();
281 
282 	/*
283 	 * If there is no object tied to @inode, then create a new one (without
284 	 * holding any locks).
285 	 */
286 	new_object = landlock_create_object(&landlock_fs_underops, inode);
287 	if (IS_ERR(new_object))
288 		return new_object;
289 
290 	/*
291 	 * Protects against concurrent calls to get_inode_object() or
292 	 * hook_sb_delete().
293 	 */
294 	spin_lock(&inode->i_lock);
295 	if (unlikely(rcu_access_pointer(inode_sec->object))) {
296 		/* Someone else just created the object, bail out and retry. */
297 		spin_unlock(&inode->i_lock);
298 		kfree(new_object);
299 
300 		rcu_read_lock();
301 		goto retry;
302 	}
303 
304 	/*
305 	 * @inode will be released by hook_sb_delete() on its superblock
306 	 * shutdown, or by release_inode() when no more ruleset references the
307 	 * related object.
308 	 */
309 	ihold(inode);
310 	rcu_assign_pointer(inode_sec->object, new_object);
311 	spin_unlock(&inode->i_lock);
312 	return new_object;
313 }
314 
315 /* All access rights that can be tied to files. */
316 /* clang-format off */
317 #define ACCESS_FILE ( \
318 	LANDLOCK_ACCESS_FS_EXECUTE | \
319 	LANDLOCK_ACCESS_FS_WRITE_FILE | \
320 	LANDLOCK_ACCESS_FS_READ_FILE | \
321 	LANDLOCK_ACCESS_FS_TRUNCATE | \
322 	LANDLOCK_ACCESS_FS_IOCTL_DEV | \
323 	LANDLOCK_ACCESS_FS_RESOLVE_UNIX)
324 /* clang-format on */
325 
326 /*
327  * @path: Should have been checked by get_path_from_fd().
328  */
329 int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
330 			    const struct path *const path,
331 			    access_mask_t access_rights, const u32 flags)
332 {
333 	int err;
334 	struct landlock_id id = {
335 		.type = LANDLOCK_KEY_INODE,
336 	};
337 
338 	/* Files only get access rights that make sense. */
339 	if (!d_is_dir(path->dentry) &&
340 	    !access_mask_subset(access_rights, ACCESS_FILE))
341 		return -EINVAL;
342 
343 	/* Transforms relative access rights to absolute ones. */
344 	access_rights |= LANDLOCK_MASK_ACCESS_FS &
345 			 ~(ruleset->handled_masks.fs |
346 			   _LANDLOCK_ACCESS_FS_INITIALLY_DENIED);
347 	id.key.object = get_inode_object(d_backing_inode(path->dentry));
348 	if (IS_ERR(id.key.object))
349 		return PTR_ERR(id.key.object);
350 	mutex_lock(&ruleset->lock);
351 	err = landlock_insert_rule(ruleset, id, access_rights, flags);
352 
353 	/*
354 	 * Emit after the rule insertion succeeds, so every event corresponds to
355 	 * a rule that is actually in the ruleset.  The ruleset lock is still
356 	 * held for BTF consistency (enforced by lockdep_assert_held in
357 	 * TP_fast_assign).
358 	 */
359 	if (!err && trace_landlock_add_rule_fs_enabled()) {
360 		char *buffer __free(__putname) = __getname();
361 		const char *pathname =
362 			buffer ? resolve_path_for_trace(path, buffer) :
363 				 "<no_mem>";
364 
365 		trace_landlock_add_rule_fs(ruleset, access_rights, path,
366 					   pathname);
367 	}
368 	mutex_unlock(&ruleset->lock);
369 
370 	/*
371 	 * No need to check for an error because landlock_insert_rule()
372 	 * increments the refcount for the new object if needed.
373 	 */
374 	landlock_put_object(id.key.object);
375 	return err;
376 }
377 
378 /* Access-control management */
379 
380 /**
381  * get_inode_id - Look up the Landlock object for a dentry
382  * @dentry: The dentry to look up.
383  * @id: Filled with the inode's Landlock object pointer on success.
384  *
385  * Extracts the Landlock object pointer from @dentry's inode security blob and
386  * stores it in @id for use as a rule-tree lookup key.
387  *
388  * When this returns false (negative dentry or no Landlock object), no rule can
389  * match this inode, so landlock_unmask_layers() need not be called.  Callers
390  * that gate landlock_unmask_layers() on this function must handle the NULL
391  * masks case independently, since the !masks-returns-true early-return in
392  * landlock_unmask_layers() will not be reached.  See the allowed_parent2
393  * initialization in is_access_to_paths_allowed().
394  *
395  * Return: True if a Landlock object exists for @dentry, false otherwise.
396  */
397 static bool get_inode_id(const struct dentry *const dentry,
398 			 struct landlock_id *id)
399 {
400 	/* Ignores nonexistent leafs. */
401 	if (d_is_negative(dentry))
402 		return false;
403 
404 	/*
405 	 * rcu_access_pointer() is sufficient: the pointer is used only as a
406 	 * numeric comparison key for rule lookup, not dereferenced.  The object
407 	 * cannot be freed while the domain exists because the domain's rule
408 	 * tree holds its own reference to it.
409 	 */
410 	id->key.object = rcu_access_pointer(
411 		landlock_inode(d_backing_inode(dentry))->object);
412 	return !!id->key.object;
413 }
414 
415 static bool unmask_layers_fs(const struct landlock_domain *const domain,
416 			     const struct landlock_id id,
417 			     const access_mask_t access_request,
418 			     struct layer_masks *masks,
419 			     const struct dentry *const dentry)
420 {
421 	const struct landlock_rule *rule = NULL;
422 	bool ret;
423 
424 	ret = landlock_unmask_layers(domain, id, masks, &rule);
425 	if (rule)
426 		trace_landlock_check_rule_fs(domain, rule, access_request,
427 					     dentry);
428 	return ret;
429 }
430 
431 /*
432  * Allows access to pseudo filesystems that will never be mountable (e.g.
433  * sockfs, pipefs), but can still be reachable through
434  * /proc/<pid>/fd/<file-descriptor>
435  */
436 static bool is_nouser_or_private(const struct dentry *dentry)
437 {
438 	return (dentry->d_sb->s_flags & SB_NOUSER) ||
439 	       (d_is_positive(dentry) &&
440 		unlikely(IS_PRIVATE(d_backing_inode(dentry))));
441 }
442 
443 static const struct access_masks any_fs = {
444 	.fs = ~0,
445 };
446 
447 /*
448  * Returns true iff the child file with the given src_child access rights under
449  * src_parent would result in having the same or fewer access rights if it were
450  * moved under new_parent.
451  */
452 static bool may_refer(const struct layer_masks *const src_parent,
453 		      const struct layer_masks *const src_child,
454 		      const struct layer_masks *const new_parent,
455 		      const bool child_is_dir)
456 {
457 	for (size_t i = 0; i < ARRAY_SIZE(new_parent->layers); i++) {
458 		access_mask_t child_access = src_parent->layers[i].access &
459 					     src_child->layers[i].access;
460 		access_mask_t parent_access = new_parent->layers[i].access;
461 
462 		if (!child_is_dir) {
463 			child_access &= ACCESS_FILE;
464 			parent_access &= ACCESS_FILE;
465 		}
466 
467 		if (!access_mask_subset(child_access, parent_access))
468 			return false;
469 	}
470 	return true;
471 }
472 
473 /*
474  * Check that a destination file hierarchy has more restrictions than a source
475  * file hierarchy.  This is only used for link and rename actions.
476  *
477  * Return: True if child1 may be moved from parent1 to parent2 without
478  * increasing its access rights (if child2 is set, an additional condition is
479  * that child2 may be used from parent2 to parent1 without increasing its access
480  * rights), false otherwise.
481  */
482 static bool no_more_access(const struct layer_masks *const parent1,
483 			   const struct layer_masks *const child1,
484 			   const bool child1_is_dir,
485 			   const struct layer_masks *const parent2,
486 			   const struct layer_masks *const child2,
487 			   const bool child2_is_dir)
488 {
489 	if (!may_refer(parent1, child1, parent2, child1_is_dir))
490 		return false;
491 
492 	if (!child2)
493 		return true;
494 
495 	return may_refer(parent2, child2, parent1, child2_is_dir);
496 }
497 
498 #define NMA_TRUE(...) KUNIT_EXPECT_TRUE(test, no_more_access(__VA_ARGS__))
499 #define NMA_FALSE(...) KUNIT_EXPECT_FALSE(test, no_more_access(__VA_ARGS__))
500 
501 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
502 
503 static void test_no_more_access(struct kunit *const test)
504 {
505 	const struct layer_masks rx0 = {
506 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE |
507 				    LANDLOCK_ACCESS_FS_READ_FILE,
508 	};
509 	const struct layer_masks mx0 = {
510 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE |
511 				    LANDLOCK_ACCESS_FS_MAKE_REG,
512 	};
513 	const struct layer_masks x0 = {
514 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE,
515 	};
516 	const struct layer_masks x1 = {
517 		.layers[1].access = LANDLOCK_ACCESS_FS_EXECUTE,
518 	};
519 	const struct layer_masks x01 = {
520 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE,
521 		.layers[1].access = LANDLOCK_ACCESS_FS_EXECUTE,
522 	};
523 	const struct layer_masks allows_all = {};
524 
525 	/* Checks without restriction. */
526 	NMA_TRUE(&x0, &allows_all, false, &allows_all, NULL, false);
527 	NMA_TRUE(&allows_all, &x0, false, &allows_all, NULL, false);
528 	NMA_FALSE(&x0, &x0, false, &allows_all, NULL, false);
529 
530 	/*
531 	 * Checks that we can only refer a file if no more access could be
532 	 * inherited.
533 	 */
534 	NMA_TRUE(&x0, &x0, false, &rx0, NULL, false);
535 	NMA_TRUE(&rx0, &rx0, false, &rx0, NULL, false);
536 	NMA_FALSE(&rx0, &rx0, false, &x0, NULL, false);
537 	NMA_FALSE(&rx0, &rx0, false, &x1, NULL, false);
538 
539 	/* Checks allowed referring with different nested domains. */
540 	NMA_TRUE(&x0, &x1, false, &x0, NULL, false);
541 	NMA_TRUE(&x1, &x0, false, &x0, NULL, false);
542 	NMA_TRUE(&x0, &x01, false, &x0, NULL, false);
543 	NMA_TRUE(&x0, &x01, false, &rx0, NULL, false);
544 	NMA_TRUE(&x01, &x0, false, &x0, NULL, false);
545 	NMA_TRUE(&x01, &x0, false, &rx0, NULL, false);
546 	NMA_FALSE(&x01, &x01, false, &x0, NULL, false);
547 
548 	/* Checks that file access rights are also enforced for a directory. */
549 	NMA_FALSE(&rx0, &rx0, true, &x0, NULL, false);
550 
551 	/* Checks that directory access rights don't impact file referring... */
552 	NMA_TRUE(&mx0, &mx0, false, &x0, NULL, false);
553 	/* ...but only directory referring. */
554 	NMA_FALSE(&mx0, &mx0, true, &x0, NULL, false);
555 
556 	/* Checks directory exchange. */
557 	NMA_TRUE(&mx0, &mx0, true, &mx0, &mx0, true);
558 	NMA_TRUE(&mx0, &mx0, true, &mx0, &x0, true);
559 	NMA_FALSE(&mx0, &mx0, true, &x0, &mx0, true);
560 	NMA_FALSE(&mx0, &mx0, true, &x0, &x0, true);
561 	NMA_FALSE(&mx0, &mx0, true, &x1, &x1, true);
562 
563 	/* Checks file exchange with directory access rights... */
564 	NMA_TRUE(&mx0, &mx0, false, &mx0, &mx0, false);
565 	NMA_TRUE(&mx0, &mx0, false, &mx0, &x0, false);
566 	NMA_TRUE(&mx0, &mx0, false, &x0, &mx0, false);
567 	NMA_TRUE(&mx0, &mx0, false, &x0, &x0, false);
568 	/* ...and with file access rights. */
569 	NMA_TRUE(&rx0, &rx0, false, &rx0, &rx0, false);
570 	NMA_TRUE(&rx0, &rx0, false, &rx0, &x0, false);
571 	NMA_FALSE(&rx0, &rx0, false, &x0, &rx0, false);
572 	NMA_FALSE(&rx0, &rx0, false, &x0, &x0, false);
573 	NMA_FALSE(&rx0, &rx0, false, &x1, &x1, false);
574 
575 	/*
576 	 * Allowing the following requests should not be a security risk
577 	 * because domain 0 denies execute access, and domain 1 is always
578 	 * nested with domain 0.  However, adding an exception for this case
579 	 * would mean to check all nested domains to make sure none can get
580 	 * more privileges (e.g. processes only sandboxed by domain 0).
581 	 * Moreover, this behavior (i.e. composition of N domains) could then
582 	 * be inconsistent compared to domain 1's ruleset alone (e.g. it might
583 	 * be denied to link/rename with domain 1's ruleset, whereas it would
584 	 * be allowed if nested on top of domain 0).  Another drawback would be
585 	 * to create a cover channel that could enable sandboxed processes to
586 	 * infer most of the filesystem restrictions from their domain.  To
587 	 * make it simple, efficient, safe, and more consistent, this case is
588 	 * always denied.
589 	 */
590 	NMA_FALSE(&x1, &x1, false, &x0, NULL, false);
591 	NMA_FALSE(&x1, &x1, false, &rx0, NULL, false);
592 	NMA_FALSE(&x1, &x1, true, &x0, NULL, false);
593 	NMA_FALSE(&x1, &x1, true, &rx0, NULL, false);
594 
595 	/* Checks the same case of exclusive domains with a file... */
596 	NMA_TRUE(&x1, &x1, false, &x01, NULL, false);
597 	NMA_FALSE(&x1, &x1, false, &x01, &x0, false);
598 	NMA_FALSE(&x1, &x1, false, &x01, &x01, false);
599 	NMA_FALSE(&x1, &x1, false, &x0, &x0, false);
600 	/* ...and with a directory. */
601 	NMA_FALSE(&x1, &x1, false, &x0, &x0, true);
602 	NMA_FALSE(&x1, &x1, true, &x0, &x0, false);
603 	NMA_FALSE(&x1, &x1, true, &x0, &x0, true);
604 }
605 
606 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
607 
608 #undef NMA_TRUE
609 #undef NMA_FALSE
610 
611 static bool is_layer_masks_allowed(const struct layer_masks *masks)
612 {
613 	for (size_t i = 0; i < ARRAY_SIZE(masks->layers); i++) {
614 		if (masks->layers[i].access)
615 			return false;
616 	}
617 	return true;
618 }
619 
620 /*
621  * Removes @masks accesses that are not requested.
622  *
623  * Returns true if the request is allowed, false otherwise.
624  */
625 static bool scope_to_request(const access_mask_t access_request,
626 			     struct layer_masks *masks)
627 {
628 	bool saw_unfulfilled_access = false;
629 
630 	if (WARN_ON_ONCE(!masks))
631 		return true;
632 
633 	for (size_t i = 0; i < ARRAY_SIZE(masks->layers); i++) {
634 		masks->layers[i].access &= access_request;
635 		if (masks->layers[i].access)
636 			saw_unfulfilled_access = true;
637 	}
638 	return !saw_unfulfilled_access;
639 }
640 
641 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
642 
643 static void test_scope_to_request_with_exec_none(struct kunit *const test)
644 {
645 	/* Allows everything. */
646 	struct layer_masks masks = {};
647 
648 	/* Checks and scopes with execute. */
649 	KUNIT_EXPECT_TRUE(test,
650 			  scope_to_request(LANDLOCK_ACCESS_FS_EXECUTE, &masks));
651 	KUNIT_EXPECT_EQ(test, 0, (access_mask_t)masks.layers[0].access);
652 }
653 
654 static void test_scope_to_request_with_exec_some(struct kunit *const test)
655 {
656 	/* Denies execute and write. */
657 	struct layer_masks masks = {
658 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE,
659 		.layers[1].access = LANDLOCK_ACCESS_FS_WRITE_FILE,
660 	};
661 
662 	/* Checks and scopes with execute. */
663 	KUNIT_EXPECT_FALSE(test, scope_to_request(LANDLOCK_ACCESS_FS_EXECUTE,
664 						  &masks));
665 	/*
666 	 * These casts to access_mask_t are needed because typeof(), used in
667 	 * KUNIT_EXPECT_EQ(), does not work on bitfields.
668 	 */
669 	KUNIT_EXPECT_EQ(test, LANDLOCK_ACCESS_FS_EXECUTE,
670 			(access_mask_t)masks.layers[0].access);
671 	KUNIT_EXPECT_EQ(test, 0, (access_mask_t)masks.layers[1].access);
672 }
673 
674 static void test_scope_to_request_without_access(struct kunit *const test)
675 {
676 	/* Denies execute and write. */
677 	struct layer_masks masks = {
678 		.layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE,
679 		.layers[1].access = LANDLOCK_ACCESS_FS_WRITE_FILE,
680 	};
681 
682 	/* Checks and scopes without access request. */
683 	KUNIT_EXPECT_TRUE(test, scope_to_request(0, &masks));
684 	KUNIT_EXPECT_EQ(test, 0, (access_mask_t)masks.layers[0].access);
685 	KUNIT_EXPECT_EQ(test, 0, (access_mask_t)masks.layers[1].access);
686 }
687 
688 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
689 
690 /*
691  * Returns true if there is at least one access right different than
692  * LANDLOCK_ACCESS_FS_REFER.
693  */
694 static bool is_eacces(const struct layer_masks *masks,
695 		      const access_mask_t access_request)
696 {
697 	if (!masks)
698 		return false;
699 
700 	for (size_t i = 0; i < ARRAY_SIZE(masks->layers); i++) {
701 		/* LANDLOCK_ACCESS_FS_REFER alone must return -EXDEV. */
702 		if (masks->layers[i].access & access_request &
703 		    ~LANDLOCK_ACCESS_FS_REFER)
704 			return true;
705 	}
706 	return false;
707 }
708 
709 #define IE_TRUE(...) KUNIT_EXPECT_TRUE(test, is_eacces(__VA_ARGS__))
710 #define IE_FALSE(...) KUNIT_EXPECT_FALSE(test, is_eacces(__VA_ARGS__))
711 
712 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
713 
714 static void test_is_eacces_with_none(struct kunit *const test)
715 {
716 	const struct layer_masks masks = {};
717 
718 	IE_FALSE(&masks, 0);
719 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_REFER);
720 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_EXECUTE);
721 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_WRITE_FILE);
722 }
723 
724 static void test_is_eacces_with_refer(struct kunit *const test)
725 {
726 	const struct layer_masks masks = {
727 		.layers[0].access = LANDLOCK_ACCESS_FS_REFER,
728 	};
729 
730 	IE_FALSE(&masks, 0);
731 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_REFER);
732 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_EXECUTE);
733 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_WRITE_FILE);
734 }
735 
736 static void test_is_eacces_with_write(struct kunit *const test)
737 {
738 	const struct layer_masks masks = {
739 		.layers[0].access = LANDLOCK_ACCESS_FS_WRITE_FILE,
740 	};
741 
742 	IE_FALSE(&masks, 0);
743 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_REFER);
744 	IE_FALSE(&masks, LANDLOCK_ACCESS_FS_EXECUTE);
745 
746 	IE_TRUE(&masks, LANDLOCK_ACCESS_FS_WRITE_FILE);
747 }
748 
749 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
750 
751 #undef IE_TRUE
752 #undef IE_FALSE
753 
754 /**
755  * is_access_to_paths_allowed - Check accesses for requests with a common path
756  *
757  * @domain: Domain to check against.
758  * @path: File hierarchy to walk through.  For refer checks, this would be
759  *     the common mountpoint.
760  * @access_request_parent1: Accesses to check, once @layer_masks_parent1 is
761  *     equal to @layer_masks_parent2 (if any).  This is tied to the unique
762  *     requested path for most actions, or the source in case of a refer action
763  *     (i.e. rename or link), or the source and destination in case of
764  *     RENAME_EXCHANGE.
765  * @layer_masks_parent1: Pointer to a matrix of layer masks per access
766  *     masks, identifying the layers that forbid a specific access.  Bits from
767  *     this matrix can be unset according to the @path walk.  An empty matrix
768  *     means that @domain allows all possible Landlock accesses (i.e. not only
769  *     those identified by @access_request_parent1).  This matrix can
770  *     initially refer to domain layer masks and, when the accesses for the
771  *     destination and source are the same, to requested layer masks.
772  * @log_request_parent1: Audit request to fill if the related access is denied.
773  * @dentry_child1: Dentry to the initial child of the parent1 path.  This
774  *     pointer must be NULL for non-refer actions (i.e. not link nor rename).
775  * @access_request_parent2: Similar to @access_request_parent1 but for a
776  *     request involving a source and a destination.  This refers to the
777  *     destination, except in case of RENAME_EXCHANGE where it also refers to
778  *     the source.  Must be set to 0 when using a simple path request.
779  * @layer_masks_parent2: Similar to @layer_masks_parent1 but for a refer
780  *     action.  This must be NULL otherwise.
781  * @log_request_parent2: Audit request to fill if the related access is denied.
782  * @dentry_child2: Dentry to the initial child of the parent2 path.  This
783  *     pointer is only set for RENAME_EXCHANGE actions and must be NULL
784  *     otherwise.
785  *
786  * This helper first checks that the destination has a superset of restrictions
787  * compared to the source (if any) for a common path.  Because of
788  * RENAME_EXCHANGE actions, source and destinations may be swapped.  It then
789  * checks that the collected accesses and the remaining ones are enough to
790  * allow the request.
791  *
792  * Return: True if the access request is granted, false otherwise.
793  */
794 static bool
795 is_access_to_paths_allowed(const struct landlock_domain *const domain,
796 			   const struct path *const path,
797 			   const access_mask_t access_request_parent1,
798 			   struct layer_masks *layer_masks_parent1,
799 			   struct landlock_request *const log_request_parent1,
800 			   struct dentry *const dentry_child1,
801 			   const access_mask_t access_request_parent2,
802 			   struct layer_masks *layer_masks_parent2,
803 			   struct landlock_request *const log_request_parent2,
804 			   struct dentry *const dentry_child2)
805 {
806 	bool allowed_parent1 = false, allowed_parent2 = false, is_dom_check,
807 	     child1_is_directory = true, child2_is_directory = true;
808 	struct path walker_path;
809 	struct landlock_id id = {
810 		.type = LANDLOCK_KEY_INODE,
811 	};
812 	access_mask_t access_masked_parent1, access_masked_parent2;
813 	struct layer_masks _layer_masks_child1, _layer_masks_child2;
814 	struct layer_masks *layer_masks_child1 = NULL,
815 			   *layer_masks_child2 = NULL;
816 
817 	if (!access_request_parent1 && !access_request_parent2)
818 		return true;
819 
820 	if (WARN_ON_ONCE(!path))
821 		return true;
822 
823 	if (is_nouser_or_private(path->dentry))
824 		return true;
825 
826 	if (WARN_ON_ONCE(!layer_masks_parent1))
827 		return false;
828 
829 	allowed_parent1 = is_layer_masks_allowed(layer_masks_parent1);
830 
831 	if (unlikely(layer_masks_parent2)) {
832 		if (WARN_ON_ONCE(!dentry_child1))
833 			return false;
834 
835 		allowed_parent2 = is_layer_masks_allowed(layer_masks_parent2);
836 
837 		/*
838 		 * For a double request, first check for potential privilege
839 		 * escalation by looking at domain handled accesses (which are
840 		 * a superset of the meaningful requested accesses).
841 		 */
842 		access_masked_parent1 = access_masked_parent2 =
843 			landlock_union_access_masks(domain).fs;
844 		is_dom_check = true;
845 	} else {
846 		if (WARN_ON_ONCE(dentry_child1 || dentry_child2))
847 			return false;
848 		/* For a simple request, only check for requested accesses. */
849 		access_masked_parent1 = access_request_parent1;
850 		access_masked_parent2 = access_request_parent2;
851 		/*
852 		 * Simple requests have no parent2 to check, so parent2 is
853 		 * trivially allowed.  This must be set explicitly because the
854 		 * get_inode_id() gate in the pathwalk loop may prevent
855 		 * landlock_unmask_layers() from being called (which would
856 		 * otherwise return true for NULL masks as a side effect).
857 		 */
858 		allowed_parent2 = true;
859 		is_dom_check = false;
860 	}
861 
862 	if (unlikely(dentry_child1)) {
863 		struct landlock_id id = {
864 			.type = LANDLOCK_KEY_INODE,
865 		};
866 		access_mask_t handled;
867 
868 		handled = landlock_init_layer_masks(domain,
869 						    LANDLOCK_MASK_ACCESS_FS,
870 						    &_layer_masks_child1,
871 						    LANDLOCK_KEY_INODE);
872 		if (handled && get_inode_id(dentry_child1, &id))
873 			unmask_layers_fs(domain, id, handled,
874 					 &_layer_masks_child1, dentry_child1);
875 		layer_masks_child1 = &_layer_masks_child1;
876 		child1_is_directory = d_is_dir(dentry_child1);
877 	}
878 	if (unlikely(dentry_child2)) {
879 		struct landlock_id id = {
880 			.type = LANDLOCK_KEY_INODE,
881 		};
882 		access_mask_t handled;
883 
884 		handled = landlock_init_layer_masks(domain,
885 						    LANDLOCK_MASK_ACCESS_FS,
886 						    &_layer_masks_child2,
887 						    LANDLOCK_KEY_INODE);
888 		if (handled && get_inode_id(dentry_child2, &id))
889 			unmask_layers_fs(domain, id, handled,
890 					 &_layer_masks_child2, dentry_child2);
891 		layer_masks_child2 = &_layer_masks_child2;
892 		child2_is_directory = d_is_dir(dentry_child2);
893 	}
894 
895 	walker_path = *path;
896 	path_get(&walker_path);
897 	/*
898 	 * We need to walk through all the hierarchy to not miss any relevant
899 	 * restriction.
900 	 */
901 	while (true) {
902 		/*
903 		 * If at least all accesses allowed on the destination are
904 		 * already allowed on the source, respectively if there is at
905 		 * least as much as restrictions on the destination than on the
906 		 * source, then we can safely refer files from the source to
907 		 * the destination without risking a privilege escalation.
908 		 * This also applies in the case of RENAME_EXCHANGE, which
909 		 * implies checks on both direction.  This is crucial for
910 		 * standalone multilayered security policies.  Furthermore,
911 		 * this helps avoid policy writers to shoot themselves in the
912 		 * foot.
913 		 */
914 		if (unlikely(is_dom_check &&
915 			     no_more_access(
916 				     layer_masks_parent1, layer_masks_child1,
917 				     child1_is_directory, layer_masks_parent2,
918 				     layer_masks_child2,
919 				     child2_is_directory))) {
920 			/*
921 			 * Now, downgrades the remaining checks from domain
922 			 * handled accesses to requested accesses.
923 			 */
924 			is_dom_check = false;
925 			access_masked_parent1 = access_request_parent1;
926 			access_masked_parent2 = access_request_parent2;
927 
928 			allowed_parent1 =
929 				allowed_parent1 ||
930 				scope_to_request(access_masked_parent1,
931 						 layer_masks_parent1);
932 			allowed_parent2 =
933 				allowed_parent2 ||
934 				scope_to_request(access_masked_parent2,
935 						 layer_masks_parent2);
936 
937 			/* Stops when all accesses are granted. */
938 			if (allowed_parent1 && allowed_parent2)
939 				break;
940 		}
941 
942 		if (get_inode_id(walker_path.dentry, &id)) {
943 			allowed_parent1 =
944 				allowed_parent1 ||
945 				unmask_layers_fs(domain, id,
946 						 access_masked_parent1,
947 						 layer_masks_parent1,
948 						 walker_path.dentry);
949 			allowed_parent2 =
950 				allowed_parent2 ||
951 				unmask_layers_fs(domain, id,
952 						 access_masked_parent2,
953 						 layer_masks_parent2,
954 						 walker_path.dentry);
955 		}
956 
957 		/* Stops when a rule from each layer grants access. */
958 		if (allowed_parent1 && allowed_parent2)
959 			break;
960 
961 jump_up:
962 		if (walker_path.dentry == walker_path.mnt->mnt_root) {
963 			if (follow_up(&walker_path)) {
964 				/* Ignores hidden mount points. */
965 				goto jump_up;
966 			} else {
967 				/*
968 				 * Stops at the real root.  Denies access
969 				 * because not all layers have granted access.
970 				 */
971 				break;
972 			}
973 		}
974 
975 		if (unlikely(IS_ROOT(walker_path.dentry))) {
976 			if (likely(walker_path.mnt->mnt_flags & MNT_INTERNAL)) {
977 				/*
978 				 * Stops and allows access when reaching disconnected root
979 				 * directories that are part of internal filesystems (e.g. nsfs,
980 				 * which is reachable through /proc/<pid>/ns/<namespace>).
981 				 */
982 				allowed_parent1 = true;
983 				allowed_parent2 = true;
984 				break;
985 			}
986 
987 			/*
988 			 * We reached a disconnected root directory from a bind mount.
989 			 * Let's continue the walk with the mount point we missed.
990 			 */
991 			dput(walker_path.dentry);
992 			walker_path.dentry = walker_path.mnt->mnt_root;
993 			dget(walker_path.dentry);
994 		} else {
995 			struct dentry *const parent_dentry =
996 				dget_parent(walker_path.dentry);
997 
998 			dput(walker_path.dentry);
999 			walker_path.dentry = parent_dentry;
1000 		}
1001 	}
1002 	path_put(&walker_path);
1003 
1004 	/*
1005 	 * Check CONFIG_SECURITY_LANDLOCK_LOG to enable elision of
1006 	 * log_request_parent* and associated caller's stack variables thanks to
1007 	 * dead code elimination.
1008 	 */
1009 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1010 	if (!allowed_parent1 && log_request_parent1) {
1011 		log_request_parent1->type = LANDLOCK_REQUEST_FS_ACCESS;
1012 		log_request_parent1->audit.type = LSM_AUDIT_DATA_PATH;
1013 		log_request_parent1->audit.u.path = *path;
1014 		log_request_parent1->access = access_masked_parent1;
1015 		log_request_parent1->layer_masks = layer_masks_parent1;
1016 	}
1017 
1018 	if (!allowed_parent2 && log_request_parent2) {
1019 		log_request_parent2->type = LANDLOCK_REQUEST_FS_ACCESS;
1020 		log_request_parent2->audit.type = LSM_AUDIT_DATA_PATH;
1021 		log_request_parent2->audit.u.path = *path;
1022 		log_request_parent2->access = access_masked_parent2;
1023 		log_request_parent2->layer_masks = layer_masks_parent2;
1024 	}
1025 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1026 
1027 	return allowed_parent1 && allowed_parent2;
1028 }
1029 
1030 static int current_check_access_path(const struct path *const path,
1031 				     access_mask_t access_request)
1032 {
1033 	const struct access_masks masks = {
1034 		.fs = access_request,
1035 	};
1036 	const struct landlock_cred_security *const subject =
1037 		landlock_get_applicable_subject(current_cred(), masks, NULL);
1038 	struct layer_masks layer_masks;
1039 	struct landlock_request request = {};
1040 
1041 	if (!subject)
1042 		return 0;
1043 
1044 	access_request = landlock_init_layer_masks(subject->domain,
1045 						   access_request, &layer_masks,
1046 						   LANDLOCK_KEY_INODE);
1047 	if (is_access_to_paths_allowed(subject->domain, path, access_request,
1048 				       &layer_masks, &request, NULL, 0, NULL,
1049 				       NULL, NULL))
1050 		return 0;
1051 
1052 	landlock_log_denial(subject, &request);
1053 	return -EACCES;
1054 }
1055 
1056 static __attribute_const__ access_mask_t get_mode_access(const umode_t mode,
1057 							 const dev_t dev)
1058 {
1059 	switch (mode & S_IFMT) {
1060 	case S_IFLNK:
1061 		return LANDLOCK_ACCESS_FS_MAKE_SYM;
1062 	case S_IFDIR:
1063 		return LANDLOCK_ACCESS_FS_MAKE_DIR;
1064 	case S_IFCHR:
1065 		/* Whiteout objects are guarded with MAKE_REG. */
1066 		if (dev == WHITEOUT_DEV)
1067 			return LANDLOCK_ACCESS_FS_MAKE_REG;
1068 		return LANDLOCK_ACCESS_FS_MAKE_CHAR;
1069 	case S_IFBLK:
1070 		return LANDLOCK_ACCESS_FS_MAKE_BLOCK;
1071 	case S_IFIFO:
1072 		return LANDLOCK_ACCESS_FS_MAKE_FIFO;
1073 	case S_IFSOCK:
1074 		return LANDLOCK_ACCESS_FS_MAKE_SOCK;
1075 	case S_IFREG:
1076 	case 0:
1077 		/* A zero mode translates to S_IFREG. */
1078 	default:
1079 		/* Treats weird files as regular files. */
1080 		return LANDLOCK_ACCESS_FS_MAKE_REG;
1081 	}
1082 }
1083 
1084 static access_mask_t get_dentry_access(const struct dentry *const dentry)
1085 {
1086 	const struct inode *const inode = d_backing_inode(dentry);
1087 
1088 	return get_mode_access(inode->i_mode, inode->i_rdev);
1089 }
1090 
1091 static access_mask_t maybe_remove(const struct dentry *const dentry)
1092 {
1093 	if (d_is_negative(dentry))
1094 		return 0;
1095 	return d_is_dir(dentry) ? LANDLOCK_ACCESS_FS_REMOVE_DIR :
1096 				  LANDLOCK_ACCESS_FS_REMOVE_FILE;
1097 }
1098 
1099 /**
1100  * collect_domain_accesses - Walk through a file path and collect accesses
1101  *
1102  * @domain: Domain to check against.
1103  * @mnt_root: Last directory to check.
1104  * @dir: Directory to start the walk from.
1105  * @layer_masks_dom: Where to store the collected accesses.
1106  *
1107  * This helper is useful to begin a path walk from the @dir directory to a
1108  * @mnt_root directory used as a mount point.  This mount point is the common
1109  * ancestor between the source and the destination of a renamed and linked
1110  * file.  While walking from @dir to @mnt_root, we record all the domain's
1111  * allowed accesses in @layer_masks_dom.
1112  *
1113  * Because of disconnected directories, this walk may not reach @mnt_dir.  In
1114  * this case, the walk will continue to @mnt_dir after this call.
1115  *
1116  * This is similar to is_access_to_paths_allowed() but much simpler because it
1117  * only handles walking on the same mount point and only checks one set of
1118  * accesses.
1119  *
1120  * Return: True if all the domain access rights are allowed for @dir, false if
1121  * the walk reached @mnt_root.
1122  */
1123 static bool collect_domain_accesses(const struct landlock_domain *const domain,
1124 				    const struct dentry *const mnt_root,
1125 				    struct dentry *dir,
1126 				    struct layer_masks *layer_masks_dom)
1127 {
1128 	bool ret = false;
1129 	access_mask_t access_masked_dom;
1130 
1131 	if (WARN_ON_ONCE(!domain || !mnt_root || !dir || !layer_masks_dom))
1132 		return true;
1133 	if (is_nouser_or_private(dir))
1134 		return true;
1135 
1136 	access_masked_dom =
1137 		landlock_init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
1138 					  layer_masks_dom, LANDLOCK_KEY_INODE);
1139 	if (!access_masked_dom)
1140 		return true;
1141 
1142 	dget(dir);
1143 	while (true) {
1144 		struct dentry *parent_dentry;
1145 		struct landlock_id id = {
1146 			.type = LANDLOCK_KEY_INODE,
1147 		};
1148 
1149 		/* Gets all layers allowing all domain accesses. */
1150 		if (get_inode_id(dir, &id) &&
1151 		    unmask_layers_fs(domain, id, access_masked_dom,
1152 				     layer_masks_dom, dir)) {
1153 			/*
1154 			 * Stops when all handled accesses are allowed by at
1155 			 * least one rule in each layer.
1156 			 */
1157 			ret = true;
1158 			break;
1159 		}
1160 
1161 		/*
1162 		 * Stops at the mount point or the filesystem root for a disconnected
1163 		 * directory.
1164 		 */
1165 		if (dir == mnt_root || unlikely(IS_ROOT(dir)))
1166 			break;
1167 
1168 		parent_dentry = dget_parent(dir);
1169 		dput(dir);
1170 		dir = parent_dentry;
1171 	}
1172 	dput(dir);
1173 	return ret;
1174 }
1175 
1176 /**
1177  * current_check_refer_path - Check if a rename or link action is allowed
1178  *
1179  * @old_dentry: File or directory requested to be moved or linked.
1180  * @new_dir: Destination parent directory.
1181  * @new_dentry: Destination file or directory.
1182  * @removable: Sets to true if it is a rename operation.
1183  * @exchange: Sets to true if it is a rename operation with RENAME_EXCHANGE.
1184  * @whiteout: Sets to true if it is a rename operation with RENAME_WHITEOUT.
1185  *
1186  * Because of its unprivileged constraints, Landlock relies on file hierarchies
1187  * (and not only inodes) to tie access rights to files.  Being able to link or
1188  * rename a file hierarchy brings some challenges.  Indeed, moving or linking a
1189  * file (i.e. creating a new reference to an inode) can have an impact on the
1190  * actions allowed for a set of files if it would change its parent directory
1191  * (i.e. reparenting).
1192  *
1193  * To avoid trivial access right bypasses, Landlock first checks if the file or
1194  * directory requested to be moved would gain new access rights inherited from
1195  * its new hierarchy.  Before returning any error, Landlock then checks that
1196  * the parent source hierarchy and the destination hierarchy would allow the
1197  * link or rename action.  If it is not the case, an error with EACCES is
1198  * returned to inform user space that there is no way to remove or create the
1199  * requested source file type.  If it should be allowed but the new inherited
1200  * access rights would be greater than the source access rights, then the
1201  * kernel returns an error with EXDEV.  Prioritizing EACCES over EXDEV enables
1202  * user space to abort the whole operation if there is no way to do it, or to
1203  * manually copy the source to the destination if this remains allowed, e.g.
1204  * because file creation is allowed on the destination directory but not direct
1205  * linking.
1206  *
1207  * To achieve this goal, the kernel needs to compare two file hierarchies: the
1208  * one identifying the source file or directory (including itself), and the
1209  * destination one.  This can be seen as a multilayer partial ordering problem.
1210  * The kernel walks through these paths and collects in a matrix the access
1211  * rights that are denied per layer.  These matrices are then compared to see
1212  * if the destination one has more (or the same) restrictions as the source
1213  * one.  If this is the case, the requested action will not return EXDEV, which
1214  * doesn't mean the action is allowed.  The parent hierarchy of the source
1215  * (i.e. parent directory), and the destination hierarchy must also be checked
1216  * to verify that they explicitly allow such action (i.e.  referencing,
1217  * creation and potentially removal rights).  The kernel implementation is then
1218  * required to rely on potentially four matrices of access rights: one for the
1219  * source file or directory (i.e. the child), a potentially other one for the
1220  * other source/destination (in case of RENAME_EXCHANGE), one for the source
1221  * parent hierarchy and a last one for the destination hierarchy.  These
1222  * ephemeral matrices take some space on the stack, which limits the number of
1223  * layers to a deemed reasonable number: 16.
1224  *
1225  * Return: 0 if access is allowed, -EXDEV if @old_dentry would inherit new
1226  * access rights from @new_dir, or -EACCES if file removal or creation is
1227  * denied.
1228  */
1229 static int current_check_refer_path(struct dentry *const old_dentry,
1230 				    const struct path *const new_dir,
1231 				    struct dentry *const new_dentry,
1232 				    const bool removable, const bool exchange,
1233 				    const bool whiteout)
1234 {
1235 	const struct landlock_cred_security *const subject =
1236 		landlock_get_applicable_subject(current_cred(), any_fs, NULL);
1237 	bool allow_parent1, allow_parent2;
1238 	access_mask_t access_request_parent1, access_request_parent2;
1239 	struct path mnt_dir;
1240 	struct dentry *old_parent;
1241 	struct layer_masks layer_masks_parent1 = {}, layer_masks_parent2 = {};
1242 	struct landlock_request request1 = {}, request2 = {};
1243 
1244 	if (!subject)
1245 		return 0;
1246 
1247 	if (unlikely(d_is_negative(old_dentry)))
1248 		return -ENOENT;
1249 	if (exchange) {
1250 		if (unlikely(d_is_negative(new_dentry)))
1251 			return -ENOENT;
1252 		access_request_parent1 = get_dentry_access(new_dentry);
1253 	} else {
1254 		access_request_parent1 = 0;
1255 	}
1256 	access_request_parent2 = get_dentry_access(old_dentry);
1257 	if (removable) {
1258 		access_request_parent1 |= maybe_remove(old_dentry);
1259 		access_request_parent2 |= maybe_remove(new_dentry);
1260 	}
1261 
1262 	/*
1263 	 * In case of renameat2(2) with RENAME_WHITEOUT, a whiteout object is
1264 	 * created in the source location, so we require an additional access
1265 	 * right there.
1266 	 */
1267 	if (whiteout)
1268 		access_request_parent1 |=
1269 			get_mode_access(S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
1270 
1271 	/* The mount points are the same for old and new paths, cf. EXDEV. */
1272 	if (old_dentry->d_parent == new_dir->dentry) {
1273 		/*
1274 		 * The LANDLOCK_ACCESS_FS_REFER access right is not required
1275 		 * for same-directory referer (i.e. no reparenting).
1276 		 */
1277 		access_request_parent1 = landlock_init_layer_masks(
1278 			subject->domain,
1279 			access_request_parent1 | access_request_parent2,
1280 			&layer_masks_parent1, LANDLOCK_KEY_INODE);
1281 		if (is_access_to_paths_allowed(subject->domain, new_dir,
1282 					       access_request_parent1,
1283 					       &layer_masks_parent1, &request1,
1284 					       NULL, 0, NULL, NULL, NULL))
1285 			return 0;
1286 
1287 		landlock_log_denial(subject, &request1);
1288 		return -EACCES;
1289 	}
1290 
1291 	access_request_parent1 |= LANDLOCK_ACCESS_FS_REFER;
1292 	access_request_parent2 |= LANDLOCK_ACCESS_FS_REFER;
1293 
1294 	/* Saves the common mount point. */
1295 	mnt_dir.mnt = new_dir->mnt;
1296 	mnt_dir.dentry = new_dir->mnt->mnt_root;
1297 
1298 	/*
1299 	 * old_dentry may be the root of the common mount point and
1300 	 * !IS_ROOT(old_dentry) at the same time (e.g. with open_tree() and
1301 	 * OPEN_TREE_CLONE).  We do not need to call dget(old_parent) because
1302 	 * we keep a reference to old_dentry.
1303 	 */
1304 	old_parent = (old_dentry == mnt_dir.dentry) ? old_dentry :
1305 						      old_dentry->d_parent;
1306 
1307 	/* new_dir->dentry is equal to new_dentry->d_parent */
1308 	allow_parent1 = collect_domain_accesses(subject->domain, mnt_dir.dentry,
1309 						old_parent,
1310 						&layer_masks_parent1);
1311 	allow_parent2 = collect_domain_accesses(subject->domain, mnt_dir.dentry,
1312 						new_dir->dentry,
1313 						&layer_masks_parent2);
1314 	if (allow_parent1 && allow_parent2)
1315 		return 0;
1316 
1317 	/*
1318 	 * To be able to compare source and destination domain access rights,
1319 	 * take into account the @old_dentry access rights aggregated with its
1320 	 * parent access rights.  This will be useful to compare with the
1321 	 * destination parent access rights.
1322 	 */
1323 	if (is_access_to_paths_allowed(
1324 		    subject->domain, &mnt_dir, access_request_parent1,
1325 		    &layer_masks_parent1, &request1, old_dentry,
1326 		    access_request_parent2, &layer_masks_parent2, &request2,
1327 		    exchange ? new_dentry : NULL))
1328 		return 0;
1329 
1330 	if (request1.access) {
1331 		request1.audit.u.path.dentry = old_parent;
1332 		landlock_log_denial(subject, &request1);
1333 	}
1334 	if (request2.access) {
1335 		request2.audit.u.path.dentry = new_dir->dentry;
1336 		landlock_log_denial(subject, &request2);
1337 	}
1338 
1339 	/*
1340 	 * This prioritizes EACCES over EXDEV for all actions, including
1341 	 * renames with RENAME_EXCHANGE.
1342 	 */
1343 	if (likely(is_eacces(&layer_masks_parent1, access_request_parent1) ||
1344 		   is_eacces(&layer_masks_parent2, access_request_parent2)))
1345 		return -EACCES;
1346 
1347 	/*
1348 	 * Gracefully forbids reparenting if the destination directory
1349 	 * hierarchy is not a superset of restrictions of the source directory
1350 	 * hierarchy, or if LANDLOCK_ACCESS_FS_REFER is not allowed by the
1351 	 * source or the destination.
1352 	 */
1353 	return -EXDEV;
1354 }
1355 
1356 /* Inode hooks */
1357 
1358 static void hook_inode_free_security_rcu(void *inode_security)
1359 {
1360 	struct landlock_inode_security *inode_sec;
1361 
1362 	/*
1363 	 * All inodes must already have been untied from their object by
1364 	 * release_inode() or hook_sb_delete().
1365 	 */
1366 	inode_sec = inode_security + landlock_blob_sizes.lbs_inode;
1367 	WARN_ON_ONCE(inode_sec->object);
1368 }
1369 
1370 /* Super-block hooks */
1371 
1372 /*
1373  * Release the inodes used in a security policy.
1374  *
1375  * Cf. fsnotify_unmount_inodes() and evict_inodes()
1376  */
1377 static void hook_sb_delete(struct super_block *const sb)
1378 {
1379 	struct inode *inode, *prev_inode = NULL;
1380 
1381 	if (!landlock_initialized)
1382 		return;
1383 
1384 	spin_lock(&sb->s_inode_list_lock);
1385 	list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
1386 		struct landlock_object *object;
1387 
1388 		/* Only handles referenced inodes. */
1389 		if (!icount_read_once(inode))
1390 			continue;
1391 
1392 		/*
1393 		 * Protects against concurrent modification of inode (e.g.
1394 		 * from get_inode_object()).
1395 		 */
1396 		spin_lock(&inode->i_lock);
1397 		/*
1398 		 * Checks I_FREEING and I_WILL_FREE  to protect against a race
1399 		 * condition when release_inode() just called iput(), which
1400 		 * could lead to a NULL dereference of inode->security or a
1401 		 * second call to iput() for the same Landlock object.  Also
1402 		 * checks I_NEW because such inode cannot be tied to an object.
1403 		 */
1404 		if (inode_state_read(inode) &
1405 		    (I_FREEING | I_WILL_FREE | I_NEW)) {
1406 			spin_unlock(&inode->i_lock);
1407 			continue;
1408 		}
1409 
1410 		rcu_read_lock();
1411 		object = rcu_dereference(landlock_inode(inode)->object);
1412 		if (!object) {
1413 			rcu_read_unlock();
1414 			spin_unlock(&inode->i_lock);
1415 			continue;
1416 		}
1417 		/* Keeps a reference to this inode until the next loop walk. */
1418 		__iget(inode);
1419 		spin_unlock(&inode->i_lock);
1420 
1421 		/*
1422 		 * If there is no concurrent release_inode() ongoing, then we
1423 		 * are in charge of calling iput() on this inode, otherwise we
1424 		 * will just wait for it to finish.
1425 		 */
1426 		spin_lock(&object->lock);
1427 		if (object->underobj == inode) {
1428 			object->underobj = NULL;
1429 			spin_unlock(&object->lock);
1430 			rcu_read_unlock();
1431 
1432 			/*
1433 			 * Because object->underobj was not NULL,
1434 			 * release_inode() and get_inode_object() guarantee
1435 			 * that it is safe to reset
1436 			 * landlock_inode(inode)->object while it is not NULL.
1437 			 * It is therefore not necessary to lock inode->i_lock.
1438 			 */
1439 			rcu_assign_pointer(landlock_inode(inode)->object, NULL);
1440 			/*
1441 			 * At this point, we own the ihold() reference that was
1442 			 * originally set up by get_inode_object() and the
1443 			 * __iget() reference that we just set in this loop
1444 			 * walk.  Therefore there are at least two references
1445 			 * on the inode.
1446 			 */
1447 			iput_not_last(inode);
1448 		} else {
1449 			spin_unlock(&object->lock);
1450 			rcu_read_unlock();
1451 		}
1452 
1453 		if (prev_inode) {
1454 			/*
1455 			 * At this point, we still own the __iget() reference
1456 			 * that we just set in this loop walk.  Therefore we
1457 			 * can drop the list lock and know that the inode won't
1458 			 * disappear from under us until the next loop walk.
1459 			 */
1460 			spin_unlock(&sb->s_inode_list_lock);
1461 			/*
1462 			 * We can now actually put the inode reference from the
1463 			 * previous loop walk, which is not needed anymore.
1464 			 */
1465 			iput(prev_inode);
1466 			cond_resched();
1467 			spin_lock(&sb->s_inode_list_lock);
1468 		}
1469 		prev_inode = inode;
1470 	}
1471 	spin_unlock(&sb->s_inode_list_lock);
1472 
1473 	/* Puts the inode reference from the last loop walk, if any. */
1474 	if (prev_inode)
1475 		iput(prev_inode);
1476 	/* Waits for pending iput() in release_inode(). */
1477 	wait_var_event(&landlock_superblock(sb)->inode_refs,
1478 		       !atomic_long_read(&landlock_superblock(sb)->inode_refs));
1479 }
1480 
1481 static void
1482 log_fs_change_topology_path(const struct landlock_cred_security *const subject,
1483 			    size_t handle_layer, const struct path *const path)
1484 {
1485 	landlock_log_denial(subject, &(struct landlock_request) {
1486 		.type = LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY,
1487 		.audit = {
1488 			.type = LSM_AUDIT_DATA_PATH,
1489 			.u.path = *path,
1490 		},
1491 		.layer_plus_one = handle_layer + 1,
1492 	});
1493 }
1494 
1495 static void log_fs_change_topology_dentry(
1496 	const struct landlock_cred_security *const subject, size_t handle_layer,
1497 	struct dentry *const dentry)
1498 {
1499 	landlock_log_denial(subject, &(struct landlock_request) {
1500 		.type = LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY,
1501 		.audit = {
1502 			.type = LSM_AUDIT_DATA_DENTRY,
1503 			.u.dentry = dentry,
1504 		},
1505 		.layer_plus_one = handle_layer + 1,
1506 	});
1507 }
1508 
1509 /*
1510  * Because a Landlock security policy is defined according to the filesystem
1511  * topology (i.e. the mount namespace), changing it may grant access to files
1512  * not previously allowed.
1513  *
1514  * To make it simple, deny any filesystem topology modification by landlocked
1515  * processes.  Non-landlocked processes may still change the namespace of a
1516  * landlocked process, but this kind of threat must be handled by a system-wide
1517  * access-control security policy.
1518  *
1519  * This could be lifted in the future if Landlock can safely handle mount
1520  * namespace updates requested by a landlocked process.  Indeed, we could
1521  * update the current domain (which is currently read-only) by taking into
1522  * account the accesses of the source and the destination of a new mount point.
1523  * However, it would also require to make all the child domains dynamically
1524  * inherit these new constraints.  Anyway, for backward compatibility reasons,
1525  * a dedicated user space option would be required (e.g. as a ruleset flag).
1526  */
1527 static int hook_sb_mount(const char *const dev_name,
1528 			 const struct path *const path, const char *const type,
1529 			 const unsigned long flags, void *const data)
1530 {
1531 	size_t handle_layer;
1532 	const struct landlock_cred_security *const subject =
1533 		landlock_get_applicable_subject(current_cred(), any_fs,
1534 						&handle_layer);
1535 
1536 	if (!subject)
1537 		return 0;
1538 
1539 	log_fs_change_topology_path(subject, handle_layer, path);
1540 	return -EPERM;
1541 }
1542 
1543 static int hook_move_mount(const struct path *const from_path,
1544 			   const struct path *const to_path)
1545 {
1546 	size_t handle_layer;
1547 	const struct landlock_cred_security *const subject =
1548 		landlock_get_applicable_subject(current_cred(), any_fs,
1549 						&handle_layer);
1550 
1551 	if (!subject)
1552 		return 0;
1553 
1554 	log_fs_change_topology_path(subject, handle_layer, to_path);
1555 	return -EPERM;
1556 }
1557 
1558 /*
1559  * Removing a mount point may reveal a previously hidden file hierarchy, which
1560  * may then grant access to files, which may have previously been forbidden.
1561  */
1562 static int hook_sb_umount(struct vfsmount *const mnt, const int flags)
1563 {
1564 	size_t handle_layer;
1565 	const struct landlock_cred_security *const subject =
1566 		landlock_get_applicable_subject(current_cred(), any_fs,
1567 						&handle_layer);
1568 
1569 	if (!subject)
1570 		return 0;
1571 
1572 	log_fs_change_topology_dentry(subject, handle_layer, mnt->mnt_root);
1573 	return -EPERM;
1574 }
1575 
1576 static int hook_sb_remount(struct super_block *const sb, void *const mnt_opts)
1577 {
1578 	size_t handle_layer;
1579 	const struct landlock_cred_security *const subject =
1580 		landlock_get_applicable_subject(current_cred(), any_fs,
1581 						&handle_layer);
1582 
1583 	if (!subject)
1584 		return 0;
1585 
1586 	log_fs_change_topology_dentry(subject, handle_layer, sb->s_root);
1587 	return -EPERM;
1588 }
1589 
1590 /*
1591  * pivot_root(2), like mount(2), changes the current mount namespace.  It must
1592  * then be forbidden for a landlocked process.
1593  *
1594  * However, chroot(2) may be allowed because it only changes the relative root
1595  * directory of the current process.  Moreover, it can be used to restrict the
1596  * view of the filesystem.
1597  */
1598 static int hook_sb_pivotroot(const struct path *const old_path,
1599 			     const struct path *const new_path)
1600 {
1601 	size_t handle_layer;
1602 	const struct landlock_cred_security *const subject =
1603 		landlock_get_applicable_subject(current_cred(), any_fs,
1604 						&handle_layer);
1605 
1606 	if (!subject)
1607 		return 0;
1608 
1609 	log_fs_change_topology_path(subject, handle_layer, new_path);
1610 	return -EPERM;
1611 }
1612 
1613 /* Path hooks */
1614 
1615 static int hook_path_link(struct dentry *const old_dentry,
1616 			  const struct path *const new_dir,
1617 			  struct dentry *const new_dentry)
1618 {
1619 	return current_check_refer_path(old_dentry, new_dir, new_dentry, false,
1620 					false, false);
1621 }
1622 
1623 static int hook_path_rename(const struct path *const old_dir,
1624 			    struct dentry *const old_dentry,
1625 			    const struct path *const new_dir,
1626 			    struct dentry *const new_dentry,
1627 			    const unsigned int flags)
1628 {
1629 	/* old_dir refers to old_dentry->d_parent and new_dir->mnt */
1630 	return current_check_refer_path(old_dentry, new_dir, new_dentry, true,
1631 					!!(flags & RENAME_EXCHANGE),
1632 					!!(flags & RENAME_WHITEOUT));
1633 }
1634 
1635 static int hook_path_mkdir(const struct path *const dir,
1636 			   struct dentry *const dentry, const umode_t mode)
1637 {
1638 	return current_check_access_path(dir, LANDLOCK_ACCESS_FS_MAKE_DIR);
1639 }
1640 
1641 static int hook_path_mknod(const struct path *const dir,
1642 			   struct dentry *const dentry, const umode_t mode,
1643 			   const unsigned int dev)
1644 {
1645 	return current_check_access_path(
1646 		dir, get_mode_access(mode, new_decode_dev(dev)));
1647 }
1648 
1649 static int hook_path_symlink(const struct path *const dir,
1650 			     struct dentry *const dentry,
1651 			     const char *const old_name)
1652 {
1653 	return current_check_access_path(dir, LANDLOCK_ACCESS_FS_MAKE_SYM);
1654 }
1655 
1656 static int hook_path_unlink(const struct path *const dir,
1657 			    struct dentry *const dentry)
1658 {
1659 	return current_check_access_path(dir, LANDLOCK_ACCESS_FS_REMOVE_FILE);
1660 }
1661 
1662 static int hook_path_rmdir(const struct path *const dir,
1663 			   struct dentry *const dentry)
1664 {
1665 	return current_check_access_path(dir, LANDLOCK_ACCESS_FS_REMOVE_DIR);
1666 }
1667 
1668 static int hook_path_truncate(const struct path *const path)
1669 {
1670 	return current_check_access_path(path, LANDLOCK_ACCESS_FS_TRUNCATE);
1671 }
1672 
1673 /**
1674  * unmask_scoped_access - Remove access right bits in @masks in all layers
1675  *                        where @client and @server have the same domain
1676  *
1677  * This does the same as domain_is_scoped(), but unmasks bits in @masks.
1678  * It can not return early as domain_is_scoped() does.
1679  *
1680  * A scoped access for a given access right bit is allowed iff, for all layer
1681  * depths where the access bit is set, the client and server domain are the
1682  * same.  This function clears the access rights @access in @masks at all layer
1683  * depths where the client and server domain are the same, so that, when they
1684  * are all cleared, the access is allowed.
1685  *
1686  * @client: Client domain
1687  * @server: Server domain
1688  * @masks: Layer access masks to unmask
1689  * @access: Access bits that control scoping
1690  */
1691 static void unmask_scoped_access(const struct landlock_domain *const client,
1692 				 const struct landlock_domain *const server,
1693 				 struct layer_masks *const masks,
1694 				 const access_mask_t access)
1695 {
1696 	int client_layer, server_layer;
1697 	const struct landlock_hierarchy *client_walker, *server_walker;
1698 
1699 	/* This should not happen. */
1700 	if (WARN_ON_ONCE(!client))
1701 		return;
1702 
1703 	/* Server has no Landlock domain; nothing to clear. */
1704 	if (!server)
1705 		return;
1706 
1707 	/*
1708 	 * client_layer must be able to represent all numbers from
1709 	 * LANDLOCK_MAX_NUM_LAYERS - 1 to -1 for the loop below to terminate.
1710 	 * (It must be large enough, and it must be signed.)
1711 	 */
1712 	BUILD_BUG_ON(!is_signed_type(typeof(client_layer)));
1713 	BUILD_BUG_ON(LANDLOCK_MAX_NUM_LAYERS - 1 >
1714 		     type_max(typeof(client_layer)));
1715 
1716 	client_layer = client->num_layers - 1;
1717 	client_walker = client->hierarchy;
1718 	server_layer = server->num_layers - 1;
1719 	server_walker = server->hierarchy;
1720 
1721 	/*
1722 	 * Clears the access bits at all layers where the client domain is the
1723 	 * same as the server domain.  We start the walk at min(client_layer,
1724 	 * server_layer).  The layer bits until there can not be cleared because
1725 	 * either the client or the server domain is missing.
1726 	 */
1727 	for (; client_layer > server_layer; client_layer--)
1728 		client_walker = client_walker->parent;
1729 
1730 	for (; server_layer > client_layer; server_layer--)
1731 		server_walker = server_walker->parent;
1732 
1733 	for (; client_layer >= 0; client_layer--) {
1734 		if (masks->layers[client_layer].access & access &&
1735 		    client_walker == server_walker)
1736 			masks->layers[client_layer].access &= ~access;
1737 
1738 		client_walker = client_walker->parent;
1739 		server_walker = server_walker->parent;
1740 	}
1741 }
1742 
1743 static int hook_unix_find(const struct path *const path, struct sock *other,
1744 			  int flags)
1745 {
1746 	const struct landlock_domain *dom_other;
1747 	const struct landlock_cred_security *subject;
1748 	struct layer_masks layer_masks;
1749 	struct landlock_request request = {};
1750 	static const struct access_masks fs_resolve_unix = {
1751 		.fs = LANDLOCK_ACCESS_FS_RESOLVE_UNIX,
1752 	};
1753 
1754 	/* Lookup for the purpose of saving coredumps is OK. */
1755 	if (unlikely(flags & SOCK_COREDUMP))
1756 		return 0;
1757 
1758 	subject = landlock_get_applicable_subject(current_cred(),
1759 						  fs_resolve_unix, NULL);
1760 
1761 	if (!subject)
1762 		return 0;
1763 
1764 	/*
1765 	 * Ignoring return value: that the domains apply was already checked in
1766 	 * landlock_get_applicable_subject() above.
1767 	 */
1768 	landlock_init_layer_masks(subject->domain, fs_resolve_unix.fs,
1769 				  &layer_masks, LANDLOCK_KEY_INODE);
1770 
1771 	/* Checks the layers in which we are connecting within the same domain. */
1772 	unix_state_lock(other);
1773 	if (unlikely(sock_flag(other, SOCK_DEAD) || !other->sk_socket ||
1774 		     !other->sk_socket->file)) {
1775 		unix_state_unlock(other);
1776 		/*
1777 		 * We rely on the caller to catch the (non-reversible) SOCK_DEAD
1778 		 * condition and retry the lookup.  If we returned an error
1779 		 * here, the lookup would not get retried.
1780 		 */
1781 		return 0;
1782 	}
1783 	dom_other = landlock_cred(other->sk_socket->file->f_cred)->domain;
1784 
1785 	/* Access to the same (or a lower) domain is always allowed. */
1786 	unmask_scoped_access(subject->domain, dom_other, &layer_masks,
1787 			     fs_resolve_unix.fs);
1788 	unix_state_unlock(other);
1789 
1790 	/* Checks the connections to allow-listed paths. */
1791 	if (is_access_to_paths_allowed(subject->domain, path,
1792 				       fs_resolve_unix.fs, &layer_masks,
1793 				       &request, NULL, 0, NULL, NULL, NULL))
1794 		return 0;
1795 
1796 	landlock_log_denial(subject, &request);
1797 	return -EACCES;
1798 }
1799 
1800 /* File hooks */
1801 
1802 /**
1803  * get_required_file_open_access - Get access needed to open a file
1804  *
1805  * @file: File being opened.
1806  *
1807  * Return: The access rights that are required for opening the given file,
1808  * depending on the file type and open mode.
1809  */
1810 static access_mask_t
1811 get_required_file_open_access(const struct file *const file)
1812 {
1813 	access_mask_t access = 0;
1814 
1815 	if (file->f_mode & FMODE_READ) {
1816 		/* A directory can only be opened in read mode. */
1817 		if (S_ISDIR(file_inode(file)->i_mode))
1818 			return LANDLOCK_ACCESS_FS_READ_DIR;
1819 		access = LANDLOCK_ACCESS_FS_READ_FILE;
1820 	}
1821 	if (file->f_mode & FMODE_WRITE)
1822 		access |= LANDLOCK_ACCESS_FS_WRITE_FILE;
1823 	/* __FMODE_EXEC is indeed part of f_flags, not f_mode. */
1824 	if (file->f_flags & __FMODE_EXEC)
1825 		access |= LANDLOCK_ACCESS_FS_EXECUTE;
1826 	return access;
1827 }
1828 
1829 static int hook_file_alloc_security(struct file *const file)
1830 {
1831 	/*
1832 	 * Grants all access rights, even if most of them are not checked later
1833 	 * on. It is more consistent.
1834 	 *
1835 	 * Notably, file descriptors for regular files can also be acquired
1836 	 * without going through the file_open hook, for example when using
1837 	 * memfd_create(2).
1838 	 */
1839 	landlock_file(file)->allowed_access = LANDLOCK_MASK_ACCESS_FS;
1840 	return 0;
1841 }
1842 
1843 static bool is_device(const struct file *const file)
1844 {
1845 	const struct inode *inode = file_inode(file);
1846 
1847 	return S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode);
1848 }
1849 
1850 static int hook_file_open(struct file *const file)
1851 {
1852 	struct layer_masks layer_masks = {};
1853 	access_mask_t open_access_request, full_access_request, allowed_access,
1854 		optional_access;
1855 	const struct landlock_cred_security *const subject =
1856 		landlock_get_applicable_subject(file->f_cred, any_fs, NULL);
1857 	struct landlock_request request = {};
1858 
1859 	if (!subject)
1860 		return 0;
1861 
1862 	/*
1863 	 * Because a file may be opened with O_PATH, get_required_file_open_access()
1864 	 * may return 0.  This case will be handled with a future Landlock
1865 	 * evolution.
1866 	 */
1867 	open_access_request = get_required_file_open_access(file);
1868 
1869 	/*
1870 	 * We look up more access than what we immediately need for open(), so
1871 	 * that we can later authorize operations on opened files.
1872 	 */
1873 	optional_access = LANDLOCK_ACCESS_FS_TRUNCATE;
1874 	if (is_device(file))
1875 		optional_access |= LANDLOCK_ACCESS_FS_IOCTL_DEV;
1876 
1877 	full_access_request = open_access_request | optional_access;
1878 
1879 	if (is_access_to_paths_allowed(
1880 		    subject->domain, &file->f_path,
1881 		    landlock_init_layer_masks(subject->domain,
1882 					      full_access_request, &layer_masks,
1883 					      LANDLOCK_KEY_INODE),
1884 		    &layer_masks, &request, NULL, 0, NULL, NULL, NULL)) {
1885 		allowed_access = full_access_request;
1886 	} else {
1887 		/*
1888 		 * Calculate the actual allowed access rights from layer_masks.
1889 		 * Remove the access rights from the full access request which
1890 		 * are still unfulfilled in any of the layers.
1891 		 */
1892 		allowed_access = full_access_request;
1893 		for (size_t i = 0; i < ARRAY_SIZE(layer_masks.layers); i++)
1894 			allowed_access &= ~layer_masks.layers[i].access;
1895 	}
1896 
1897 	/*
1898 	 * For operations on already opened files (i.e. ftruncate()), it is the
1899 	 * access rights at the time of open() which decide whether the
1900 	 * operation is permitted. Therefore, we record the relevant subset of
1901 	 * file access rights in the opened struct file.
1902 	 */
1903 	landlock_file(file)->allowed_access = allowed_access;
1904 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1905 	landlock_file(file)->deny_masks = landlock_get_deny_masks(
1906 		_LANDLOCK_ACCESS_FS_OPTIONAL, optional_access, &layer_masks);
1907 	landlock_file(file)->quiet_optional_accesses =
1908 		landlock_get_quiet_optional_accesses(
1909 			_LANDLOCK_ACCESS_FS_OPTIONAL,
1910 			landlock_file(file)->deny_masks, &layer_masks);
1911 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1912 
1913 	if (access_mask_subset(open_access_request, allowed_access))
1914 		return 0;
1915 
1916 	/* Sets access to reflect the actual request. */
1917 	request.access = open_access_request;
1918 	landlock_log_denial(subject, &request);
1919 	return -EACCES;
1920 }
1921 
1922 static int hook_file_truncate(struct file *const file)
1923 {
1924 	/*
1925 	 * Allows truncation if the truncate right was available at the time of
1926 	 * opening the file, to get a consistent access check as for read, write
1927 	 * and execute operations.
1928 	 *
1929 	 * Note: For checks done based on the file's Landlock allowed access, we
1930 	 * enforce them independently of whether the current thread is in a
1931 	 * Landlock domain, so that open files passed between independent
1932 	 * processes retain their behaviour.
1933 	 */
1934 	if (landlock_file(file)->allowed_access & LANDLOCK_ACCESS_FS_TRUNCATE)
1935 		return 0;
1936 
1937 	landlock_log_denial(landlock_cred(file->f_cred), &(struct landlock_request) {
1938 		.type = LANDLOCK_REQUEST_FS_ACCESS,
1939 		.audit = {
1940 			.type = LSM_AUDIT_DATA_FILE,
1941 			.u.file = file,
1942 		},
1943 		.all_existing_optional_access = _LANDLOCK_ACCESS_FS_OPTIONAL,
1944 		.access = LANDLOCK_ACCESS_FS_TRUNCATE,
1945 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1946 		.deny_masks = landlock_file(file)->deny_masks,
1947 		.quiet_optional_accesses = landlock_file(file)->quiet_optional_accesses,
1948 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1949 	});
1950 	return -EACCES;
1951 }
1952 
1953 static int hook_file_ioctl_common(const struct file *const file,
1954 				  const unsigned int cmd, const bool is_compat)
1955 {
1956 	access_mask_t allowed_access = landlock_file(file)->allowed_access;
1957 
1958 	/*
1959 	 * It is the access rights at the time of opening the file which
1960 	 * determine whether IOCTL can be used on the opened file later.
1961 	 *
1962 	 * The access right is attached to the opened file in hook_file_open().
1963 	 */
1964 	if (allowed_access & LANDLOCK_ACCESS_FS_IOCTL_DEV)
1965 		return 0;
1966 
1967 	if (!is_device(file))
1968 		return 0;
1969 
1970 	if (unlikely(is_compat) ? is_masked_device_ioctl_compat(cmd) :
1971 				  is_masked_device_ioctl(cmd))
1972 		return 0;
1973 
1974 	landlock_log_denial(landlock_cred(file->f_cred), &(struct landlock_request) {
1975 		.type = LANDLOCK_REQUEST_FS_ACCESS,
1976 		.audit = {
1977 			.type = LSM_AUDIT_DATA_IOCTL_OP,
1978 			.u.op = &(struct lsm_ioctlop_audit) {
1979 				.path = file->f_path,
1980 				.cmd = cmd,
1981 			},
1982 		},
1983 		.all_existing_optional_access = _LANDLOCK_ACCESS_FS_OPTIONAL,
1984 		.access = LANDLOCK_ACCESS_FS_IOCTL_DEV,
1985 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1986 		.deny_masks = landlock_file(file)->deny_masks,
1987 		.quiet_optional_accesses = landlock_file(file)->quiet_optional_accesses,
1988 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1989 	});
1990 	return -EACCES;
1991 }
1992 
1993 static int hook_file_ioctl(struct file *file, unsigned int cmd,
1994 			   unsigned long arg)
1995 {
1996 	return hook_file_ioctl_common(file, cmd, false);
1997 }
1998 
1999 static int hook_file_ioctl_compat(struct file *file, unsigned int cmd,
2000 				  unsigned long arg)
2001 {
2002 	return hook_file_ioctl_common(file, cmd, true);
2003 }
2004 
2005 /*
2006  * Always allow sending signals between threads of the same process.  This
2007  * ensures consistency with hook_task_kill().
2008  */
2009 static bool control_current_fowner(struct fown_struct *const fown)
2010 {
2011 	struct task_struct *p;
2012 
2013 	/*
2014 	 * Lock already held by __f_setown(), see commit 26f204380a3c ("fs: Fix
2015 	 * file_set_fowner LSM hook inconsistencies").
2016 	 */
2017 	lockdep_assert_held(&fown->lock);
2018 
2019 	/*
2020 	 * A process-group or session owner (PIDTYPE_PGID/PIDTYPE_SID) fans the
2021 	 * signal out to every member at delivery time, so record the domain and
2022 	 * let hook_file_send_sigiotask() check the live scope per recipient.
2023 	 */
2024 	if (fown->pid_type != PIDTYPE_PID && fown->pid_type != PIDTYPE_TGID)
2025 		return true;
2026 
2027 	/*
2028 	 * Some callers (e.g. fcntl_dirnotify) may not be in an RCU read-side
2029 	 * critical section.
2030 	 */
2031 	guard(rcu)();
2032 	p = pid_task(fown->pid, fown->pid_type);
2033 	if (!p)
2034 		return true;
2035 
2036 	return !same_thread_group(p, current);
2037 }
2038 
2039 static void hook_file_set_fowner(struct file *file)
2040 {
2041 	struct landlock_domain *prev_dom;
2042 	struct landlock_cred_security fown_subject = {};
2043 	struct pid *prev_tg, *fown_tg = NULL;
2044 	size_t fown_layer = 0;
2045 
2046 	if (control_current_fowner(file_f_owner(file))) {
2047 		static const struct access_masks signal_scope = {
2048 			.scope = LANDLOCK_SCOPE_SIGNAL,
2049 		};
2050 		const struct landlock_cred_security *new_subject =
2051 			landlock_get_applicable_subject(
2052 				current_cred(), signal_scope, &fown_layer);
2053 		if (new_subject) {
2054 			landlock_get_domain(new_subject->domain);
2055 			fown_subject = *new_subject;
2056 			fown_tg = get_pid(task_tgid(current));
2057 		}
2058 	}
2059 
2060 	prev_dom = landlock_file(file)->fown_subject.domain;
2061 	prev_tg = landlock_file(file)->fown_tg;
2062 	landlock_file(file)->fown_subject = fown_subject;
2063 	landlock_file(file)->fown_tg = fown_tg;
2064 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
2065 	landlock_file(file)->fown_layer = fown_layer;
2066 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
2067 
2068 	/* May be called in an RCU read-side critical section. */
2069 	landlock_put_domain_deferred(prev_dom);
2070 	put_pid(prev_tg);
2071 }
2072 
2073 static void hook_file_free_security(struct file *file)
2074 {
2075 	put_pid(landlock_file(file)->fown_tg);
2076 	landlock_put_domain_deferred(landlock_file(file)->fown_subject.domain);
2077 }
2078 
2079 static struct security_hook_list landlock_hooks[] __ro_after_init = {
2080 	LSM_HOOK_INIT(inode_free_security_rcu, hook_inode_free_security_rcu),
2081 
2082 	LSM_HOOK_INIT(sb_delete, hook_sb_delete),
2083 	LSM_HOOK_INIT(sb_mount, hook_sb_mount),
2084 	LSM_HOOK_INIT(move_mount, hook_move_mount),
2085 	LSM_HOOK_INIT(sb_umount, hook_sb_umount),
2086 	LSM_HOOK_INIT(sb_remount, hook_sb_remount),
2087 	LSM_HOOK_INIT(sb_pivotroot, hook_sb_pivotroot),
2088 
2089 	LSM_HOOK_INIT(path_link, hook_path_link),
2090 	LSM_HOOK_INIT(path_rename, hook_path_rename),
2091 	LSM_HOOK_INIT(path_mkdir, hook_path_mkdir),
2092 	LSM_HOOK_INIT(path_mknod, hook_path_mknod),
2093 	LSM_HOOK_INIT(path_symlink, hook_path_symlink),
2094 	LSM_HOOK_INIT(path_unlink, hook_path_unlink),
2095 	LSM_HOOK_INIT(path_rmdir, hook_path_rmdir),
2096 	LSM_HOOK_INIT(path_truncate, hook_path_truncate),
2097 	LSM_HOOK_INIT(unix_find, hook_unix_find),
2098 
2099 	LSM_HOOK_INIT(file_alloc_security, hook_file_alloc_security),
2100 	LSM_HOOK_INIT(file_open, hook_file_open),
2101 	LSM_HOOK_INIT(file_truncate, hook_file_truncate),
2102 	LSM_HOOK_INIT(file_ioctl, hook_file_ioctl),
2103 	LSM_HOOK_INIT(file_ioctl_compat, hook_file_ioctl_compat),
2104 	LSM_HOOK_INIT(file_set_fowner, hook_file_set_fowner),
2105 	LSM_HOOK_INIT(file_free_security, hook_file_free_security),
2106 };
2107 
2108 __init void landlock_add_fs_hooks(void)
2109 {
2110 	security_add_hooks(landlock_hooks, ARRAY_SIZE(landlock_hooks),
2111 			   &landlock_lsmid);
2112 }
2113 
2114 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
2115 
2116 /* clang-format off */
2117 static struct kunit_case test_cases[] = {
2118 	KUNIT_CASE(test_no_more_access),
2119 	KUNIT_CASE(test_scope_to_request_with_exec_none),
2120 	KUNIT_CASE(test_scope_to_request_with_exec_some),
2121 	KUNIT_CASE(test_scope_to_request_without_access),
2122 	KUNIT_CASE(test_is_eacces_with_none),
2123 	KUNIT_CASE(test_is_eacces_with_refer),
2124 	KUNIT_CASE(test_is_eacces_with_write),
2125 	{}
2126 };
2127 /* clang-format on */
2128 
2129 static struct kunit_suite test_suite = {
2130 	.name = "landlock_fs",
2131 	.test_cases = test_cases,
2132 };
2133 
2134 kunit_test_suite(test_suite);
2135 
2136 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
2137