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