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
release_inode(struct landlock_object * const object)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 */
is_masked_device_ioctl(const unsigned int cmd)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
is_masked_device_ioctl_compat(const unsigned int cmd)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
get_inode_object(struct inode * const inode)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 */
landlock_append_fs_rule(struct landlock_ruleset * const ruleset,const struct path * const path,access_mask_t access_rights,const u32 flags)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 */
get_inode_id(const struct dentry * const dentry,struct landlock_id * id)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
unmask_layers_fs(const struct landlock_domain * const domain,const struct landlock_id id,const access_mask_t access_request,struct layer_masks * masks,const struct dentry * const dentry)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 */
is_nouser_or_private(const struct dentry * dentry)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 */
may_refer(const struct layer_masks * const src_parent,const struct layer_masks * const src_child,const struct layer_masks * const new_parent,const bool child_is_dir)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 */
no_more_access(const struct layer_masks * const parent1,const struct layer_masks * const child1,const bool child1_is_dir,const struct layer_masks * const parent2,const struct layer_masks * const child2,const bool child2_is_dir)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
test_no_more_access(struct kunit * const test)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
is_layer_masks_allowed(const struct layer_masks * masks)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 */
scope_to_request(const access_mask_t access_request,struct layer_masks * masks)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
test_scope_to_request_with_exec_none(struct kunit * const test)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
test_scope_to_request_with_exec_some(struct kunit * const test)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
test_scope_to_request_without_access(struct kunit * const test)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 */
is_eacces(const struct layer_masks * masks,const access_mask_t access_request)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
test_is_eacces_with_none(struct kunit * const test)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
test_is_eacces_with_refer(struct kunit * const test)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
test_is_eacces_with_write(struct kunit * const test)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
is_access_to_paths_allowed(const struct landlock_domain * const domain,const struct path * const path,const access_mask_t access_request_parent1,struct layer_masks * layer_masks_parent1,struct landlock_request * const log_request_parent1,struct dentry * const dentry_child1,const access_mask_t access_request_parent2,struct layer_masks * layer_masks_parent2,struct landlock_request * const log_request_parent2,struct dentry * const dentry_child2)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
current_check_access_path(const struct path * const path,access_mask_t access_request)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
get_mode_access(const umode_t mode,const dev_t dev)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
get_dentry_access(const struct dentry * const dentry)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
maybe_remove(const struct dentry * const dentry)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 */
collect_domain_accesses(const struct landlock_domain * const domain,const struct dentry * const mnt_root,struct dentry * dir,struct layer_masks * layer_masks_dom)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 */
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,const bool whiteout)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). Pin the dentry used as old_parent in either case.
1302 * Otherwise, dget_parent() safely fetches and pins the current parent
1303 * against a concurrent rename(2).
1304 */
1305 old_parent = (old_dentry == mnt_dir.dentry) ? dget(old_dentry) :
1306 dget_parent(old_dentry);
1307
1308 /* new_dir->dentry is equal to new_dentry->d_parent */
1309 allow_parent1 = collect_domain_accesses(subject->domain, mnt_dir.dentry,
1310 old_parent,
1311 &layer_masks_parent1);
1312 allow_parent2 = collect_domain_accesses(subject->domain, mnt_dir.dentry,
1313 new_dir->dentry,
1314 &layer_masks_parent2);
1315 if (allow_parent1 && allow_parent2) {
1316 dput(old_parent);
1317 return 0;
1318 }
1319
1320 /*
1321 * To be able to compare source and destination domain access rights,
1322 * take into account the @old_dentry access rights aggregated with its
1323 * parent access rights. This will be useful to compare with the
1324 * destination parent access rights.
1325 */
1326 if (is_access_to_paths_allowed(
1327 subject->domain, &mnt_dir, access_request_parent1,
1328 &layer_masks_parent1, &request1, old_dentry,
1329 access_request_parent2, &layer_masks_parent2, &request2,
1330 exchange ? new_dentry : NULL)) {
1331 dput(old_parent);
1332 return 0;
1333 }
1334
1335 if (request1.access) {
1336 request1.audit.u.path.dentry = old_parent;
1337 landlock_log_denial(subject, &request1);
1338 }
1339 if (request2.access) {
1340 request2.audit.u.path.dentry = new_dir->dentry;
1341 landlock_log_denial(subject, &request2);
1342 }
1343 dput(old_parent);
1344
1345 /*
1346 * This prioritizes EACCES over EXDEV for all actions, including
1347 * renames with RENAME_EXCHANGE.
1348 */
1349 if (likely(is_eacces(&layer_masks_parent1, access_request_parent1) ||
1350 is_eacces(&layer_masks_parent2, access_request_parent2)))
1351 return -EACCES;
1352
1353 /*
1354 * Gracefully forbids reparenting if the destination directory
1355 * hierarchy is not a superset of restrictions of the source directory
1356 * hierarchy, or if LANDLOCK_ACCESS_FS_REFER is not allowed by the
1357 * source or the destination.
1358 */
1359 return -EXDEV;
1360 }
1361
1362 /* Inode hooks */
1363
hook_inode_free_security_rcu(void * inode_security)1364 static void hook_inode_free_security_rcu(void *inode_security)
1365 {
1366 struct landlock_inode_security *inode_sec;
1367
1368 /*
1369 * All inodes must already have been untied from their object by
1370 * release_inode() or hook_sb_delete().
1371 */
1372 inode_sec = inode_security + landlock_blob_sizes.lbs_inode;
1373 WARN_ON_ONCE(inode_sec->object);
1374 }
1375
1376 /* Super-block hooks */
1377
1378 /*
1379 * Release the inodes used in a security policy.
1380 *
1381 * Cf. fsnotify_unmount_inodes() and evict_inodes()
1382 */
hook_sb_delete(struct super_block * const sb)1383 static void hook_sb_delete(struct super_block *const sb)
1384 {
1385 struct inode *inode, *prev_inode = NULL;
1386
1387 if (!landlock_initialized)
1388 return;
1389
1390 spin_lock(&sb->s_inode_list_lock);
1391 list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
1392 struct landlock_object *object;
1393
1394 /* Only handles referenced inodes. */
1395 if (!icount_read_once(inode))
1396 continue;
1397
1398 /*
1399 * Protects against concurrent modification of inode (e.g.
1400 * from get_inode_object()).
1401 */
1402 spin_lock(&inode->i_lock);
1403 /*
1404 * Checks I_FREEING and I_WILL_FREE to protect against a race
1405 * condition when release_inode() just called iput(), which
1406 * could lead to a NULL dereference of inode->security or a
1407 * second call to iput() for the same Landlock object. Also
1408 * checks I_NEW because such inode cannot be tied to an object.
1409 */
1410 if (inode_state_read(inode) &
1411 (I_FREEING | I_WILL_FREE | I_NEW)) {
1412 spin_unlock(&inode->i_lock);
1413 continue;
1414 }
1415
1416 rcu_read_lock();
1417 object = rcu_dereference(landlock_inode(inode)->object);
1418 if (!object) {
1419 rcu_read_unlock();
1420 spin_unlock(&inode->i_lock);
1421 continue;
1422 }
1423 /* Keeps a reference to this inode until the next loop walk. */
1424 __iget(inode);
1425 spin_unlock(&inode->i_lock);
1426
1427 /*
1428 * If there is no concurrent release_inode() ongoing, then we
1429 * are in charge of calling iput() on this inode, otherwise we
1430 * will just wait for it to finish.
1431 */
1432 spin_lock(&object->lock);
1433 if (object->underobj == inode) {
1434 object->underobj = NULL;
1435 spin_unlock(&object->lock);
1436 rcu_read_unlock();
1437
1438 /*
1439 * Because object->underobj was not NULL,
1440 * release_inode() and get_inode_object() guarantee
1441 * that it is safe to reset
1442 * landlock_inode(inode)->object while it is not NULL.
1443 * It is therefore not necessary to lock inode->i_lock.
1444 */
1445 rcu_assign_pointer(landlock_inode(inode)->object, NULL);
1446 /*
1447 * At this point, we own the ihold() reference that was
1448 * originally set up by get_inode_object() and the
1449 * __iget() reference that we just set in this loop
1450 * walk. Therefore there are at least two references
1451 * on the inode.
1452 */
1453 iput_not_last(inode);
1454 } else {
1455 spin_unlock(&object->lock);
1456 rcu_read_unlock();
1457 }
1458
1459 if (prev_inode) {
1460 /*
1461 * At this point, we still own the __iget() reference
1462 * that we just set in this loop walk. Therefore we
1463 * can drop the list lock and know that the inode won't
1464 * disappear from under us until the next loop walk.
1465 */
1466 spin_unlock(&sb->s_inode_list_lock);
1467 /*
1468 * We can now actually put the inode reference from the
1469 * previous loop walk, which is not needed anymore.
1470 */
1471 iput(prev_inode);
1472 cond_resched();
1473 spin_lock(&sb->s_inode_list_lock);
1474 }
1475 prev_inode = inode;
1476 }
1477 spin_unlock(&sb->s_inode_list_lock);
1478
1479 /* Puts the inode reference from the last loop walk, if any. */
1480 if (prev_inode)
1481 iput(prev_inode);
1482 /* Waits for pending iput() in release_inode(). */
1483 wait_var_event(&landlock_superblock(sb)->inode_refs,
1484 !atomic_long_read(&landlock_superblock(sb)->inode_refs));
1485 }
1486
1487 static void
log_fs_change_topology_path(const struct landlock_cred_security * const subject,size_t handle_layer,const struct path * const path)1488 log_fs_change_topology_path(const struct landlock_cred_security *const subject,
1489 size_t handle_layer, const struct path *const path)
1490 {
1491 landlock_log_denial(subject, &(struct landlock_request) {
1492 .type = LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY,
1493 .audit = {
1494 .type = LSM_AUDIT_DATA_PATH,
1495 .u.path = *path,
1496 },
1497 .layer_plus_one = handle_layer + 1,
1498 });
1499 }
1500
log_fs_change_topology_dentry(const struct landlock_cred_security * const subject,size_t handle_layer,struct dentry * const dentry)1501 static void log_fs_change_topology_dentry(
1502 const struct landlock_cred_security *const subject, size_t handle_layer,
1503 struct dentry *const dentry)
1504 {
1505 landlock_log_denial(subject, &(struct landlock_request) {
1506 .type = LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY,
1507 .audit = {
1508 .type = LSM_AUDIT_DATA_DENTRY,
1509 .u.dentry = dentry,
1510 },
1511 .layer_plus_one = handle_layer + 1,
1512 });
1513 }
1514
1515 /*
1516 * Because a Landlock security policy is defined according to the filesystem
1517 * topology (i.e. the mount namespace), changing it may grant access to files
1518 * not previously allowed.
1519 *
1520 * To make it simple, deny any filesystem topology modification by landlocked
1521 * processes. Non-landlocked processes may still change the namespace of a
1522 * landlocked process, but this kind of threat must be handled by a system-wide
1523 * access-control security policy.
1524 *
1525 * This could be lifted in the future if Landlock can safely handle mount
1526 * namespace updates requested by a landlocked process. Indeed, we could
1527 * update the current domain (which is currently read-only) by taking into
1528 * account the accesses of the source and the destination of a new mount point.
1529 * However, it would also require to make all the child domains dynamically
1530 * inherit these new constraints. Anyway, for backward compatibility reasons,
1531 * a dedicated user space option would be required (e.g. as a ruleset flag).
1532 */
hook_sb_mount(const char * const dev_name,const struct path * const path,const char * const type,const unsigned long flags,void * const data)1533 static int hook_sb_mount(const char *const dev_name,
1534 const struct path *const path, const char *const type,
1535 const unsigned long flags, void *const data)
1536 {
1537 size_t handle_layer;
1538 const struct landlock_cred_security *const subject =
1539 landlock_get_applicable_subject(current_cred(), any_fs,
1540 &handle_layer);
1541
1542 if (!subject)
1543 return 0;
1544
1545 log_fs_change_topology_path(subject, handle_layer, path);
1546 return -EPERM;
1547 }
1548
hook_move_mount(const struct path * const from_path,const struct path * const to_path)1549 static int hook_move_mount(const struct path *const from_path,
1550 const struct path *const to_path)
1551 {
1552 size_t handle_layer;
1553 const struct landlock_cred_security *const subject =
1554 landlock_get_applicable_subject(current_cred(), any_fs,
1555 &handle_layer);
1556
1557 if (!subject)
1558 return 0;
1559
1560 log_fs_change_topology_path(subject, handle_layer, to_path);
1561 return -EPERM;
1562 }
1563
1564 /*
1565 * Removing a mount point may reveal a previously hidden file hierarchy, which
1566 * may then grant access to files, which may have previously been forbidden.
1567 */
hook_sb_umount(struct vfsmount * const mnt,const int flags)1568 static int hook_sb_umount(struct vfsmount *const mnt, const int flags)
1569 {
1570 size_t handle_layer;
1571 const struct landlock_cred_security *const subject =
1572 landlock_get_applicable_subject(current_cred(), any_fs,
1573 &handle_layer);
1574
1575 if (!subject)
1576 return 0;
1577
1578 log_fs_change_topology_dentry(subject, handle_layer, mnt->mnt_root);
1579 return -EPERM;
1580 }
1581
hook_sb_remount(struct super_block * const sb,void * const mnt_opts)1582 static int hook_sb_remount(struct super_block *const sb, void *const mnt_opts)
1583 {
1584 size_t handle_layer;
1585 const struct landlock_cred_security *const subject =
1586 landlock_get_applicable_subject(current_cred(), any_fs,
1587 &handle_layer);
1588
1589 if (!subject)
1590 return 0;
1591
1592 log_fs_change_topology_dentry(subject, handle_layer, sb->s_root);
1593 return -EPERM;
1594 }
1595
1596 /*
1597 * pivot_root(2), like mount(2), changes the current mount namespace. It must
1598 * then be forbidden for a landlocked process.
1599 *
1600 * However, chroot(2) may be allowed because it only changes the relative root
1601 * directory of the current process. Moreover, it can be used to restrict the
1602 * view of the filesystem.
1603 */
hook_sb_pivotroot(const struct path * const old_path,const struct path * const new_path)1604 static int hook_sb_pivotroot(const struct path *const old_path,
1605 const struct path *const new_path)
1606 {
1607 size_t handle_layer;
1608 const struct landlock_cred_security *const subject =
1609 landlock_get_applicable_subject(current_cred(), any_fs,
1610 &handle_layer);
1611
1612 if (!subject)
1613 return 0;
1614
1615 log_fs_change_topology_path(subject, handle_layer, new_path);
1616 return -EPERM;
1617 }
1618
1619 /* Path hooks */
1620
hook_path_link(struct dentry * const old_dentry,const struct path * const new_dir,struct dentry * const new_dentry)1621 static int hook_path_link(struct dentry *const old_dentry,
1622 const struct path *const new_dir,
1623 struct dentry *const new_dentry)
1624 {
1625 return current_check_refer_path(old_dentry, new_dir, new_dentry, false,
1626 false, false);
1627 }
1628
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)1629 static int hook_path_rename(const struct path *const old_dir,
1630 struct dentry *const old_dentry,
1631 const struct path *const new_dir,
1632 struct dentry *const new_dentry,
1633 const unsigned int flags)
1634 {
1635 /* old_dir refers to old_dentry->d_parent and new_dir->mnt */
1636 return current_check_refer_path(old_dentry, new_dir, new_dentry, true,
1637 !!(flags & RENAME_EXCHANGE),
1638 !!(flags & RENAME_WHITEOUT));
1639 }
1640
hook_path_mkdir(const struct path * const dir,struct dentry * const dentry,const umode_t mode)1641 static int hook_path_mkdir(const struct path *const dir,
1642 struct dentry *const dentry, const umode_t mode)
1643 {
1644 return current_check_access_path(dir, LANDLOCK_ACCESS_FS_MAKE_DIR);
1645 }
1646
hook_path_mknod(const struct path * const dir,struct dentry * const dentry,const umode_t mode,const unsigned int dev)1647 static int hook_path_mknod(const struct path *const dir,
1648 struct dentry *const dentry, const umode_t mode,
1649 const unsigned int dev)
1650 {
1651 return current_check_access_path(
1652 dir, get_mode_access(mode, new_decode_dev(dev)));
1653 }
1654
hook_path_symlink(const struct path * const dir,struct dentry * const dentry,const char * const old_name)1655 static int hook_path_symlink(const struct path *const dir,
1656 struct dentry *const dentry,
1657 const char *const old_name)
1658 {
1659 return current_check_access_path(dir, LANDLOCK_ACCESS_FS_MAKE_SYM);
1660 }
1661
hook_path_unlink(const struct path * const dir,struct dentry * const dentry)1662 static int hook_path_unlink(const struct path *const dir,
1663 struct dentry *const dentry)
1664 {
1665 return current_check_access_path(dir, LANDLOCK_ACCESS_FS_REMOVE_FILE);
1666 }
1667
hook_path_rmdir(const struct path * const dir,struct dentry * const dentry)1668 static int hook_path_rmdir(const struct path *const dir,
1669 struct dentry *const dentry)
1670 {
1671 return current_check_access_path(dir, LANDLOCK_ACCESS_FS_REMOVE_DIR);
1672 }
1673
hook_path_truncate(const struct path * const path)1674 static int hook_path_truncate(const struct path *const path)
1675 {
1676 return current_check_access_path(path, LANDLOCK_ACCESS_FS_TRUNCATE);
1677 }
1678
1679 /**
1680 * unmask_scoped_access - Remove access right bits in @masks in all layers
1681 * where @client and @server have the same domain
1682 *
1683 * This does the same as domain_is_scoped(), but unmasks bits in @masks.
1684 * It can not return early as domain_is_scoped() does.
1685 *
1686 * A scoped access for a given access right bit is allowed iff, for all layer
1687 * depths where the access bit is set, the client and server domain are the
1688 * same. This function clears the access rights @access in @masks at all layer
1689 * depths where the client and server domain are the same, so that, when they
1690 * are all cleared, the access is allowed.
1691 *
1692 * @client: Client domain
1693 * @server: Server domain
1694 * @masks: Layer access masks to unmask
1695 * @access: Access bits that control scoping
1696 */
unmask_scoped_access(const struct landlock_domain * const client,const struct landlock_domain * const server,struct layer_masks * const masks,const access_mask_t access)1697 static void unmask_scoped_access(const struct landlock_domain *const client,
1698 const struct landlock_domain *const server,
1699 struct layer_masks *const masks,
1700 const access_mask_t access)
1701 {
1702 int client_layer, server_layer;
1703 const struct landlock_hierarchy *client_walker, *server_walker;
1704
1705 /* This should not happen. */
1706 if (WARN_ON_ONCE(!client))
1707 return;
1708
1709 /* Server has no Landlock domain; nothing to clear. */
1710 if (!server)
1711 return;
1712
1713 /*
1714 * client_layer must be able to represent all numbers from
1715 * LANDLOCK_MAX_NUM_LAYERS - 1 to -1 for the loop below to terminate.
1716 * (It must be large enough, and it must be signed.)
1717 */
1718 BUILD_BUG_ON(!is_signed_type(typeof(client_layer)));
1719 BUILD_BUG_ON(LANDLOCK_MAX_NUM_LAYERS - 1 >
1720 type_max(typeof(client_layer)));
1721
1722 client_layer = client->num_layers - 1;
1723 client_walker = client->hierarchy;
1724 server_layer = server->num_layers - 1;
1725 server_walker = server->hierarchy;
1726
1727 /*
1728 * Clears the access bits at all layers where the client domain is the
1729 * same as the server domain. We start the walk at min(client_layer,
1730 * server_layer). The layer bits until there can not be cleared because
1731 * either the client or the server domain is missing.
1732 */
1733 for (; client_layer > server_layer; client_layer--)
1734 client_walker = client_walker->parent;
1735
1736 for (; server_layer > client_layer; server_layer--)
1737 server_walker = server_walker->parent;
1738
1739 for (; client_layer >= 0; client_layer--) {
1740 if (masks->layers[client_layer].access & access &&
1741 client_walker == server_walker)
1742 masks->layers[client_layer].access &= ~access;
1743
1744 client_walker = client_walker->parent;
1745 server_walker = server_walker->parent;
1746 }
1747 }
1748
hook_unix_find(const struct path * const path,struct sock * other,int flags)1749 static int hook_unix_find(const struct path *const path, struct sock *other,
1750 int flags)
1751 {
1752 const struct landlock_domain *dom_other;
1753 const struct landlock_cred_security *subject;
1754 struct layer_masks layer_masks;
1755 struct landlock_request request = {};
1756 static const struct access_masks fs_resolve_unix = {
1757 .fs = LANDLOCK_ACCESS_FS_RESOLVE_UNIX,
1758 };
1759
1760 /* Lookup for the purpose of saving coredumps is OK. */
1761 if (unlikely(flags & SOCK_COREDUMP))
1762 return 0;
1763
1764 subject = landlock_get_applicable_subject(current_cred(),
1765 fs_resolve_unix, NULL);
1766
1767 if (!subject)
1768 return 0;
1769
1770 /*
1771 * Ignoring return value: that the domains apply was already checked in
1772 * landlock_get_applicable_subject() above.
1773 */
1774 landlock_init_layer_masks(subject->domain, fs_resolve_unix.fs,
1775 &layer_masks, LANDLOCK_KEY_INODE);
1776
1777 /* Checks the layers in which we are connecting within the same domain. */
1778 unix_state_lock(other);
1779 if (unlikely(sock_flag(other, SOCK_DEAD) || !other->sk_socket ||
1780 !other->sk_socket->file)) {
1781 unix_state_unlock(other);
1782 /*
1783 * We rely on the caller to catch the (non-reversible) SOCK_DEAD
1784 * condition and retry the lookup. If we returned an error
1785 * here, the lookup would not get retried.
1786 */
1787 return 0;
1788 }
1789 dom_other = landlock_cred(other->sk_socket->file->f_cred)->domain;
1790
1791 /* Access to the same (or a lower) domain is always allowed. */
1792 unmask_scoped_access(subject->domain, dom_other, &layer_masks,
1793 fs_resolve_unix.fs);
1794 unix_state_unlock(other);
1795
1796 /* Checks the connections to allow-listed paths. */
1797 if (is_access_to_paths_allowed(subject->domain, path,
1798 fs_resolve_unix.fs, &layer_masks,
1799 &request, NULL, 0, NULL, NULL, NULL))
1800 return 0;
1801
1802 landlock_log_denial(subject, &request);
1803 return -EACCES;
1804 }
1805
1806 /* File hooks */
1807
1808 /**
1809 * get_required_file_open_access - Get access needed to open a file
1810 *
1811 * @file: File being opened.
1812 *
1813 * Return: The access rights that are required for opening the given file,
1814 * depending on the file type and open mode.
1815 */
1816 static access_mask_t
get_required_file_open_access(const struct file * const file)1817 get_required_file_open_access(const struct file *const file)
1818 {
1819 access_mask_t access = 0;
1820
1821 if (file->f_mode & FMODE_READ) {
1822 /* A directory can only be opened in read mode. */
1823 if (S_ISDIR(file_inode(file)->i_mode))
1824 return LANDLOCK_ACCESS_FS_READ_DIR;
1825 access = LANDLOCK_ACCESS_FS_READ_FILE;
1826 }
1827 if (file->f_mode & FMODE_WRITE)
1828 access |= LANDLOCK_ACCESS_FS_WRITE_FILE;
1829 /* __FMODE_EXEC is indeed part of f_flags, not f_mode. */
1830 if (file->f_flags & __FMODE_EXEC)
1831 access |= LANDLOCK_ACCESS_FS_EXECUTE;
1832 return access;
1833 }
1834
hook_file_alloc_security(struct file * const file)1835 static int hook_file_alloc_security(struct file *const file)
1836 {
1837 /*
1838 * Grants all access rights, even if most of them are not checked later
1839 * on. It is more consistent.
1840 *
1841 * Notably, file descriptors for regular files can also be acquired
1842 * without going through the file_open hook, for example when using
1843 * memfd_create(2).
1844 */
1845 landlock_file(file)->allowed_access = LANDLOCK_MASK_ACCESS_FS;
1846 return 0;
1847 }
1848
is_device(const struct file * const file)1849 static bool is_device(const struct file *const file)
1850 {
1851 const struct inode *inode = file_inode(file);
1852
1853 return S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode);
1854 }
1855
hook_file_open(struct file * const file)1856 static int hook_file_open(struct file *const file)
1857 {
1858 struct layer_masks layer_masks = {};
1859 access_mask_t open_access_request, full_access_request, allowed_access,
1860 optional_access;
1861 const struct landlock_cred_security *const subject =
1862 landlock_get_applicable_subject(file->f_cred, any_fs, NULL);
1863 struct landlock_request request = {};
1864
1865 if (!subject)
1866 return 0;
1867
1868 /*
1869 * Because a file may be opened with O_PATH, get_required_file_open_access()
1870 * may return 0. This case will be handled with a future Landlock
1871 * evolution.
1872 */
1873 open_access_request = get_required_file_open_access(file);
1874
1875 /*
1876 * We look up more access than what we immediately need for open(), so
1877 * that we can later authorize operations on opened files.
1878 */
1879 optional_access = LANDLOCK_ACCESS_FS_TRUNCATE;
1880 if (is_device(file))
1881 optional_access |= LANDLOCK_ACCESS_FS_IOCTL_DEV;
1882
1883 full_access_request = open_access_request | optional_access;
1884
1885 if (is_access_to_paths_allowed(
1886 subject->domain, &file->f_path,
1887 landlock_init_layer_masks(subject->domain,
1888 full_access_request, &layer_masks,
1889 LANDLOCK_KEY_INODE),
1890 &layer_masks, &request, NULL, 0, NULL, NULL, NULL)) {
1891 allowed_access = full_access_request;
1892 } else {
1893 /*
1894 * Calculate the actual allowed access rights from layer_masks.
1895 * Remove the access rights from the full access request which
1896 * are still unfulfilled in any of the layers.
1897 */
1898 allowed_access = full_access_request;
1899 for (size_t i = 0; i < ARRAY_SIZE(layer_masks.layers); i++)
1900 allowed_access &= ~layer_masks.layers[i].access;
1901 }
1902
1903 /*
1904 * For operations on already opened files (i.e. ftruncate()), it is the
1905 * access rights at the time of open() which decide whether the
1906 * operation is permitted. Therefore, we record the relevant subset of
1907 * file access rights in the opened struct file.
1908 */
1909 landlock_file(file)->allowed_access = allowed_access;
1910 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1911 landlock_file(file)->deny_masks = landlock_get_deny_masks(
1912 _LANDLOCK_ACCESS_FS_OPTIONAL, optional_access, &layer_masks);
1913 landlock_file(file)->quiet_optional_accesses =
1914 landlock_get_quiet_optional_accesses(
1915 _LANDLOCK_ACCESS_FS_OPTIONAL,
1916 landlock_file(file)->deny_masks, &layer_masks);
1917 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1918
1919 if (access_mask_subset(open_access_request, allowed_access))
1920 return 0;
1921
1922 /* Sets access to reflect the actual request. */
1923 request.access = open_access_request;
1924 landlock_log_denial(subject, &request);
1925 return -EACCES;
1926 }
1927
hook_file_truncate(struct file * const file)1928 static int hook_file_truncate(struct file *const file)
1929 {
1930 /*
1931 * Allows truncation if the truncate right was available at the time of
1932 * opening the file, to get a consistent access check as for read, write
1933 * and execute operations.
1934 *
1935 * Note: For checks done based on the file's Landlock allowed access, we
1936 * enforce them independently of whether the current thread is in a
1937 * Landlock domain, so that open files passed between independent
1938 * processes retain their behaviour.
1939 */
1940 if (landlock_file(file)->allowed_access & LANDLOCK_ACCESS_FS_TRUNCATE)
1941 return 0;
1942
1943 landlock_log_denial(landlock_cred(file->f_cred), &(struct landlock_request) {
1944 .type = LANDLOCK_REQUEST_FS_ACCESS,
1945 .audit = {
1946 .type = LSM_AUDIT_DATA_FILE,
1947 .u.file = file,
1948 },
1949 .all_existing_optional_access = _LANDLOCK_ACCESS_FS_OPTIONAL,
1950 .access = LANDLOCK_ACCESS_FS_TRUNCATE,
1951 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1952 .deny_masks = landlock_file(file)->deny_masks,
1953 .quiet_optional_accesses = landlock_file(file)->quiet_optional_accesses,
1954 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1955 });
1956 return -EACCES;
1957 }
1958
hook_file_ioctl_common(const struct file * const file,const unsigned int cmd,const bool is_compat)1959 static int hook_file_ioctl_common(const struct file *const file,
1960 const unsigned int cmd, const bool is_compat)
1961 {
1962 access_mask_t allowed_access = landlock_file(file)->allowed_access;
1963
1964 /*
1965 * It is the access rights at the time of opening the file which
1966 * determine whether IOCTL can be used on the opened file later.
1967 *
1968 * The access right is attached to the opened file in hook_file_open().
1969 */
1970 if (allowed_access & LANDLOCK_ACCESS_FS_IOCTL_DEV)
1971 return 0;
1972
1973 if (!is_device(file))
1974 return 0;
1975
1976 if (unlikely(is_compat) ? is_masked_device_ioctl_compat(cmd) :
1977 is_masked_device_ioctl(cmd))
1978 return 0;
1979
1980 landlock_log_denial(landlock_cred(file->f_cred), &(struct landlock_request) {
1981 .type = LANDLOCK_REQUEST_FS_ACCESS,
1982 .audit = {
1983 .type = LSM_AUDIT_DATA_IOCTL_OP,
1984 .u.op = &(struct lsm_ioctlop_audit) {
1985 .path = file->f_path,
1986 .cmd = cmd,
1987 },
1988 },
1989 .all_existing_optional_access = _LANDLOCK_ACCESS_FS_OPTIONAL,
1990 .access = LANDLOCK_ACCESS_FS_IOCTL_DEV,
1991 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
1992 .deny_masks = landlock_file(file)->deny_masks,
1993 .quiet_optional_accesses = landlock_file(file)->quiet_optional_accesses,
1994 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
1995 });
1996 return -EACCES;
1997 }
1998
hook_file_ioctl(struct file * file,unsigned int cmd,unsigned long arg)1999 static int hook_file_ioctl(struct file *file, unsigned int cmd,
2000 unsigned long arg)
2001 {
2002 return hook_file_ioctl_common(file, cmd, false);
2003 }
2004
hook_file_ioctl_compat(struct file * file,unsigned int cmd,unsigned long arg)2005 static int hook_file_ioctl_compat(struct file *file, unsigned int cmd,
2006 unsigned long arg)
2007 {
2008 return hook_file_ioctl_common(file, cmd, true);
2009 }
2010
2011 /*
2012 * Always allow sending signals between threads of the same process. This
2013 * ensures consistency with hook_task_kill().
2014 */
control_current_fowner(struct fown_struct * const fown)2015 static bool control_current_fowner(struct fown_struct *const fown)
2016 {
2017 struct task_struct *p;
2018
2019 /*
2020 * Lock already held by __f_setown(), see commit 26f204380a3c ("fs: Fix
2021 * file_set_fowner LSM hook inconsistencies").
2022 */
2023 lockdep_assert_held(&fown->lock);
2024
2025 /*
2026 * A process-group or session owner (PIDTYPE_PGID/PIDTYPE_SID) fans the
2027 * signal out to every member at delivery time, so record the domain and
2028 * let hook_file_send_sigiotask() check the live scope per recipient.
2029 */
2030 if (fown->pid_type != PIDTYPE_PID && fown->pid_type != PIDTYPE_TGID)
2031 return true;
2032
2033 /*
2034 * Some callers (e.g. fcntl_dirnotify) may not be in an RCU read-side
2035 * critical section.
2036 */
2037 guard(rcu)();
2038 p = pid_task(fown->pid, fown->pid_type);
2039 if (!p)
2040 return true;
2041
2042 return !same_thread_group(p, current);
2043 }
2044
hook_file_set_fowner(struct file * file)2045 static void hook_file_set_fowner(struct file *file)
2046 {
2047 struct landlock_domain *prev_dom;
2048 struct landlock_cred_security fown_subject = {};
2049 struct pid *prev_tg, *fown_tg = NULL;
2050 size_t fown_layer = 0;
2051
2052 if (control_current_fowner(file_f_owner(file))) {
2053 static const struct access_masks signal_scope = {
2054 .scope = LANDLOCK_SCOPE_SIGNAL,
2055 };
2056 const struct landlock_cred_security *new_subject =
2057 landlock_get_applicable_subject(
2058 current_cred(), signal_scope, &fown_layer);
2059 if (new_subject) {
2060 landlock_get_domain(new_subject->domain);
2061 fown_subject = *new_subject;
2062 fown_tg = get_pid(task_tgid(current));
2063 }
2064 }
2065
2066 prev_dom = landlock_file(file)->fown_subject.domain;
2067 prev_tg = landlock_file(file)->fown_tg;
2068 landlock_file(file)->fown_subject = fown_subject;
2069 landlock_file(file)->fown_tg = fown_tg;
2070 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
2071 landlock_file(file)->fown_layer = fown_layer;
2072 #endif /* CONFIG_SECURITY_LANDLOCK_LOG */
2073
2074 /* May be called in an RCU read-side critical section. */
2075 landlock_put_domain_deferred(prev_dom);
2076 put_pid(prev_tg);
2077 }
2078
hook_file_free_security(struct file * file)2079 static void hook_file_free_security(struct file *file)
2080 {
2081 put_pid(landlock_file(file)->fown_tg);
2082 landlock_put_domain_deferred(landlock_file(file)->fown_subject.domain);
2083 }
2084
2085 static struct security_hook_list landlock_hooks[] __ro_after_init = {
2086 LSM_HOOK_INIT(inode_free_security_rcu, hook_inode_free_security_rcu),
2087
2088 LSM_HOOK_INIT(sb_delete, hook_sb_delete),
2089 LSM_HOOK_INIT(sb_mount, hook_sb_mount),
2090 LSM_HOOK_INIT(move_mount, hook_move_mount),
2091 LSM_HOOK_INIT(sb_umount, hook_sb_umount),
2092 LSM_HOOK_INIT(sb_remount, hook_sb_remount),
2093 LSM_HOOK_INIT(sb_pivotroot, hook_sb_pivotroot),
2094
2095 LSM_HOOK_INIT(path_link, hook_path_link),
2096 LSM_HOOK_INIT(path_rename, hook_path_rename),
2097 LSM_HOOK_INIT(path_mkdir, hook_path_mkdir),
2098 LSM_HOOK_INIT(path_mknod, hook_path_mknod),
2099 LSM_HOOK_INIT(path_symlink, hook_path_symlink),
2100 LSM_HOOK_INIT(path_unlink, hook_path_unlink),
2101 LSM_HOOK_INIT(path_rmdir, hook_path_rmdir),
2102 LSM_HOOK_INIT(path_truncate, hook_path_truncate),
2103 LSM_HOOK_INIT(unix_find, hook_unix_find),
2104
2105 LSM_HOOK_INIT(file_alloc_security, hook_file_alloc_security),
2106 LSM_HOOK_INIT(file_open, hook_file_open),
2107 LSM_HOOK_INIT(file_truncate, hook_file_truncate),
2108 LSM_HOOK_INIT(file_ioctl, hook_file_ioctl),
2109 LSM_HOOK_INIT(file_ioctl_compat, hook_file_ioctl_compat),
2110 LSM_HOOK_INIT(file_set_fowner, hook_file_set_fowner),
2111 LSM_HOOK_INIT(file_free_security, hook_file_free_security),
2112 };
2113
landlock_add_fs_hooks(void)2114 __init void landlock_add_fs_hooks(void)
2115 {
2116 security_add_hooks(landlock_hooks, ARRAY_SIZE(landlock_hooks),
2117 &landlock_lsmid);
2118 }
2119
2120 #ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
2121
2122 /* clang-format off */
2123 static struct kunit_case test_cases[] = {
2124 KUNIT_CASE(test_no_more_access),
2125 KUNIT_CASE(test_scope_to_request_with_exec_none),
2126 KUNIT_CASE(test_scope_to_request_with_exec_some),
2127 KUNIT_CASE(test_scope_to_request_without_access),
2128 KUNIT_CASE(test_is_eacces_with_none),
2129 KUNIT_CASE(test_is_eacces_with_refer),
2130 KUNIT_CASE(test_is_eacces_with_write),
2131 {}
2132 };
2133 /* clang-format on */
2134
2135 static struct kunit_suite test_suite = {
2136 .name = "landlock_fs",
2137 .test_cases = test_cases,
2138 };
2139
2140 kunit_test_suite(test_suite);
2141
2142 #endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
2143