Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Landlock LSM - Filesystem management and hooks
0004  *
0005  * Copyright © 2016-2020 Mickaël Salaün <mic@digikod.net>
0006  * Copyright © 2018-2020 ANSSI
0007  * Copyright © 2021-2022 Microsoft Corporation
0008  */
0009 
0010 #include <linux/atomic.h>
0011 #include <linux/bitops.h>
0012 #include <linux/bits.h>
0013 #include <linux/compiler_types.h>
0014 #include <linux/dcache.h>
0015 #include <linux/err.h>
0016 #include <linux/fs.h>
0017 #include <linux/init.h>
0018 #include <linux/kernel.h>
0019 #include <linux/limits.h>
0020 #include <linux/list.h>
0021 #include <linux/lsm_hooks.h>
0022 #include <linux/mount.h>
0023 #include <linux/namei.h>
0024 #include <linux/path.h>
0025 #include <linux/rcupdate.h>
0026 #include <linux/spinlock.h>
0027 #include <linux/stat.h>
0028 #include <linux/types.h>
0029 #include <linux/wait_bit.h>
0030 #include <linux/workqueue.h>
0031 #include <uapi/linux/landlock.h>
0032 
0033 #include "common.h"
0034 #include "cred.h"
0035 #include "fs.h"
0036 #include "limits.h"
0037 #include "object.h"
0038 #include "ruleset.h"
0039 #include "setup.h"
0040 
0041 /* Underlying object management */
0042 
0043 static void release_inode(struct landlock_object *const object)
0044     __releases(object->lock)
0045 {
0046     struct inode *const inode = object->underobj;
0047     struct super_block *sb;
0048 
0049     if (!inode) {
0050         spin_unlock(&object->lock);
0051         return;
0052     }
0053 
0054     /*
0055      * Protects against concurrent use by hook_sb_delete() of the reference
0056      * to the underlying inode.
0057      */
0058     object->underobj = NULL;
0059     /*
0060      * Makes sure that if the filesystem is concurrently unmounted,
0061      * hook_sb_delete() will wait for us to finish iput().
0062      */
0063     sb = inode->i_sb;
0064     atomic_long_inc(&landlock_superblock(sb)->inode_refs);
0065     spin_unlock(&object->lock);
0066     /*
0067      * Because object->underobj was not NULL, hook_sb_delete() and
0068      * get_inode_object() guarantee that it is safe to reset
0069      * landlock_inode(inode)->object while it is not NULL.  It is therefore
0070      * not necessary to lock inode->i_lock.
0071      */
0072     rcu_assign_pointer(landlock_inode(inode)->object, NULL);
0073     /*
0074      * Now, new rules can safely be tied to @inode with get_inode_object().
0075      */
0076 
0077     iput(inode);
0078     if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
0079         wake_up_var(&landlock_superblock(sb)->inode_refs);
0080 }
0081 
0082 static const struct landlock_object_underops landlock_fs_underops = {
0083     .release = release_inode
0084 };
0085 
0086 /* Ruleset management */
0087 
0088 static struct landlock_object *get_inode_object(struct inode *const inode)
0089 {
0090     struct landlock_object *object, *new_object;
0091     struct landlock_inode_security *inode_sec = landlock_inode(inode);
0092 
0093     rcu_read_lock();
0094 retry:
0095     object = rcu_dereference(inode_sec->object);
0096     if (object) {
0097         if (likely(refcount_inc_not_zero(&object->usage))) {
0098             rcu_read_unlock();
0099             return object;
0100         }
0101         /*
0102          * We are racing with release_inode(), the object is going
0103          * away.  Wait for release_inode(), then retry.
0104          */
0105         spin_lock(&object->lock);
0106         spin_unlock(&object->lock);
0107         goto retry;
0108     }
0109     rcu_read_unlock();
0110 
0111     /*
0112      * If there is no object tied to @inode, then create a new one (without
0113      * holding any locks).
0114      */
0115     new_object = landlock_create_object(&landlock_fs_underops, inode);
0116     if (IS_ERR(new_object))
0117         return new_object;
0118 
0119     /*
0120      * Protects against concurrent calls to get_inode_object() or
0121      * hook_sb_delete().
0122      */
0123     spin_lock(&inode->i_lock);
0124     if (unlikely(rcu_access_pointer(inode_sec->object))) {
0125         /* Someone else just created the object, bail out and retry. */
0126         spin_unlock(&inode->i_lock);
0127         kfree(new_object);
0128 
0129         rcu_read_lock();
0130         goto retry;
0131     }
0132 
0133     /*
0134      * @inode will be released by hook_sb_delete() on its superblock
0135      * shutdown, or by release_inode() when no more ruleset references the
0136      * related object.
0137      */
0138     ihold(inode);
0139     rcu_assign_pointer(inode_sec->object, new_object);
0140     spin_unlock(&inode->i_lock);
0141     return new_object;
0142 }
0143 
0144 /* All access rights that can be tied to files. */
0145 /* clang-format off */
0146 #define ACCESS_FILE ( \
0147     LANDLOCK_ACCESS_FS_EXECUTE | \
0148     LANDLOCK_ACCESS_FS_WRITE_FILE | \
0149     LANDLOCK_ACCESS_FS_READ_FILE)
0150 /* clang-format on */
0151 
0152 /*
0153  * All access rights that are denied by default whether they are handled or not
0154  * by a ruleset/layer.  This must be ORed with all ruleset->fs_access_masks[]
0155  * entries when we need to get the absolute handled access masks.
0156  */
0157 /* clang-format off */
0158 #define ACCESS_INITIALLY_DENIED ( \
0159     LANDLOCK_ACCESS_FS_REFER)
0160 /* clang-format on */
0161 
0162 /*
0163  * @path: Should have been checked by get_path_from_fd().
0164  */
0165 int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
0166                 const struct path *const path,
0167                 access_mask_t access_rights)
0168 {
0169     int err;
0170     struct landlock_object *object;
0171 
0172     /* Files only get access rights that make sense. */
0173     if (!d_is_dir(path->dentry) &&
0174         (access_rights | ACCESS_FILE) != ACCESS_FILE)
0175         return -EINVAL;
0176     if (WARN_ON_ONCE(ruleset->num_layers != 1))
0177         return -EINVAL;
0178 
0179     /* Transforms relative access rights to absolute ones. */
0180     access_rights |=
0181         LANDLOCK_MASK_ACCESS_FS &
0182         ~(ruleset->fs_access_masks[0] | ACCESS_INITIALLY_DENIED);
0183     object = get_inode_object(d_backing_inode(path->dentry));
0184     if (IS_ERR(object))
0185         return PTR_ERR(object);
0186     mutex_lock(&ruleset->lock);
0187     err = landlock_insert_rule(ruleset, object, access_rights);
0188     mutex_unlock(&ruleset->lock);
0189     /*
0190      * No need to check for an error because landlock_insert_rule()
0191      * increments the refcount for the new object if needed.
0192      */
0193     landlock_put_object(object);
0194     return err;
0195 }
0196 
0197 /* Access-control management */
0198 
0199 /*
0200  * The lifetime of the returned rule is tied to @domain.
0201  *
0202  * Returns NULL if no rule is found or if @dentry is negative.
0203  */
0204 static inline const struct landlock_rule *
0205 find_rule(const struct landlock_ruleset *const domain,
0206       const struct dentry *const dentry)
0207 {
0208     const struct landlock_rule *rule;
0209     const struct inode *inode;
0210 
0211     /* Ignores nonexistent leafs. */
0212     if (d_is_negative(dentry))
0213         return NULL;
0214 
0215     inode = d_backing_inode(dentry);
0216     rcu_read_lock();
0217     rule = landlock_find_rule(
0218         domain, rcu_dereference(landlock_inode(inode)->object));
0219     rcu_read_unlock();
0220     return rule;
0221 }
0222 
0223 /*
0224  * @layer_masks is read and may be updated according to the access request and
0225  * the matching rule.
0226  *
0227  * Returns true if the request is allowed (i.e. relevant layer masks for the
0228  * request are empty).
0229  */
0230 static inline bool
0231 unmask_layers(const struct landlock_rule *const rule,
0232           const access_mask_t access_request,
0233           layer_mask_t (*const layer_masks)[LANDLOCK_NUM_ACCESS_FS])
0234 {
0235     size_t layer_level;
0236 
0237     if (!access_request || !layer_masks)
0238         return true;
0239     if (!rule)
0240         return false;
0241 
0242     /*
0243      * An access is granted if, for each policy layer, at least one rule
0244      * encountered on the pathwalk grants the requested access,
0245      * regardless of its position in the layer stack.  We must then check
0246      * the remaining layers for each inode, from the first added layer to
0247      * the last one.  When there is multiple requested accesses, for each
0248      * policy layer, the full set of requested accesses may not be granted
0249      * by only one rule, but by the union (binary OR) of multiple rules.
0250      * E.g. /a/b <execute> + /a <read> => /a/b <execute + read>
0251      */
0252     for (layer_level = 0; layer_level < rule->num_layers; layer_level++) {
0253         const struct landlock_layer *const layer =
0254             &rule->layers[layer_level];
0255         const layer_mask_t layer_bit = BIT_ULL(layer->level - 1);
0256         const unsigned long access_req = access_request;
0257         unsigned long access_bit;
0258         bool is_empty;
0259 
0260         /*
0261          * Records in @layer_masks which layer grants access to each
0262          * requested access.
0263          */
0264         is_empty = true;
0265         for_each_set_bit(access_bit, &access_req,
0266                  ARRAY_SIZE(*layer_masks)) {
0267             if (layer->access & BIT_ULL(access_bit))
0268                 (*layer_masks)[access_bit] &= ~layer_bit;
0269             is_empty = is_empty && !(*layer_masks)[access_bit];
0270         }
0271         if (is_empty)
0272             return true;
0273     }
0274     return false;
0275 }
0276 
0277 /*
0278  * Allows access to pseudo filesystems that will never be mountable (e.g.
0279  * sockfs, pipefs), but can still be reachable through
0280  * /proc/<pid>/fd/<file-descriptor>
0281  */
0282 static inline bool is_nouser_or_private(const struct dentry *dentry)
0283 {
0284     return (dentry->d_sb->s_flags & SB_NOUSER) ||
0285            (d_is_positive(dentry) &&
0286         unlikely(IS_PRIVATE(d_backing_inode(dentry))));
0287 }
0288 
0289 static inline access_mask_t
0290 get_handled_accesses(const struct landlock_ruleset *const domain)
0291 {
0292     access_mask_t access_dom = ACCESS_INITIALLY_DENIED;
0293     size_t layer_level;
0294 
0295     for (layer_level = 0; layer_level < domain->num_layers; layer_level++)
0296         access_dom |= domain->fs_access_masks[layer_level];
0297     return access_dom & LANDLOCK_MASK_ACCESS_FS;
0298 }
0299 
0300 static inline access_mask_t
0301 init_layer_masks(const struct landlock_ruleset *const domain,
0302          const access_mask_t access_request,
0303          layer_mask_t (*const layer_masks)[LANDLOCK_NUM_ACCESS_FS])
0304 {
0305     access_mask_t handled_accesses = 0;
0306     size_t layer_level;
0307 
0308     memset(layer_masks, 0, sizeof(*layer_masks));
0309     /* An empty access request can happen because of O_WRONLY | O_RDWR. */
0310     if (!access_request)
0311         return 0;
0312 
0313     /* Saves all handled accesses per layer. */
0314     for (layer_level = 0; layer_level < domain->num_layers; layer_level++) {
0315         const unsigned long access_req = access_request;
0316         unsigned long access_bit;
0317 
0318         for_each_set_bit(access_bit, &access_req,
0319                  ARRAY_SIZE(*layer_masks)) {
0320             /*
0321              * Artificially handles all initially denied by default
0322              * access rights.
0323              */
0324             if (BIT_ULL(access_bit) &
0325                 (domain->fs_access_masks[layer_level] |
0326                  ACCESS_INITIALLY_DENIED)) {
0327                 (*layer_masks)[access_bit] |=
0328                     BIT_ULL(layer_level);
0329                 handled_accesses |= BIT_ULL(access_bit);
0330             }
0331         }
0332     }
0333     return handled_accesses;
0334 }
0335 
0336 /*
0337  * Check that a destination file hierarchy has more restrictions than a source
0338  * file hierarchy.  This is only used for link and rename actions.
0339  *
0340  * @layer_masks_child2: Optional child masks.
0341  */
0342 static inline bool no_more_access(
0343     const layer_mask_t (*const layer_masks_parent1)[LANDLOCK_NUM_ACCESS_FS],
0344     const layer_mask_t (*const layer_masks_child1)[LANDLOCK_NUM_ACCESS_FS],
0345     const bool child1_is_directory,
0346     const layer_mask_t (*const layer_masks_parent2)[LANDLOCK_NUM_ACCESS_FS],
0347     const layer_mask_t (*const layer_masks_child2)[LANDLOCK_NUM_ACCESS_FS],
0348     const bool child2_is_directory)
0349 {
0350     unsigned long access_bit;
0351 
0352     for (access_bit = 0; access_bit < ARRAY_SIZE(*layer_masks_parent2);
0353          access_bit++) {
0354         /* Ignores accesses that only make sense for directories. */
0355         const bool is_file_access =
0356             !!(BIT_ULL(access_bit) & ACCESS_FILE);
0357 
0358         if (child1_is_directory || is_file_access) {
0359             /*
0360              * Checks if the destination restrictions are a
0361              * superset of the source ones (i.e. inherited access
0362              * rights without child exceptions):
0363              * restrictions(parent2) >= restrictions(child1)
0364              */
0365             if ((((*layer_masks_parent1)[access_bit] &
0366                   (*layer_masks_child1)[access_bit]) |
0367                  (*layer_masks_parent2)[access_bit]) !=
0368                 (*layer_masks_parent2)[access_bit])
0369                 return false;
0370         }
0371 
0372         if (!layer_masks_child2)
0373             continue;
0374         if (child2_is_directory || is_file_access) {
0375             /*
0376              * Checks inverted restrictions for RENAME_EXCHANGE:
0377              * restrictions(parent1) >= restrictions(child2)
0378              */
0379             if ((((*layer_masks_parent2)[access_bit] &
0380                   (*layer_masks_child2)[access_bit]) |
0381                  (*layer_masks_parent1)[access_bit]) !=
0382                 (*layer_masks_parent1)[access_bit])
0383                 return false;
0384         }
0385     }
0386     return true;
0387 }
0388 
0389 /*
0390  * Removes @layer_masks accesses that are not requested.
0391  *
0392  * Returns true if the request is allowed, false otherwise.
0393  */
0394 static inline bool
0395 scope_to_request(const access_mask_t access_request,
0396          layer_mask_t (*const layer_masks)[LANDLOCK_NUM_ACCESS_FS])
0397 {
0398     const unsigned long access_req = access_request;
0399     unsigned long access_bit;
0400 
0401     if (WARN_ON_ONCE(!layer_masks))
0402         return true;
0403 
0404     for_each_clear_bit(access_bit, &access_req, ARRAY_SIZE(*layer_masks))
0405         (*layer_masks)[access_bit] = 0;
0406     return !memchr_inv(layer_masks, 0, sizeof(*layer_masks));
0407 }
0408 
0409 /*
0410  * Returns true if there is at least one access right different than
0411  * LANDLOCK_ACCESS_FS_REFER.
0412  */
0413 static inline bool
0414 is_eacces(const layer_mask_t (*const layer_masks)[LANDLOCK_NUM_ACCESS_FS],
0415       const access_mask_t access_request)
0416 {
0417     unsigned long access_bit;
0418     /* LANDLOCK_ACCESS_FS_REFER alone must return -EXDEV. */
0419     const unsigned long access_check = access_request &
0420                        ~LANDLOCK_ACCESS_FS_REFER;
0421 
0422     if (!layer_masks)
0423         return false;
0424 
0425     for_each_set_bit(access_bit, &access_check, ARRAY_SIZE(*layer_masks)) {
0426         if ((*layer_masks)[access_bit])
0427             return true;
0428     }
0429     return false;
0430 }
0431 
0432 /**
0433  * check_access_path_dual - Check accesses for requests with a common path
0434  *
0435  * @domain: Domain to check against.
0436  * @path: File hierarchy to walk through.
0437  * @access_request_parent1: Accesses to check, once @layer_masks_parent1 is
0438  *     equal to @layer_masks_parent2 (if any).  This is tied to the unique
0439  *     requested path for most actions, or the source in case of a refer action
0440  *     (i.e. rename or link), or the source and destination in case of
0441  *     RENAME_EXCHANGE.
0442  * @layer_masks_parent1: Pointer to a matrix of layer masks per access
0443  *     masks, identifying the layers that forbid a specific access.  Bits from
0444  *     this matrix can be unset according to the @path walk.  An empty matrix
0445  *     means that @domain allows all possible Landlock accesses (i.e. not only
0446  *     those identified by @access_request_parent1).  This matrix can
0447  *     initially refer to domain layer masks and, when the accesses for the
0448  *     destination and source are the same, to requested layer masks.
0449  * @dentry_child1: Dentry to the initial child of the parent1 path.  This
0450  *     pointer must be NULL for non-refer actions (i.e. not link nor rename).
0451  * @access_request_parent2: Similar to @access_request_parent1 but for a
0452  *     request involving a source and a destination.  This refers to the
0453  *     destination, except in case of RENAME_EXCHANGE where it also refers to
0454  *     the source.  Must be set to 0 when using a simple path request.
0455  * @layer_masks_parent2: Similar to @layer_masks_parent1 but for a refer
0456  *     action.  This must be NULL otherwise.
0457  * @dentry_child2: Dentry to the initial child of the parent2 path.  This
0458  *     pointer is only set for RENAME_EXCHANGE actions and must be NULL
0459  *     otherwise.
0460  *
0461  * This helper first checks that the destination has a superset of restrictions
0462  * compared to the source (if any) for a common path.  Because of
0463  * RENAME_EXCHANGE actions, source and destinations may be swapped.  It then
0464  * checks that the collected accesses and the remaining ones are enough to
0465  * allow the request.
0466  *
0467  * Returns:
0468  * - 0 if the access request is granted;
0469  * - -EACCES if it is denied because of access right other than
0470  *   LANDLOCK_ACCESS_FS_REFER;
0471  * - -EXDEV if the renaming or linking would be a privileged escalation
0472  *   (according to each layered policies), or if LANDLOCK_ACCESS_FS_REFER is
0473  *   not allowed by the source or the destination.
0474  */
0475 static int check_access_path_dual(
0476     const struct landlock_ruleset *const domain,
0477     const struct path *const path,
0478     const access_mask_t access_request_parent1,
0479     layer_mask_t (*const layer_masks_parent1)[LANDLOCK_NUM_ACCESS_FS],
0480     const struct dentry *const dentry_child1,
0481     const access_mask_t access_request_parent2,
0482     layer_mask_t (*const layer_masks_parent2)[LANDLOCK_NUM_ACCESS_FS],
0483     const struct dentry *const dentry_child2)
0484 {
0485     bool allowed_parent1 = false, allowed_parent2 = false, is_dom_check,
0486          child1_is_directory = true, child2_is_directory = true;
0487     struct path walker_path;
0488     access_mask_t access_masked_parent1, access_masked_parent2;
0489     layer_mask_t _layer_masks_child1[LANDLOCK_NUM_ACCESS_FS],
0490         _layer_masks_child2[LANDLOCK_NUM_ACCESS_FS];
0491     layer_mask_t(*layer_masks_child1)[LANDLOCK_NUM_ACCESS_FS] = NULL,
0492     (*layer_masks_child2)[LANDLOCK_NUM_ACCESS_FS] = NULL;
0493 
0494     if (!access_request_parent1 && !access_request_parent2)
0495         return 0;
0496     if (WARN_ON_ONCE(!domain || !path))
0497         return 0;
0498     if (is_nouser_or_private(path->dentry))
0499         return 0;
0500     if (WARN_ON_ONCE(domain->num_layers < 1 || !layer_masks_parent1))
0501         return -EACCES;
0502 
0503     if (unlikely(layer_masks_parent2)) {
0504         if (WARN_ON_ONCE(!dentry_child1))
0505             return -EACCES;
0506         /*
0507          * For a double request, first check for potential privilege
0508          * escalation by looking at domain handled accesses (which are
0509          * a superset of the meaningful requested accesses).
0510          */
0511         access_masked_parent1 = access_masked_parent2 =
0512             get_handled_accesses(domain);
0513         is_dom_check = true;
0514     } else {
0515         if (WARN_ON_ONCE(dentry_child1 || dentry_child2))
0516             return -EACCES;
0517         /* For a simple request, only check for requested accesses. */
0518         access_masked_parent1 = access_request_parent1;
0519         access_masked_parent2 = access_request_parent2;
0520         is_dom_check = false;
0521     }
0522 
0523     if (unlikely(dentry_child1)) {
0524         unmask_layers(find_rule(domain, dentry_child1),
0525                   init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
0526                            &_layer_masks_child1),
0527                   &_layer_masks_child1);
0528         layer_masks_child1 = &_layer_masks_child1;
0529         child1_is_directory = d_is_dir(dentry_child1);
0530     }
0531     if (unlikely(dentry_child2)) {
0532         unmask_layers(find_rule(domain, dentry_child2),
0533                   init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
0534                            &_layer_masks_child2),
0535                   &_layer_masks_child2);
0536         layer_masks_child2 = &_layer_masks_child2;
0537         child2_is_directory = d_is_dir(dentry_child2);
0538     }
0539 
0540     walker_path = *path;
0541     path_get(&walker_path);
0542     /*
0543      * We need to walk through all the hierarchy to not miss any relevant
0544      * restriction.
0545      */
0546     while (true) {
0547         struct dentry *parent_dentry;
0548         const struct landlock_rule *rule;
0549 
0550         /*
0551          * If at least all accesses allowed on the destination are
0552          * already allowed on the source, respectively if there is at
0553          * least as much as restrictions on the destination than on the
0554          * source, then we can safely refer files from the source to
0555          * the destination without risking a privilege escalation.
0556          * This also applies in the case of RENAME_EXCHANGE, which
0557          * implies checks on both direction.  This is crucial for
0558          * standalone multilayered security policies.  Furthermore,
0559          * this helps avoid policy writers to shoot themselves in the
0560          * foot.
0561          */
0562         if (unlikely(is_dom_check &&
0563                  no_more_access(
0564                      layer_masks_parent1, layer_masks_child1,
0565                      child1_is_directory, layer_masks_parent2,
0566                      layer_masks_child2,
0567                      child2_is_directory))) {
0568             allowed_parent1 = scope_to_request(
0569                 access_request_parent1, layer_masks_parent1);
0570             allowed_parent2 = scope_to_request(
0571                 access_request_parent2, layer_masks_parent2);
0572 
0573             /* Stops when all accesses are granted. */
0574             if (allowed_parent1 && allowed_parent2)
0575                 break;
0576 
0577             /*
0578              * Now, downgrades the remaining checks from domain
0579              * handled accesses to requested accesses.
0580              */
0581             is_dom_check = false;
0582             access_masked_parent1 = access_request_parent1;
0583             access_masked_parent2 = access_request_parent2;
0584         }
0585 
0586         rule = find_rule(domain, walker_path.dentry);
0587         allowed_parent1 = unmask_layers(rule, access_masked_parent1,
0588                         layer_masks_parent1);
0589         allowed_parent2 = unmask_layers(rule, access_masked_parent2,
0590                         layer_masks_parent2);
0591 
0592         /* Stops when a rule from each layer grants access. */
0593         if (allowed_parent1 && allowed_parent2)
0594             break;
0595 
0596 jump_up:
0597         if (walker_path.dentry == walker_path.mnt->mnt_root) {
0598             if (follow_up(&walker_path)) {
0599                 /* Ignores hidden mount points. */
0600                 goto jump_up;
0601             } else {
0602                 /*
0603                  * Stops at the real root.  Denies access
0604                  * because not all layers have granted access.
0605                  */
0606                 break;
0607             }
0608         }
0609         if (unlikely(IS_ROOT(walker_path.dentry))) {
0610             /*
0611              * Stops at disconnected root directories.  Only allows
0612              * access to internal filesystems (e.g. nsfs, which is
0613              * reachable through /proc/<pid>/ns/<namespace>).
0614              */
0615             allowed_parent1 = allowed_parent2 =
0616                 !!(walker_path.mnt->mnt_flags & MNT_INTERNAL);
0617             break;
0618         }
0619         parent_dentry = dget_parent(walker_path.dentry);
0620         dput(walker_path.dentry);
0621         walker_path.dentry = parent_dentry;
0622     }
0623     path_put(&walker_path);
0624 
0625     if (allowed_parent1 && allowed_parent2)
0626         return 0;
0627 
0628     /*
0629      * This prioritizes EACCES over EXDEV for all actions, including
0630      * renames with RENAME_EXCHANGE.
0631      */
0632     if (likely(is_eacces(layer_masks_parent1, access_request_parent1) ||
0633            is_eacces(layer_masks_parent2, access_request_parent2)))
0634         return -EACCES;
0635 
0636     /*
0637      * Gracefully forbids reparenting if the destination directory
0638      * hierarchy is not a superset of restrictions of the source directory
0639      * hierarchy, or if LANDLOCK_ACCESS_FS_REFER is not allowed by the
0640      * source or the destination.
0641      */
0642     return -EXDEV;
0643 }
0644 
0645 static inline int check_access_path(const struct landlock_ruleset *const domain,
0646                     const struct path *const path,
0647                     access_mask_t access_request)
0648 {
0649     layer_mask_t layer_masks[LANDLOCK_NUM_ACCESS_FS] = {};
0650 
0651     access_request = init_layer_masks(domain, access_request, &layer_masks);
0652     return check_access_path_dual(domain, path, access_request,
0653                       &layer_masks, NULL, 0, NULL, NULL);
0654 }
0655 
0656 static inline int current_check_access_path(const struct path *const path,
0657                         const access_mask_t access_request)
0658 {
0659     const struct landlock_ruleset *const dom =
0660         landlock_get_current_domain();
0661 
0662     if (!dom)
0663         return 0;
0664     return check_access_path(dom, path, access_request);
0665 }
0666 
0667 static inline access_mask_t get_mode_access(const umode_t mode)
0668 {
0669     switch (mode & S_IFMT) {
0670     case S_IFLNK:
0671         return LANDLOCK_ACCESS_FS_MAKE_SYM;
0672     case 0:
0673         /* A zero mode translates to S_IFREG. */
0674     case S_IFREG:
0675         return LANDLOCK_ACCESS_FS_MAKE_REG;
0676     case S_IFDIR:
0677         return LANDLOCK_ACCESS_FS_MAKE_DIR;
0678     case S_IFCHR:
0679         return LANDLOCK_ACCESS_FS_MAKE_CHAR;
0680     case S_IFBLK:
0681         return LANDLOCK_ACCESS_FS_MAKE_BLOCK;
0682     case S_IFIFO:
0683         return LANDLOCK_ACCESS_FS_MAKE_FIFO;
0684     case S_IFSOCK:
0685         return LANDLOCK_ACCESS_FS_MAKE_SOCK;
0686     default:
0687         WARN_ON_ONCE(1);
0688         return 0;
0689     }
0690 }
0691 
0692 static inline access_mask_t maybe_remove(const struct dentry *const dentry)
0693 {
0694     if (d_is_negative(dentry))
0695         return 0;
0696     return d_is_dir(dentry) ? LANDLOCK_ACCESS_FS_REMOVE_DIR :
0697                   LANDLOCK_ACCESS_FS_REMOVE_FILE;
0698 }
0699 
0700 /**
0701  * collect_domain_accesses - Walk through a file path and collect accesses
0702  *
0703  * @domain: Domain to check against.
0704  * @mnt_root: Last directory to check.
0705  * @dir: Directory to start the walk from.
0706  * @layer_masks_dom: Where to store the collected accesses.
0707  *
0708  * This helper is useful to begin a path walk from the @dir directory to a
0709  * @mnt_root directory used as a mount point.  This mount point is the common
0710  * ancestor between the source and the destination of a renamed and linked
0711  * file.  While walking from @dir to @mnt_root, we record all the domain's
0712  * allowed accesses in @layer_masks_dom.
0713  *
0714  * This is similar to check_access_path_dual() but much simpler because it only
0715  * handles walking on the same mount point and only check one set of accesses.
0716  *
0717  * Returns:
0718  * - true if all the domain access rights are allowed for @dir;
0719  * - false if the walk reached @mnt_root.
0720  */
0721 static bool collect_domain_accesses(
0722     const struct landlock_ruleset *const domain,
0723     const struct dentry *const mnt_root, struct dentry *dir,
0724     layer_mask_t (*const layer_masks_dom)[LANDLOCK_NUM_ACCESS_FS])
0725 {
0726     unsigned long access_dom;
0727     bool ret = false;
0728 
0729     if (WARN_ON_ONCE(!domain || !mnt_root || !dir || !layer_masks_dom))
0730         return true;
0731     if (is_nouser_or_private(dir))
0732         return true;
0733 
0734     access_dom = init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
0735                       layer_masks_dom);
0736 
0737     dget(dir);
0738     while (true) {
0739         struct dentry *parent_dentry;
0740 
0741         /* Gets all layers allowing all domain accesses. */
0742         if (unmask_layers(find_rule(domain, dir), access_dom,
0743                   layer_masks_dom)) {
0744             /*
0745              * Stops when all handled accesses are allowed by at
0746              * least one rule in each layer.
0747              */
0748             ret = true;
0749             break;
0750         }
0751 
0752         /* We should not reach a root other than @mnt_root. */
0753         if (dir == mnt_root || WARN_ON_ONCE(IS_ROOT(dir)))
0754             break;
0755 
0756         parent_dentry = dget_parent(dir);
0757         dput(dir);
0758         dir = parent_dentry;
0759     }
0760     dput(dir);
0761     return ret;
0762 }
0763 
0764 /**
0765  * current_check_refer_path - Check if a rename or link action is allowed
0766  *
0767  * @old_dentry: File or directory requested to be moved or linked.
0768  * @new_dir: Destination parent directory.
0769  * @new_dentry: Destination file or directory.
0770  * @removable: Sets to true if it is a rename operation.
0771  * @exchange: Sets to true if it is a rename operation with RENAME_EXCHANGE.
0772  *
0773  * Because of its unprivileged constraints, Landlock relies on file hierarchies
0774  * (and not only inodes) to tie access rights to files.  Being able to link or
0775  * rename a file hierarchy brings some challenges.  Indeed, moving or linking a
0776  * file (i.e. creating a new reference to an inode) can have an impact on the
0777  * actions allowed for a set of files if it would change its parent directory
0778  * (i.e. reparenting).
0779  *
0780  * To avoid trivial access right bypasses, Landlock first checks if the file or
0781  * directory requested to be moved would gain new access rights inherited from
0782  * its new hierarchy.  Before returning any error, Landlock then checks that
0783  * the parent source hierarchy and the destination hierarchy would allow the
0784  * link or rename action.  If it is not the case, an error with EACCES is
0785  * returned to inform user space that there is no way to remove or create the
0786  * requested source file type.  If it should be allowed but the new inherited
0787  * access rights would be greater than the source access rights, then the
0788  * kernel returns an error with EXDEV.  Prioritizing EACCES over EXDEV enables
0789  * user space to abort the whole operation if there is no way to do it, or to
0790  * manually copy the source to the destination if this remains allowed, e.g.
0791  * because file creation is allowed on the destination directory but not direct
0792  * linking.
0793  *
0794  * To achieve this goal, the kernel needs to compare two file hierarchies: the
0795  * one identifying the source file or directory (including itself), and the
0796  * destination one.  This can be seen as a multilayer partial ordering problem.
0797  * The kernel walks through these paths and collects in a matrix the access
0798  * rights that are denied per layer.  These matrices are then compared to see
0799  * if the destination one has more (or the same) restrictions as the source
0800  * one.  If this is the case, the requested action will not return EXDEV, which
0801  * doesn't mean the action is allowed.  The parent hierarchy of the source
0802  * (i.e. parent directory), and the destination hierarchy must also be checked
0803  * to verify that they explicitly allow such action (i.e.  referencing,
0804  * creation and potentially removal rights).  The kernel implementation is then
0805  * required to rely on potentially four matrices of access rights: one for the
0806  * source file or directory (i.e. the child), a potentially other one for the
0807  * other source/destination (in case of RENAME_EXCHANGE), one for the source
0808  * parent hierarchy and a last one for the destination hierarchy.  These
0809  * ephemeral matrices take some space on the stack, which limits the number of
0810  * layers to a deemed reasonable number: 16.
0811  *
0812  * Returns:
0813  * - 0 if access is allowed;
0814  * - -EXDEV if @old_dentry would inherit new access rights from @new_dir;
0815  * - -EACCES if file removal or creation is denied.
0816  */
0817 static int current_check_refer_path(struct dentry *const old_dentry,
0818                     const struct path *const new_dir,
0819                     struct dentry *const new_dentry,
0820                     const bool removable, const bool exchange)
0821 {
0822     const struct landlock_ruleset *const dom =
0823         landlock_get_current_domain();
0824     bool allow_parent1, allow_parent2;
0825     access_mask_t access_request_parent1, access_request_parent2;
0826     struct path mnt_dir;
0827     layer_mask_t layer_masks_parent1[LANDLOCK_NUM_ACCESS_FS],
0828         layer_masks_parent2[LANDLOCK_NUM_ACCESS_FS];
0829 
0830     if (!dom)
0831         return 0;
0832     if (WARN_ON_ONCE(dom->num_layers < 1))
0833         return -EACCES;
0834     if (unlikely(d_is_negative(old_dentry)))
0835         return -ENOENT;
0836     if (exchange) {
0837         if (unlikely(d_is_negative(new_dentry)))
0838             return -ENOENT;
0839         access_request_parent1 =
0840             get_mode_access(d_backing_inode(new_dentry)->i_mode);
0841     } else {
0842         access_request_parent1 = 0;
0843     }
0844     access_request_parent2 =
0845         get_mode_access(d_backing_inode(old_dentry)->i_mode);
0846     if (removable) {
0847         access_request_parent1 |= maybe_remove(old_dentry);
0848         access_request_parent2 |= maybe_remove(new_dentry);
0849     }
0850 
0851     /* The mount points are the same for old and new paths, cf. EXDEV. */
0852     if (old_dentry->d_parent == new_dir->dentry) {
0853         /*
0854          * The LANDLOCK_ACCESS_FS_REFER access right is not required
0855          * for same-directory referer (i.e. no reparenting).
0856          */
0857         access_request_parent1 = init_layer_masks(
0858             dom, access_request_parent1 | access_request_parent2,
0859             &layer_masks_parent1);
0860         return check_access_path_dual(dom, new_dir,
0861                           access_request_parent1,
0862                           &layer_masks_parent1, NULL, 0,
0863                           NULL, NULL);
0864     }
0865 
0866     access_request_parent1 |= LANDLOCK_ACCESS_FS_REFER;
0867     access_request_parent2 |= LANDLOCK_ACCESS_FS_REFER;
0868 
0869     /* Saves the common mount point. */
0870     mnt_dir.mnt = new_dir->mnt;
0871     mnt_dir.dentry = new_dir->mnt->mnt_root;
0872 
0873     /* new_dir->dentry is equal to new_dentry->d_parent */
0874     allow_parent1 = collect_domain_accesses(dom, mnt_dir.dentry,
0875                         old_dentry->d_parent,
0876                         &layer_masks_parent1);
0877     allow_parent2 = collect_domain_accesses(
0878         dom, mnt_dir.dentry, new_dir->dentry, &layer_masks_parent2);
0879 
0880     if (allow_parent1 && allow_parent2)
0881         return 0;
0882 
0883     /*
0884      * To be able to compare source and destination domain access rights,
0885      * take into account the @old_dentry access rights aggregated with its
0886      * parent access rights.  This will be useful to compare with the
0887      * destination parent access rights.
0888      */
0889     return check_access_path_dual(dom, &mnt_dir, access_request_parent1,
0890                       &layer_masks_parent1, old_dentry,
0891                       access_request_parent2,
0892                       &layer_masks_parent2,
0893                       exchange ? new_dentry : NULL);
0894 }
0895 
0896 /* Inode hooks */
0897 
0898 static void hook_inode_free_security(struct inode *const inode)
0899 {
0900     /*
0901      * All inodes must already have been untied from their object by
0902      * release_inode() or hook_sb_delete().
0903      */
0904     WARN_ON_ONCE(landlock_inode(inode)->object);
0905 }
0906 
0907 /* Super-block hooks */
0908 
0909 /*
0910  * Release the inodes used in a security policy.
0911  *
0912  * Cf. fsnotify_unmount_inodes() and invalidate_inodes()
0913  */
0914 static void hook_sb_delete(struct super_block *const sb)
0915 {
0916     struct inode *inode, *prev_inode = NULL;
0917 
0918     if (!landlock_initialized)
0919         return;
0920 
0921     spin_lock(&sb->s_inode_list_lock);
0922     list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
0923         struct landlock_object *object;
0924 
0925         /* Only handles referenced inodes. */
0926         if (!atomic_read(&inode->i_count))
0927             continue;
0928 
0929         /*
0930          * Protects against concurrent modification of inode (e.g.
0931          * from get_inode_object()).
0932          */
0933         spin_lock(&inode->i_lock);
0934         /*
0935          * Checks I_FREEING and I_WILL_FREE  to protect against a race
0936          * condition when release_inode() just called iput(), which
0937          * could lead to a NULL dereference of inode->security or a
0938          * second call to iput() for the same Landlock object.  Also
0939          * checks I_NEW because such inode cannot be tied to an object.
0940          */
0941         if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
0942             spin_unlock(&inode->i_lock);
0943             continue;
0944         }
0945 
0946         rcu_read_lock();
0947         object = rcu_dereference(landlock_inode(inode)->object);
0948         if (!object) {
0949             rcu_read_unlock();
0950             spin_unlock(&inode->i_lock);
0951             continue;
0952         }
0953         /* Keeps a reference to this inode until the next loop walk. */
0954         __iget(inode);
0955         spin_unlock(&inode->i_lock);
0956 
0957         /*
0958          * If there is no concurrent release_inode() ongoing, then we
0959          * are in charge of calling iput() on this inode, otherwise we
0960          * will just wait for it to finish.
0961          */
0962         spin_lock(&object->lock);
0963         if (object->underobj == inode) {
0964             object->underobj = NULL;
0965             spin_unlock(&object->lock);
0966             rcu_read_unlock();
0967 
0968             /*
0969              * Because object->underobj was not NULL,
0970              * release_inode() and get_inode_object() guarantee
0971              * that it is safe to reset
0972              * landlock_inode(inode)->object while it is not NULL.
0973              * It is therefore not necessary to lock inode->i_lock.
0974              */
0975             rcu_assign_pointer(landlock_inode(inode)->object, NULL);
0976             /*
0977              * At this point, we own the ihold() reference that was
0978              * originally set up by get_inode_object() and the
0979              * __iget() reference that we just set in this loop
0980              * walk.  Therefore the following call to iput() will
0981              * not sleep nor drop the inode because there is now at
0982              * least two references to it.
0983              */
0984             iput(inode);
0985         } else {
0986             spin_unlock(&object->lock);
0987             rcu_read_unlock();
0988         }
0989 
0990         if (prev_inode) {
0991             /*
0992              * At this point, we still own the __iget() reference
0993              * that we just set in this loop walk.  Therefore we
0994              * can drop the list lock and know that the inode won't
0995              * disappear from under us until the next loop walk.
0996              */
0997             spin_unlock(&sb->s_inode_list_lock);
0998             /*
0999              * We can now actually put the inode reference from the
1000              * previous loop walk, which is not needed anymore.
1001              */
1002             iput(prev_inode);
1003             cond_resched();
1004             spin_lock(&sb->s_inode_list_lock);
1005         }
1006         prev_inode = inode;
1007     }
1008     spin_unlock(&sb->s_inode_list_lock);
1009 
1010     /* Puts the inode reference from the last loop walk, if any. */
1011     if (prev_inode)
1012         iput(prev_inode);
1013     /* Waits for pending iput() in release_inode(). */
1014     wait_var_event(&landlock_superblock(sb)->inode_refs,
1015                !atomic_long_read(&landlock_superblock(sb)->inode_refs));
1016 }
1017 
1018 /*
1019  * Because a Landlock security policy is defined according to the filesystem
1020  * topology (i.e. the mount namespace), changing it may grant access to files
1021  * not previously allowed.
1022  *
1023  * To make it simple, deny any filesystem topology modification by landlocked
1024  * processes.  Non-landlocked processes may still change the namespace of a
1025  * landlocked process, but this kind of threat must be handled by a system-wide
1026  * access-control security policy.
1027  *
1028  * This could be lifted in the future if Landlock can safely handle mount
1029  * namespace updates requested by a landlocked process.  Indeed, we could
1030  * update the current domain (which is currently read-only) by taking into
1031  * account the accesses of the source and the destination of a new mount point.
1032  * However, it would also require to make all the child domains dynamically
1033  * inherit these new constraints.  Anyway, for backward compatibility reasons,
1034  * a dedicated user space option would be required (e.g. as a ruleset flag).
1035  */
1036 static int hook_sb_mount(const char *const dev_name,
1037              const struct path *const path, const char *const type,
1038              const unsigned long flags, void *const data)
1039 {
1040     if (!landlock_get_current_domain())
1041         return 0;
1042     return -EPERM;
1043 }
1044 
1045 static int hook_move_mount(const struct path *const from_path,
1046                const struct path *const to_path)
1047 {
1048     if (!landlock_get_current_domain())
1049         return 0;
1050     return -EPERM;
1051 }
1052 
1053 /*
1054  * Removing a mount point may reveal a previously hidden file hierarchy, which
1055  * may then grant access to files, which may have previously been forbidden.
1056  */
1057 static int hook_sb_umount(struct vfsmount *const mnt, const int flags)
1058 {
1059     if (!landlock_get_current_domain())
1060         return 0;
1061     return -EPERM;
1062 }
1063 
1064 static int hook_sb_remount(struct super_block *const sb, void *const mnt_opts)
1065 {
1066     if (!landlock_get_current_domain())
1067         return 0;
1068     return -EPERM;
1069 }
1070 
1071 /*
1072  * pivot_root(2), like mount(2), changes the current mount namespace.  It must
1073  * then be forbidden for a landlocked process.
1074  *
1075  * However, chroot(2) may be allowed because it only changes the relative root
1076  * directory of the current process.  Moreover, it can be used to restrict the
1077  * view of the filesystem.
1078  */
1079 static int hook_sb_pivotroot(const struct path *const old_path,
1080                  const struct path *const new_path)
1081 {
1082     if (!landlock_get_current_domain())
1083         return 0;
1084     return -EPERM;
1085 }
1086 
1087 /* Path hooks */
1088 
1089 static int hook_path_link(struct dentry *const old_dentry,
1090               const struct path *const new_dir,
1091               struct dentry *const new_dentry)
1092 {
1093     return current_check_refer_path(old_dentry, new_dir, new_dentry, false,
1094                     false);
1095 }
1096 
1097 static int hook_path_rename(const struct path *const old_dir,
1098                 struct dentry *const old_dentry,
1099                 const struct path *const new_dir,
1100                 struct dentry *const new_dentry,
1101                 const unsigned int flags)
1102 {
1103     /* old_dir refers to old_dentry->d_parent and new_dir->mnt */
1104     return current_check_refer_path(old_dentry, new_dir, new_dentry, true,
1105                     !!(flags & RENAME_EXCHANGE));
1106 }
1107 
1108 static int hook_path_mkdir(const struct path *const dir,
1109                struct dentry *const dentry, const umode_t mode)
1110 {
1111     return current_check_access_path(dir, LANDLOCK_ACCESS_FS_MAKE_DIR);
1112 }
1113 
1114 static int hook_path_mknod(const struct path *const dir,
1115                struct dentry *const dentry, const umode_t mode,
1116                const unsigned int dev)
1117 {
1118     const struct landlock_ruleset *const dom =
1119         landlock_get_current_domain();
1120 
1121     if (!dom)
1122         return 0;
1123     return check_access_path(dom, dir, get_mode_access(mode));
1124 }
1125 
1126 static int hook_path_symlink(const struct path *const dir,
1127                  struct dentry *const dentry,
1128                  const char *const old_name)
1129 {
1130     return current_check_access_path(dir, LANDLOCK_ACCESS_FS_MAKE_SYM);
1131 }
1132 
1133 static int hook_path_unlink(const struct path *const dir,
1134                 struct dentry *const dentry)
1135 {
1136     return current_check_access_path(dir, LANDLOCK_ACCESS_FS_REMOVE_FILE);
1137 }
1138 
1139 static int hook_path_rmdir(const struct path *const dir,
1140                struct dentry *const dentry)
1141 {
1142     return current_check_access_path(dir, LANDLOCK_ACCESS_FS_REMOVE_DIR);
1143 }
1144 
1145 /* File hooks */
1146 
1147 static inline access_mask_t get_file_access(const struct file *const file)
1148 {
1149     access_mask_t access = 0;
1150 
1151     if (file->f_mode & FMODE_READ) {
1152         /* A directory can only be opened in read mode. */
1153         if (S_ISDIR(file_inode(file)->i_mode))
1154             return LANDLOCK_ACCESS_FS_READ_DIR;
1155         access = LANDLOCK_ACCESS_FS_READ_FILE;
1156     }
1157     if (file->f_mode & FMODE_WRITE)
1158         access |= LANDLOCK_ACCESS_FS_WRITE_FILE;
1159     /* __FMODE_EXEC is indeed part of f_flags, not f_mode. */
1160     if (file->f_flags & __FMODE_EXEC)
1161         access |= LANDLOCK_ACCESS_FS_EXECUTE;
1162     return access;
1163 }
1164 
1165 static int hook_file_open(struct file *const file)
1166 {
1167     const struct landlock_ruleset *const dom =
1168         landlock_get_current_domain();
1169 
1170     if (!dom)
1171         return 0;
1172     /*
1173      * Because a file may be opened with O_PATH, get_file_access() may
1174      * return 0.  This case will be handled with a future Landlock
1175      * evolution.
1176      */
1177     return check_access_path(dom, &file->f_path, get_file_access(file));
1178 }
1179 
1180 static struct security_hook_list landlock_hooks[] __lsm_ro_after_init = {
1181     LSM_HOOK_INIT(inode_free_security, hook_inode_free_security),
1182 
1183     LSM_HOOK_INIT(sb_delete, hook_sb_delete),
1184     LSM_HOOK_INIT(sb_mount, hook_sb_mount),
1185     LSM_HOOK_INIT(move_mount, hook_move_mount),
1186     LSM_HOOK_INIT(sb_umount, hook_sb_umount),
1187     LSM_HOOK_INIT(sb_remount, hook_sb_remount),
1188     LSM_HOOK_INIT(sb_pivotroot, hook_sb_pivotroot),
1189 
1190     LSM_HOOK_INIT(path_link, hook_path_link),
1191     LSM_HOOK_INIT(path_rename, hook_path_rename),
1192     LSM_HOOK_INIT(path_mkdir, hook_path_mkdir),
1193     LSM_HOOK_INIT(path_mknod, hook_path_mknod),
1194     LSM_HOOK_INIT(path_symlink, hook_path_symlink),
1195     LSM_HOOK_INIT(path_unlink, hook_path_unlink),
1196     LSM_HOOK_INIT(path_rmdir, hook_path_rmdir),
1197 
1198     LSM_HOOK_INIT(file_open, hook_file_open),
1199 };
1200 
1201 __init void landlock_add_fs_hooks(void)
1202 {
1203     security_add_hooks(landlock_hooks, ARRAY_SIZE(landlock_hooks),
1204                LANDLOCK_NAME);
1205 }