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