Landlock LSM: Toward unprivileged sandboxing
Subsystems (17)
Mickaël Salaün
maintainerv9 cover Landlock LSM: Toward unprivileged sandboxing
Hi,
This ninth series upgrade Landlock as a stackable LSM [4] and elide the file system path evaluation from the previous series [1] to make this review process easier. This patch series is almost half the size of the previous one.
Landlock is a low-level framework to build custom access-control systems or safe endpoint security agents. There is two types of Landlock hooks:FS_WALK and FS_PICK. Each of them accepts a dedicated eBPF program, called a Landlock program. The set of actions on a file is well defined (e.g. read, write, ioctl, append, lock, mount...) taking inspiration from the major Linux LSMs and some other access-controls like Capsicum.
The example patch show how a file system access control can be built based on a list of denied files and directories. From a security point of view, it may be preferable to use a whitelist instead of a blacklist, but this series only enable to match a specific list of files. Bringing back a way to evaluate a path is planned for a future dedicated series, once this base Landlock framework is merged. I may take inspiration from the LOOKUP_BENEATH approach [5], but from an eBPF point of view.
The documentation patch contains some kernel documentation and explanations on how to use Landlock. The compiled documentation and some talks can be found here: https://landlock.io
This patch series can be found in a Git repository here:
https://github.com/landlock-lsm/linux/commits/landlock-v9
There is still some minor issues with this patch series but it is enough to get a deep review.
This is the first step of the roadmap discussed at LPC [2]. While the intended final goal is to allow unprivileged users to use Landlock, this series allows only a process with global CAP_SYS_ADMIN to load and enforce a rule. This may help to get feedback and avoid unexpected behaviors.
This series can be applied on top of bpf-next, commit 88091ff56b71 ("selftests, bpf: Add test for veth native XDP"). This can be tested with CONFIG_SECCOMP_FILTER and CONFIG_SECURITY_LANDLOCK. I would really appreciate constructive comments on the design and the code.
# Landlock LSM
The goal of this new Linux Security Module (LSM) called Landlock is to allow any process, including unprivileged ones, to create powerful security sandboxes comparable to XNU Sandbox or OpenBSD Pledge (which could be implemented with Landlock). This kind of sandbox is expected to help mitigate the security impact of bugs or unexpected/malicious behaviors in user-space applications.
The approach taken is to add the minimum amount of code while still allowing the user-space application to create quite complex access rules. A dedicated security policy language such as the one used by SELinux, AppArmor and other major LSMs involves a lot of code and is usually permitted to only a trusted user (i.e. root). On the contrary, eBPF programs already exist and are designed to be safely loaded by unprivileged user-space.
This design does not seem too intrusive but is flexible enough to allow a powerful sandbox mechanism accessible by any process on Linux. The use of seccomp and Landlock is more suitable with the help of a user-space library (e.g. libseccomp) that could help to specify a high-level language to express a security policy instead of raw eBPF programs. Moreover, thanks to the LLVM front-end, it is quite easy to write an eBPF program with a subset of the C language.
# Frequently asked questions
## Why is seccomp-bpf not enough?
A seccomp filter can access only raw syscall arguments (i.e. the register values) which means that it is not possible to filter according to the value pointed to by an argument, such as a file pathname. As an embryonic Landlock version demonstrated, filtering at the syscall level is complicated (e.g. need to take care of race conditions). This is mainly because the access control checkpoints of the kernel are not at this high-level but more underneath, at the LSM-hook level. The LSM hooks are designed to handle this kind of checks. Landlock abstracts this approach to leverage the ability of unprivileged users to limit themselves.
Cf. section "What it isn't?" in Documentation/prctl/seccomp_filter.txt
## Why use the seccomp(2) syscall?
Landlock use the same semantic as seccomp to apply access rule restrictions. It add a new layer of security for the current process which is inherited by its children. It makes sense to use an unique access-restricting syscall (that should be allowed by seccomp filters) which can only drop privileges. Moreover, a Landlock rule could come from outside a process (e.g. passed through a UNIX socket). It is then useful to differentiate the creation/load of Landlock eBPF programs via bpf(2), from rule enforcement via seccomp(2).
## Why a new LSM? Are SELinux, AppArmor, Smack and Tomoyo not good
enough?
The current access control LSMs are fine for their purpose which is to give the *root* the ability to enforce a security policy for the *system*. What is missing is a way to enforce a security policy for any application by its developer and *unprivileged user* as seccomp can do for raw syscall filtering.
Differences from other (access control) LSMs:
* not only dedicated to administrators (i.e. no_new_priv);
* limited kernel attack surface (e.g. policy parsing);
* constrained policy rules (no DoS: deterministic execution time);
* do not leak more information than the loader process can legitimately have access to (minimize metadata inference).
# Changes since v8
* fit with the new LSM stacking framework (security blobs were tested but are not use in this series because of the code reduction)
* remove the Landlock program chaining and the file path evaluation feature to get a minimum viable product and ease the review
* replace the example with a simple blacklist policy
* rebase on bpf-next
# Changes since v7
* major revamp of the file system enforcement:
* new eBPF map dedicated to tie an inode with an arbitrary 64-bits value, which can be used to tag files
* three new Landlock hooks: FS_WALK, FS_PICK and FS_GET
* add the ability to chain Landlock programs
* add a new eBPF map type to compare inodes
* don't use macros anymore
* replace subtype fields:
* triggers: fine-grained bitfiel of actions on which a Landlock program may be called (if it comes from a sandbox process)
* previous: a parent chained program
* upstreamed patches:
* commit 369130b63178 ("selftests: Enhance kselftest_harness.h to print which assert failed")
# Changes since v6
* upstreamed patches:
* commit 752ba56fb130 ("bpf: Extend check_uarg_tail_zero() checks")
* commit 0b40808a1084 ("selftests: Make test_harness.h more generally available") and related ones
* commit 3bb857e47e49 ("LSM: Enable multiple calls to security_add_hooks() for the same LSM")
* simplify the landlock_context (remove syscall_* fields) and add three FS sub-events: IOCTL, LOCK, FCNTL
* minimize the number of callable BPF functions from a Landlock rule
* do not split put_seccomp_filter() with put_seccomp()
* rename Landlock version to Landlock ABI
* miscellaneous fixes
* rebase on net-next
# Changes since v5
* eBPF program subtype:
* use a prog_subtype pointer instead of inlining it into bpf_attr
* enable a future-proof behavior (reject unhandled data/size)
* add tests
* use a simple rule hierarchy (similar to seccomp-bpf)
* add a ptrace scope protection
* add more tests
* add more documentation
* rename some files
* miscellaneous fixes
* rebase on net-next
# Changes since v4
* upstreamed patches:
* commit d498f8719a09 ("bpf: Rebuild bpf.o for any dependency update")
* commit a734fb5d6006 ("samples/bpf: Reset global variables") and related ones
* commit f4874d01beba ("bpf: Use bpf_create_map() from the library") and related ones
* commit d02d8986a768 ("bpf: Always test unprivileged programs")
* commit 640eb7e7b524 ("fs: Constify path_is_under()'s arguments")
* commit 535e7b4b5ef2 ("bpf: Use u64_to_user_ptr()")
* revamp Landlock to not expose an LSM hook interface but wrap and abstract them with Landlock events (currently one for all filesystem related operations: LANDLOCK_SUBTYPE_EVENT_FS)
* wrap all filesystem kernel objects through the same FS handle (struct landlock_handle_fs): struct file, struct inode, struct path and struct dentry
* a rule don't return an errno code but only a boolean to allow or deny an access request
* handle all filesystem related LSM hooks
* add some tests and a sample:
* BPF context tests
* Landlock sandboxing tests and sample
* write Landlock rules in C and compile them with LLVM
* change field names of eBPF program subtype
* remove arraymap of handles for now (will be replaced with a revamped map)
* remove cgroup handling for now
* add user and kernel documentation
* rebase on net-next
# Changes since v3
* upstreamed patch:
* commit 1955351da41c ("bpf: Set register type according to
is_valid_access()")
* use abstract LSM hook arguments with custom types (e.g. *_LANDLOCK_ARG_FS for struct file, struct inode and struct path)
* add more LSM hooks to support full filesystem access control
* improve the sandbox example
* fix races and RCU issues:
* eBPF program execution and eBPF helpers
* revamp the arraymap of handles to cleanly deal with update/delete
* eBPF program subtype for Landlock:
* remove the "origin" field
* add an "option" field
* rebase onto Daniel Mack's patches v7 [3]
* remove merged commit 1955351da41c ("bpf: Set register type according to is_valid_access()")
* fix spelling mistakes
* cleanup some type and variable names
* split patches
* for now, remove cgroup delegation handling for unprivileged user
* remove extra access check for cgroup_get_from_fd()
* remove unused example code dealing with skb
* remove seccomp-bpf link:
* no more seccomp cookie
* for now, it is no more possible to check the current syscall properties
# Changes since v2
* revamp cgroup handling:
* use Daniel Mack's patches "Add eBPF hooks for cgroups" v5
* remove bpf_landlock_cmp_cgroup_beneath()
* make BPF_PROG_ATTACH usable with delegated cgroups
* add a new CGRP_NO_NEW_PRIVS flag for safe cgroups
* handle Landlock sandboxing for cgroups hierarchy
* allow unprivileged processes to attach Landlock eBPF program to cgroups
* add subtype to eBPF programs:
* replace Landlock hook identification by custom eBPF program types with a dedicated subtype field
* manage fine-grained privileged Landlock programs
* register Landlock programs for dedicated trigger origins (e.g. syscall, return from seccomp filter and/or interruption)
* performance and memory optimizations: use an array to access Landlock hooks directly but do not duplicated it for each thread (seccomp-based)
* allow running Landlock programs without seccomp filter
* fix seccomp-related issues
* remove extra errno bounding check for Landlock programs
* add some examples for optional eBPF functions or context access (network related) according to security checks to allow more features for privileged programs (e.g. Checmate)
# Changes since v1
* focus on the LSM hooks, not the syscalls:
* much more simple implementation
* does not need audit cache tricks to avoid race conditions
* more simple to use and more generic because using the LSM hook abstraction directly
* more efficient because only checking in LSM hooks
* architecture agnostic
* switch from cBPF to eBPF:
* new eBPF program types dedicated to Landlock
* custom functions used by the eBPF program
* gain some new features (e.g. 10 registers, can load values of different size, LLVM translator) but only a few functions allowed and a dedicated map type
* new context: LSM hook ID, cookie and LSM hook arguments
* need to set the sysctl kernel.unprivileged_bpf_disable to 0 (default value) to be able to load hook filters as unprivileged users
* smaller and simpler:
* no more checker groups but dedicated arraymap of handles
* simpler userland structs thanks to eBPF functions
* distinctive name: Landlock
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/
[3] https://lore.kernel.org/netdev/[email protected]/
[4] https://lore.kernel.org/lkml/[email protected]/
[5] https://lore.kernel.org/lkml/[email protected]/
Regards,
Mickaël Salaün (10):
fs,security: Add a new file access type: MAY_CHROOT
bpf: Add eBPF program subtype and is_valid_subtype() verifier bpf,landlock: Define an eBPF program type for Landlock hooks seccomp,landlock: Enforce Landlock programs per process hierarchy bpf,landlock: Add a new map type: inode
landlock: Handle filesystem access control
landlock: Add ptrace restrictions
bpf: Add a Landlock sandbox example
bpf,landlock: Add tests for Landlock
landlock: Add user and kernel documentation for Landlock
Documentation/security/index.rst | 1 + Documentation/security/landlock/index.rst | 20 + Documentation/security/landlock/kernel.rst | 99 +++ Documentation/security/landlock/user.rst | 148 +++++ MAINTAINERS | 13 + fs/open.c | 3 +- include/linux/bpf.h | 17 + include/linux/bpf_types.h | 6 + include/linux/fs.h | 1 + include/linux/landlock.h | 34 ++ include/linux/lsm_hooks.h | 1 + include/linux/seccomp.h | 5 + include/uapi/linux/bpf.h | 22 +- include/uapi/linux/landlock.h | 109 ++++ include/uapi/linux/seccomp.h | 1 + kernel/bpf/Makefile | 3 + kernel/bpf/core.c | 3 + kernel/bpf/inodemap.c | 315 ++++++++++ kernel/bpf/syscall.c | 59 +- kernel/bpf/verifier.c | 25 + kernel/fork.c | 8 +- kernel/seccomp.c | 4 + net/core/filter.c | 25 +- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 3 + samples/bpf/bpf_load.c | 76 ++- samples/bpf/bpf_load.h | 7 + samples/bpf/landlock1.h | 8 + samples/bpf/landlock1_kern.c | 104 ++++ samples/bpf/landlock1_user.c | 157 +++++ security/Kconfig | 1 + security/Makefile | 2 + security/landlock/Kconfig | 18 + security/landlock/Makefile | 5 + security/landlock/common.h | 81 +++ security/landlock/enforce.c | 272 +++++++++ security/landlock/enforce.h | 18 + security/landlock/enforce_seccomp.c | 92 +++ security/landlock/hooks.c | 95 +++ security/landlock/hooks.h | 31 + security/landlock/hooks_fs.c | 568 ++++++++++++++++++ security/landlock/hooks_fs.h | 31 + security/landlock/hooks_ptrace.c | 121 ++++ security/landlock/hooks_ptrace.h | 8 + security/landlock/init.c | 159 +++++ security/security.c | 15 + tools/include/uapi/linux/bpf.h | 22 +- tools/include/uapi/linux/landlock.h | 109 ++++ tools/lib/bpf/bpf.c | 10 +- tools/lib/bpf/bpf.h | 2 + tools/lib/bpf/libbpf.c | 1 + tools/lib/bpf/libbpf.map | 1 + tools/lib/bpf/libbpf_probes.c | 2 + tools/testing/selftests/Makefile | 1 + tools/testing/selftests/bpf/bpf_helpers.h | 2 + tools/testing/selftests/bpf/test_verifier.c | 27 +- .../testing/selftests/bpf/verifier/landlock.c | 35 ++ .../testing/selftests/bpf/verifier/subtype.c | 20 + tools/testing/selftests/landlock/.gitignore | 4 + tools/testing/selftests/landlock/Makefile | 39 ++ tools/testing/selftests/landlock/test.h | 48 ++ tools/testing/selftests/landlock/test_base.c | 24 + tools/testing/selftests/landlock/test_fs.c | 257 ++++++++ .../testing/selftests/landlock/test_ptrace.c | 154 +++++ 64 files changed, 3528 insertions(+), 25 deletions(-) create mode 100644 Documentation/security/landlock/index.rst create mode 100644 Documentation/security/landlock/kernel.rst create mode 100644 Documentation/security/landlock/user.rst create mode 100644 include/linux/landlock.h create mode 100644 include/uapi/linux/landlock.h create mode 100644 kernel/bpf/inodemap.c create mode 100644 samples/bpf/landlock1.h create mode 100644 samples/bpf/landlock1_kern.c create mode 100644 samples/bpf/landlock1_user.c create mode 100644 security/landlock/Kconfig create mode 100644 security/landlock/Makefile create mode 100644 security/landlock/common.h create mode 100644 security/landlock/enforce.c create mode 100644 security/landlock/enforce.h create mode 100644 security/landlock/enforce_seccomp.c create mode 100644 security/landlock/hooks.c create mode 100644 security/landlock/hooks.h create mode 100644 security/landlock/hooks_fs.c create mode 100644 security/landlock/hooks_fs.h create mode 100644 security/landlock/hooks_ptrace.c create mode 100644 security/landlock/hooks_ptrace.h create mode 100644 security/landlock/init.c create mode 100644 tools/include/uapi/linux/landlock.h create mode 100644 tools/testing/selftests/bpf/verifier/landlock.c create mode 100644 tools/testing/selftests/bpf/verifier/subtype.c create mode 100644 tools/testing/selftests/landlock/.gitignore create mode 100644 tools/testing/selftests/landlock/Makefile create mode 100644 tools/testing/selftests/landlock/test.h create mode 100644 tools/testing/selftests/landlock/test_base.c create mode 100644 tools/testing/selftests/landlock/test_fs.c create mode 100644 tools/testing/selftests/landlock/test_ptrace.c
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 1/10 fs,security: Add a new file access type: MAY_CHROOT
For compatibility reason, MAY_CHROOT is always set with MAY_CHDIR. However, this new flag enable to differentiate a chdir form a chroot.
This is needed for the Landlock LSM to be able to evaluate a new root directory.
--- fs/open.c | 3 ++- include/linux/fs.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-)
fs/open.c +2 -1
@@ -494,7 +494,8 @@ int ksys_chroot(const char __user *filename)if (error) goto out; - error =inode_permission (path.dentry->d_inode,MAY_EXEC |MAY_CHDIR ); + error =inode_permission (path.dentry->d_inode,MAY_EXEC |MAY_CHDIR | +MAY_CHROOT );if (error) goto dput_and_out;
include/linux/fs.h +1 -0
@@ -99,6 +99,7 @@ typedef int (dio_iodone_t)(struct kiocb *iocb, loff_t offset,#define MAY_CHDIR 0x00000040/* called from RCU mode, don't block */ #define MAY_NOT_BLOCK 0x00000080 +#define MAY_CHROOT 0x00000100/* * flags in file.f_mode. Note that FMODE_READ and FMODE_WRITE must correspond
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 2/10 bpf: Add eBPF program subtype and is_valid_subtype() verifier
In reply to Mickaël SalaünThe goal of the program subtype is to be able to have different static fine-grained verifications for a unique program type.
The struct bpf_verifier_ops gets a new optional function:is_valid_subtype(). This new verifier is called at the beginning of the eBPF program verification to check if the (optional) program subtype is valid.
The new helper bpf_load_program_xattr() enables to verify a program with subtypes.
For now, only Landlock eBPF programs are using a program subtype (see next commits) but this could be used by other program types in the future.
---
Changes since v8:
* use bpf_load_program_xattr() instead of bpf_load_program() and add bpf_verify_program_xattr() to deal with subtypes
* remove put_extra() since there is no more "previous" field (for now)
Changes since v7:
* rename LANDLOCK_SUBTYPE_* to LANDLOCK_*
* move subtype in bpf_prog_aux and use only one bit for has_subtype (suggested by Alexei Starovoitov)
* wrap the prog_subtype with a prog_extra to be able to reference kernel pointers:
* add an optional put_extra() function to struct bpf_prog_ops to be able to free the pointed data
* replace all the prog_subtype with prog_extra in the struct bpf_verifier_ops functions
* remove the ABI field (requested by Alexei Starovoitov)
* rename subtype fields
Changes since v6:
* rename Landlock version to ABI to better reflect its purpose
* fix unsigned integer checks
* fix pointer cast
* constify pointers
* rebase
Changes since v5:
* use a prog_subtype pointer and make it future-proof
* add subtype test
* constify bpf_load_program()'s subtype argument
* cleanup subtype initialization
* rebase
Changes since v4:
* replace the "status" field with "version" (more generic)
* replace the "access" field with "ability" (less confusing)
Changes since v3:
* remove the "origin" field
* add an "option" field
* cleanup comments
--- include/linux/bpf.h | 8 +++++ include/uapi/linux/bpf.h | 9 ++++++ kernel/bpf/core.c | 1 + kernel/bpf/syscall.c | 32 ++++++++++++++++++- kernel/bpf/verifier.c | 11 +++++++ net/core/filter.c | 25 ++++++++------- tools/include/uapi/linux/bpf.h | 9 ++++++ tools/lib/bpf/bpf.c | 10 +++++- tools/lib/bpf/bpf.h | 2 ++ tools/lib/bpf/libbpf.map | 1 + tools/testing/selftests/bpf/test_verifier.c | 26 +++++++++++++-- .../testing/selftests/bpf/verifier/subtype.c | 10 ++++++ 12 files changed, 128 insertions(+), 16 deletions(-) create mode 100644 tools/testing/selftests/bpf/verifier/subtype.c
include/linux/bpf.h +8 -0
@@ -294,6 +294,11 @@ bpf_ctx_record_field_size(struct bpf_insn_access_aux *aux, u32 size) aux->ctx_field_size = size; } +/* specific data per program type */ +struct bpf_prog_extra { +union bpf_prog_subtype subtype; +}; +struct bpf_prog_ops {int (*test_run)(struct bpf_prog *prog,const union bpf_attr *kattr,union bpf_attr __user *uattr);
@@ -319,6 +324,8 @@ struct bpf_verifier_ops {const struct bpf_insn *src, struct bpf_insn *dst, struct bpf_prog *prog, u32 *target_size); +// TODO?: convert to bool (*is_valid_subtype)(struct bpf_prog *prog); +bool (*is_valid_subtype)(struct bpf_prog_extra *prog_extra); };struct bpf_prog_offload_ops {
@@ -418,6 +425,7 @@ struct bpf_prog_aux {struct work_struct work;struct rcu_head rcu; }; +struct bpf_prog_extra *extra; };struct bpf_array {
include/uapi/linux/bpf.h +9 -0
@@ -355,6 +355,13 @@ struct bpf_stack_build_id { }; }; +union bpf_prog_subtype { +struct { +__u32 type;/* enum landlock_hook_type */ +__aligned_u64 triggers;/* LANDLOCK_TRIGGER_* */ + } landlock_hook; +} __attribute__((aligned (8 ))); +union bpf_attr {struct {/* anonymous struct used by BPF_MAP_CREATE command */ __u32 map_type;/* one of enum bpf_map_type */
@@ -409,6 +416,8 @@ union bpf_attr {__u32 line_info_rec_size;/* userspace bpf_line_info size */ __aligned_u64 line_info;/* line info */ __u32 line_info_cnt;/* number of bpf_line_info records */ +__aligned_u64 prog_subtype;/* bpf_prog_subtype address */ +__u32 prog_subtype_size; };struct {/* anonymous struct used by BPF_OBJ_* commands */
kernel/bpf/core.c +1 -0
@@ -255,6 +255,7 @@ void __bpf_prog_free(struct bpf_prog *fp) {if (fp->aux) {free_percpu (fp->aux->stats); +kfree (fp->aux->extra);kfree (fp->aux); }vfree (fp);
kernel/bpf/syscall.c +31 -1
@@ -1596,7 +1596,7 @@ bpf_prog_load_check_attach_type(enum bpf_prog_type prog_type, }/* last field in 'union bpf_attr' used by this command */ -#define BPF_PROG_LOAD_LAST_FIELD line_info_cnt +#define BPF_PROG_LOAD_LAST_FIELD prog_subtype_sizestatic int bpf_prog_load (union bpf_attr *attr,union bpf_attr __user *uattr) {
@@ -1686,6 +1686,36 @@ static int bpf_prog_load(union bpf_attr *attr, union bpf_attr __user *uattr)if (err) goto free_prog; +/* copy eBPF program subtype from user space */ +if (attr->prog_subtype) { +u32 size; + + err =bpf_check_uarg_tail_zero ( +u64_to_user_ptr (attr->prog_subtype), +sizeof (prog->aux->extra->subtype), + attr->prog_subtype_size); +if (err) + goto free_prog; + size =min_t (u32, attr->prog_subtype_size, +sizeof (prog->aux->extra->subtype)); + + prog->aux->extra =kzalloc (sizeof (*prog->aux->extra), +GFP_KERNEL |GFP_USER ); +if (!prog->aux->extra) { + err = -ENOMEM ; + goto free_prog; + } +if (copy_from_user (&prog->aux->extra->subtype, +u64_to_user_ptr (attr->prog_subtype), size) + !=0 ) { + err = -EFAULT ; + goto free_prog; + } + }else if (attr->prog_subtype_size !=0 ) { + err = -EINVAL ; + goto free_prog; + } +/* run eBPF verifier */ err =bpf_check (&prog, attr, uattr);if (err <0 )
kernel/bpf/verifier.c +11 -0
@@ -9167,6 +9167,17 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,if (ret <0 ) goto skip_full_check; +if (env->ops->is_valid_subtype) { +if (!env->ops->is_valid_subtype (env->prog->aux->extra)) { + ret = -EINVAL ; + goto err_unlock; + } + }else if (env->prog->aux->extra) { +/* do not accept a subtype if the program does not handle it */ + ret = -EINVAL ; + goto err_unlock; + } +if (bpf_prog_is_dev_bound (env->prog->aux)) { ret =bpf_prog_offload_verifier_prep (env->prog);if (ret)
net/core/filter.c +13 -12
@@ -5846,7 +5846,8 @@ bool bpf_helper_changes_pkt_data(void *func) }static const struct bpf_func_proto * -bpf_base_func_proto (enum bpf_func_id func_id) +bpf_base_func_proto (enum bpf_func_id func_id, +const struct bpf_prog_extra *prog_extra) {switch (func_id) {case BPF_FUNC_map_lookup_elem:
@@ -5902,7 +5903,7 @@ sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_get_local_storage:return &bpf_get_local_storage_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -5942,7 +5943,7 @@ sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_sk_storage_delete:return &bpf_sk_storage_delete_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -5959,7 +5960,7 @@ sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_get_socket_uid:return &bpf_get_socket_uid_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6096,7 +6097,7 @@ tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_skb_ecn_set_ce_proto;#endif default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6135,7 +6136,7 @@ xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_tcp_check_syncookie_proto;#endif default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6171,7 +6172,7 @@ sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_tcp_sock_proto;#endif /* CONFIG_INET */ default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6197,7 +6198,7 @@ sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_msg_pop_data:return &bpf_msg_pop_data_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6237,7 +6238,7 @@ sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_skc_lookup_tcp_proto;#endif default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6248,7 +6249,7 @@ flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_skb_load_bytes:return &bpf_flow_dissector_load_bytes_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -6275,7 +6276,7 @@ lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_skb_under_cgroup:return &bpf_skb_under_cgroup_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
@@ -8611,7 +8612,7 @@ sk_reuseport_func_proto(enum bpf_func_id func_id,case BPF_FUNC_skb_load_bytes_relative:return &sk_reuseport_load_bytes_relative_proto;default : -return bpf_base_func_proto (func_id); +return bpf_base_func_proto (func_id, prog->aux->extra); } }
tools/include/uapi/linux/bpf.h +9 -0
@@ -355,6 +355,13 @@ struct bpf_stack_build_id { }; }; +union bpf_prog_subtype { +struct { +__u32 type;/* enum landlock_hook_type */ +__aligned_u64 triggers;/* LANDLOCK_TRIGGER_* */ + } landlock_hook; +} __attribute__((aligned (8 ))); +union bpf_attr {struct {/* anonymous struct used by BPF_MAP_CREATE command */ __u32 map_type;/* one of enum bpf_map_type */
@@ -409,6 +416,8 @@ union bpf_attr {__u32 line_info_rec_size;/* userspace bpf_line_info size */ __aligned_u64 line_info;/* line info */ __u32 line_info_cnt;/* number of bpf_line_info records */ +__aligned_u64 prog_subtype;/* bpf_prog_subtype address */ +__u32 prog_subtype_size; };struct {/* anonymous struct used by BPF_OBJ_* commands */
tools/lib/bpf/bpf.c +9 -1
@@ -227,6 +227,9 @@ int bpf_load_program_xattr(const struct bpf_load_program_attr *load_attr,memset (&attr,0 ,sizeof (attr)); attr.prog_type = load_attr->prog_type; + attr.prog_subtype =ptr_to_u64 (load_attr->prog_subtype); + attr.prog_subtype_size = load_attr->prog_subtype ? +sizeof (*load_attr->prog_subtype) :0 ; attr.expected_attach_type = load_attr->expected_attach_type; attr.insn_cnt = (__u32 )load_attr->insns_cnt; attr.insns =ptr_to_u64 (load_attr->insns);
@@ -332,6 +335,11 @@ int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns,return bpf_load_program_xattr (&load_attr, log_buf, log_buf_sz); } +int bpf_verify_program_xattr (union bpf_attr *attr,size_t attr_sz) +{ +return sys_bpf_prog_load (attr, attr_sz); +} + int bpf_verify_program(enum bpf_prog_type type, const struct bpf_insn *insns, size_t insns_cnt, __u32 prog_flags, const char *license, __u32 kern_version, char *log_buf, size_t log_buf_sz,
@@ -351,7 +359,7 @@ int bpf_verify_program(enum bpf_prog_type type, const struct bpf_insn *insns, attr.kern_version = kern_version; attr.prog_flags = prog_flags; -return sys_bpf_prog_load (&attr,sizeof (attr)); +return bpf_verify_program_xattr (&attr,sizeof (attr)); } int bpf_map_update_elem(int fd, const void *key, const void *value,
tools/lib/bpf/bpf.h +2 -0
@@ -88,6 +88,7 @@ struct bpf_load_program_attr {__u32 line_info_cnt;__u32 log_level;__u32 prog_flags; +const union bpf_prog_subtype *prog_subtype; };/* Flags to direct loading requirements */
@@ -102,6 +103,7 @@ LIBBPF_API int bpf_load_program(enum bpf_prog_type type, const struct bpf_insn *insns, size_t insns_cnt, const char *license, __u32 kern_version, char *log_buf, size_t log_buf_sz); +LIBBPF_API int bpf_verify_program_xattr(union bpf_attr *attr, size_t attr_sz); LIBBPF_API int bpf_verify_program(enum bpf_prog_type type, const struct bpf_insn *insns, size_t insns_cnt, __u32 prog_flags,
tools/lib/bpf/libbpf.map +1 -0
@@ -107,6 +107,7 @@ LIBBPF_0.0.1 { bpf_set_link_xdp_fd; bpf_task_fd_query; bpf_verify_program; + bpf_verify_program_xattr; btf__fd; btf__find_by_name; btf__free;
tools/testing/selftests/bpf/test_verifier.c +24 -2
@@ -105,6 +105,8 @@ struct bpf_test {__u64 data64[TEST_DATA_LEN /8 ]; }; } retvals[MAX_TEST_RUNS ]; +bool has_prog_subtype; +union bpf_prog_subtype prog_subtype; };/* Note we want this to be 64 bit aligned so that the end of our array is
@@ -122,6 +124,11 @@ struct other_val {long long bar; }; +static inline __u64 ptr_to_u64 (const void *ptr) +{ +return (__u64 ) (unsigned long ) ptr; +} +static void bpf_fill_ld_abs_vlan_push_pop (struct bpf_test *self) {/* test: {skb->data[0], vlan_push} x 51 + {skb->data[0], vlan_pop} x 51 */
@@ -856,6 +863,9 @@ static void do_test_single(struct bpf_test *test, bool unpriv,int fixup_skips;__u32 pflags;int i, err; +union bpf_attr attr; +union bpf_prog_subtype *prog_subtype = + test->has_prog_subtype ? &test->prog_subtype :NULL ;for (i =0 ; i <MAX_NR_MAPS ; i++) map_fds[i] =-1 ;
@@ -881,8 +891,20 @@ static void do_test_single(struct bpf_test *test, bool unpriv, pflags |=BPF_F_STRICT_ALIGNMENT ;if (test->flags &F_NEEDS_EFFICIENT_UNALIGNED_ACCESS ) pflags |=BPF_F_ANY_ALIGNMENT ; - fd_prog =bpf_verify_program (prog_type, prog, prog_len, pflags, -"GPL" ,0 , bpf_vlog,sizeof (bpf_vlog),4 ); + +memset (&attr,0 ,sizeof (attr)); + attr.prog_type = prog_type; + attr.prog_subtype =ptr_to_u64 (prog_subtype); + attr.prog_subtype_size = prog_subtype ?sizeof (*prog_subtype) :0 ; + attr.insn_cnt = (__u32 )prog_len; + attr.insns =ptr_to_u64 (prog); + attr.license =ptr_to_u64 ("GPL" ); + bpf_vlog[0 ] =0 ; + attr.log_buf =ptr_to_u64 (bpf_vlog); + attr.log_size =sizeof (bpf_vlog); + attr.log_level =4 ; + attr.prog_flags = pflags; + fd_prog =bpf_verify_program_xattr (&attr,sizeof (attr));if (fd_prog <0 && !bpf_probe_prog_type (prog_type,0 )) {printf ("SKIP (unsupported program type %d)\n" , prog_type); skips++;
tools/testing/selftests/bpf/verifier/subtype.c new file +10 -0
@@ -0,0 +1,10 @@ +{ + "superfluous subtype", + .insns = { +BPF_MOV32_IMM (BPF_REG_0 ,0 ), + BPF_EXIT_INSN(), + }, + .errstr ="" , + .result = REJECT, + .has_prog_subtype = true, +},
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 3/10 bpf,landlock: Define an eBPF program type for Landlock hooks
In reply to Mickaël SalaünAdd a new type of eBPF program used by Landlock hooks. This type of program can be chained with the same eBPF program type (according to subtype rules). A state can be kept with a value available in the program's context (e.g. named "cookie" for Landlock programs).
This new BPF program type will be registered with the Landlock LSM initialization.
Add an initial Landlock Kconfig and update the MAINTAINERS file.
---
Changes since v8:
* Remove the chaining concept from the eBPF program contexts (chain and cookie). We need to keep these subtypes this way to be able to make them evolve, though.
* remove bpf_landlock_put_extra() because there is no more a "previous" field to free (for now)
Changes since v7:
* cosmetic fixes
* rename LANDLOCK_SUBTYPE_* to LANDLOCK_*
* cleanup UAPI definitions and move them from bpf.h to landlock.h (suggested by Alexei Starovoitov)
* disable Landlock by default (suggested by Alexei Starovoitov)
* rename BPF_PROG_TYPE_LANDLOCK_{RULE,HOOK}
* update the Kconfig
* update the MAINTAINERS file
* replace the IOCTL, LOCK and FCNTL events with FS_PICK, FS_WALK and FS_GET hook types
* add the ability to chain programs with an eBPF program file descriptor (i.e. the "previous" field in a Landlock subtype) and keep a state with a "cookie" value available from the context
* add a "triggers" subtype bitfield to match specific actions (e.g. append, chdir, read...)
Changes since v6:
* add 3 more sub-events: IOCTL, LOCK, FCNTL
https://lkml.kernel.org/r/[email protected]
* rename LANDLOCK_VERSION to LANDLOCK_ABI to better reflect its purpose, and move it from landlock.h to common.h
* rename BPF_PROG_TYPE_LANDLOCK to BPF_PROG_TYPE_LANDLOCK_RULE: an eBPF program could be used for something else than a rule
* simplify struct landlock_context by removing the arch and syscall_nr fields
* remove all eBPF map functions call, remove ABILITY_WRITE
* refactor bpf_landlock_func_proto() (suggested by Kees Cook)
* constify pointers
* fix doc inclusion
Changes since v5:
* rename file hooks.c to init.c
* fix spelling
Changes since v4:
* merge a minimal (not enabled) LSM code and Kconfig in this commit
Changes since v3:
* split commit
* revamp the landlock_context:
* add arch, syscall_nr and syscall_cmd (ioctl, fcntl…) to be able to cross-check action with the event type
* replace args array with dedicated fields to ease the addition of new fields
--- MAINTAINERS | 13 ++++ include/linux/bpf_types.h | 3 + include/uapi/linux/bpf.h | 1 + include/uapi/linux/landlock.h | 109 +++++++++++++++++++++++++++ security/Kconfig | 1 + security/Makefile | 2 + security/landlock/Kconfig | 18 +++++ security/landlock/Makefile | 3 + security/landlock/common.h | 26 +++++++ security/landlock/init.c | 110 ++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 1 + tools/include/uapi/linux/landlock.h | 109 +++++++++++++++++++++++++++ tools/lib/bpf/libbpf.c | 1 + tools/lib/bpf/libbpf_probes.c | 1 + 14 files changed, 398 insertions(+) create mode 100644 include/uapi/linux/landlock.h create mode 100644 security/landlock/Kconfig create mode 100644 security/landlock/Makefile create mode 100644 security/landlock/common.h create mode 100644 security/landlock/init.c create mode 100644 tools/include/uapi/linux/landlock.h
MAINTAINERS +13 -0
@@ -8807,6 +8807,19 @@ F: net/core/skmsg.c F: net/core/sock_map.c F: net/ipv4/tcp_bpf.c +LANDLOCK SECURITY MODULE +M: Mickaël Salaün <[email protected]> +S: Supported +F: Documentation/security/landlock/ +F: include/linux/landlock.h +F: include/uapi/linux/landlock.h +F: samples/bpf/landlock* +F: security/landlock/ +F: tools/include/uapi/linux/landlock.h +F: tools/testing/selftests/landlock/ +K: landlock +K: LANDLOCK + LANTIQ / INTEL Ethernet drivers M: Hauke Mehrtens <[email protected]> L: [email protected]
include/linux/bpf_types.h +3 -0
@@ -37,6 +37,9 @@ BPF_PROG_TYPE(BPF_PROG_TYPE_LIRC_MODE2, lirc_mode2)#ifdef CONFIG_INET BPF_PROG_TYPE(BPF_PROG_TYPE_SK_REUSEPORT, sk_reuseport)#endif +#ifdef CONFIG_SECURITY_LANDLOCK +BPF_PROG_TYPE(BPF_PROG_TYPE_LANDLOCK_HOOK, landlock) +#endif BPF_MAP_TYPE(BPF_MAP_TYPE_ARRAY, array_map_ops)BPF_MAP_TYPE (BPF_MAP_TYPE_PERCPU_ARRAY , percpu_array_map_ops)
include/uapi/linux/bpf.h +1 -0
@@ -170,6 +170,7 @@ enum bpf_prog_type {BPF_PROG_TYPE_FLOW_DISSECTOR ,BPF_PROG_TYPE_CGROUP_SYSCTL ,BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE , + BPF_PROG_TYPE_LANDLOCK_HOOK, }; enum bpf_attach_type {
include/uapi/linux/landlock.h new file +109 -0
109 lines not on this page · raw message
security/Kconfig +1 -0
@@ -237,6 +237,7 @@ source "security/apparmor/Kconfig" source "security/loadpin/Kconfig" source "security/yama/Kconfig" source "security/safesetid/Kconfig" +source "security/landlock/Kconfig" source "security/integrity/Kconfig"
security/Makefile +2 -0
@@ -11,6 +11,7 @@ subdir-$(CONFIG_SECURITY_APPARMOR) += apparmor subdir-$(CONFIG_SECURITY_YAMA) += yama subdir-$(CONFIG_SECURITY_LOADPIN) += loadpin subdir-$(CONFIG_SECURITY_SAFESETID) += safesetid +subdir-$(CONFIG_SECURITY_LANDLOCK) += landlock # always enable default capabilities obj-y += commoncap.o
@@ -27,6 +28,7 @@ obj-$(CONFIG_SECURITY_APPARMOR) += apparmor/ obj-$(CONFIG_SECURITY_YAMA) += yama/ obj-$(CONFIG_SECURITY_LOADPIN) += loadpin/ obj-$(CONFIG_SECURITY_SAFESETID) += safesetid/ +obj-$(CONFIG_SECURITY_LANDLOCK) += landlock/ obj-$(CONFIG_CGROUP_DEVICE) += device_cgroup.o # Object integrity file lists
security/landlock/Kconfig new file +18 -0
@@ -0,0 +1,18 @@ +config SECURITY_LANDLOCK + bool "Landlock support" + depends on SECURITY + depends on BPF_SYSCALL + depends on SECCOMP_FILTER + default n + help + This selects Landlock, a programmatic access control. It enables to + restrict processes on the fly (i.e. create a sandbox). The security + policy is a set of eBPF programs, dedicated to deny a list of actions + on specific kernel objects (e.g. file). + + You need to enable seccomp filter to apply a security policy to a + process hierarchy (e.g. application with built-in sandboxing). + + See Documentation/security/landlock/ for further information. + + If you are unsure how to answer this question, answer N.
security/landlock/Makefile new file +3 -0
@@ -0,0 +1,3 @@ +obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o + +landlock-y := init.o
security/landlock/common.h new file +26 -0
@@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - private headers +* +* Copyright © 2016-2019 Mickaël Salaün <[email protected]> +* Copyright © 2018-2019 ANSSI +*/ + +#ifndef _SECURITY_LANDLOCK_COMMON_H +#define _SECURITY_LANDLOCK_COMMON_H + +#include <linux/bpf.h> /* enum bpf_prog_aux */ +#include <linux/filter.h> /* bpf_prog */ +#include <linux/refcount.h> /* refcount_t */ +#include <uapi/linux/landlock.h> /* enum landlock_hook_type */ + +#define LANDLOCK_NAME "landlock" + +/* UAPI bounds and bitmasks */ + +#define _LANDLOCK_HOOK_LAST LANDLOCK_HOOK_FS_WALK + +#define _LANDLOCK_TRIGGER_FS_PICK_LAST LANDLOCK_TRIGGER_FS_PICK_WRITE +#define _LANDLOCK_TRIGGER_FS_PICK_MASK ((_LANDLOCK_TRIGGER_FS_PICK_LAST << 1ULL) - 1) + +#endif /* _SECURITY_LANDLOCK_COMMON_H */
security/landlock/init.c new file +110 -0
110 lines not on this page · raw message
tools/include/uapi/linux/bpf.h +1 -0
@@ -170,6 +170,7 @@ enum bpf_prog_type {BPF_PROG_TYPE_FLOW_DISSECTOR ,BPF_PROG_TYPE_CGROUP_SYSCTL ,BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE , + BPF_PROG_TYPE_LANDLOCK_HOOK, }; enum bpf_attach_type {
tools/include/uapi/linux/landlock.h new file +109 -0
109 lines not on this page · raw message
tools/lib/bpf/libbpf.c +1 -0
@@ -2646,6 +2646,7 @@ static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE :case BPF_PROG_TYPE_PERF_EVENT :case BPF_PROG_TYPE_CGROUP_SYSCTL : +case BPF_PROG_TYPE_LANDLOCK_HOOK :return false;case BPF_PROG_TYPE_KPROBE :default :
tools/lib/bpf/libbpf_probes.c +1 -0
@@ -101,6 +101,7 @@ probe_load(enum bpf_prog_type prog_type, const struct bpf_insn *insns,case BPF_PROG_TYPE_SK_REUSEPORT :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_SYSCTL : +case BPF_PROG_TYPE_LANDLOCK_HOOK :default :break ; }
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 4/10 seccomp,landlock: Enforce Landlock programs per process hierarchy
In reply to Mickaël SalaünThe seccomp(2) syscall can be used by a task to apply a Landlock program to itself. As a seccomp filter, a Landlock program is enforced for the current task and all its future children. A program is immutable and a task can only add new restricting programs to itself, forming a list of programss.
A Landlock program is tied to a Landlock hook. If the action on a kernel object is allowed by the other Linux security mechanisms (e.g. DAC, capabilities, other LSM), then a Landlock hook related to this kind of object is triggered. The list of programs for this hook is then evaluated. Each program return a 32-bit value which can deny the action on a kernel object with a non-zero value. If every programs of the list return zero, then the action on the object is allowed.
---
Changes since v8:
* Remove the chaining concept from the eBPF program contexts (chain and cookie). We need to keep these subtypes this way to be able to make them evolve, though.
Changes since v7:
* handle and verify program chains
* split and rename providers.c to enforce.c and enforce_seccomp.c
* rename LANDLOCK_SUBTYPE_* to LANDLOCK_*
Changes since v6:
* rename some functions with more accurate names to reflect that an eBPF program for Landlock could be used for something else than a rule
* reword rule "appending" to "prepending" and explain it
* remove the superfluous no_new_privs check, only check global CAP_SYS_ADMIN when prepending a Landlock rule (needed for containers)
* create and use {get,put}_seccomp_landlock() (suggested by Kees Cook)
* replace ifdef with static inlined function (suggested by Kees Cook)
* use get_user() (suggested by Kees Cook)
* replace atomic_t with refcount_t (requested by Kees Cook)
* move struct landlock_{rule,events} from landlock.h to common.h
* cleanup headers
Changes since v5:
* remove struct landlock_node and use a similar inheritance mechanisme as seccomp-bpf (requested by Andy Lutomirski)
* rename SECCOMP_ADD_LANDLOCK_RULE to SECCOMP_APPEND_LANDLOCK_RULE
* rename file manager.c to providers.c
* add comments
* typo and cosmetic fixes
Changes since v4:
* merge manager and seccomp patches
* return -EFAULT in seccomp(2) when user_bpf_fd is null to easely check if Landlock is supported
* only allow a process with the global CAP_SYS_ADMIN to use Landlock (will be lifted in the future)
* add an early check to exit as soon as possible if the current process does not have Landlock rules
Changes since v3:
* remove the hard link with seccomp (suggested by Andy Lutomirski and Kees Cook):
* remove the cookie which could imply multiple evaluation of Landlock rules
* remove the origin field in struct landlock_data
* remove documentation fix (merged upstream)
* rename the new seccomp command to SECCOMP_ADD_LANDLOCK_RULE
* internal renaming
* split commit
* new design to be able to inherit on the fly the parent rules
Changes since v2:
* Landlock programs can now be run without seccomp filter but for any syscall (from the process) or interruption
* move Landlock related functions and structs into security/landlock/* (to manage cgroups as well)
* fix seccomp filter handling: run Landlock programs for each of their legitimate seccomp filter
* properly clean up all seccomp results
* cosmetic changes to ease the understanding
* fix some ifdef
--- include/linux/landlock.h | 34 ++++ include/linux/seccomp.h | 5 + include/uapi/linux/seccomp.h | 1 + kernel/fork.c | 8 +- kernel/seccomp.c | 4 + security/landlock/Makefile | 3 +- security/landlock/common.h | 45 +++++ security/landlock/enforce.c | 272 ++++++++++++++++++++++++++++ security/landlock/enforce.h | 18 ++ security/landlock/enforce_seccomp.c | 92 ++++++++++ 10 files changed, 480 insertions(+), 2 deletions(-) create mode 100644 include/linux/landlock.h create mode 100644 security/landlock/enforce.c create mode 100644 security/landlock/enforce.h create mode 100644 security/landlock/enforce_seccomp.c
include/linux/landlock.h new file +34 -0
@@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Landlock LSM - public kernel headers +* +* Copyright © 2016-2019 Mickaël Salaün <[email protected]> +* Copyright © 2018-2019 ANSSI +*/ + +#ifndef _LINUX_LANDLOCK_H +#define _LINUX_LANDLOCK_H + +#include <linux/errno.h> +#include <linux/sched.h> /* task_struct */ + +#if defined(CONFIG_SECCOMP_FILTER ) && defined(CONFIG_SECURITY_LANDLOCK ) +extern int landlock_seccomp_prepend_prog (unsigned int flags, +const int __user *user_bpf_fd); +extern void put_seccomp_landlock (struct task_struct *tsk); +extern void get_seccomp_landlock (struct task_struct *tsk); +#else /* CONFIG_SECCOMP_FILTER && CONFIG_SECURITY_LANDLOCK */ +static inline int landlock_seccomp_prepend_prog (unsigned int flags, +const int __user *user_bpf_fd) +{ +return -EINVAL ; +} +static inline void put_seccomp_landlock (struct task_struct *tsk) +{ +} +static inline void get_seccomp_landlock (struct task_struct *tsk) +{ +} +#endif /* CONFIG_SECCOMP_FILTER && CONFIG_SECURITY_LANDLOCK */ + +#endif /* _LINUX_LANDLOCK_H */
include/linux/seccomp.h +5 -0
@@ -11,6 +11,7 @@#ifdef CONFIG_SECCOMP +#include <linux/landlock.h> #include <linux/thread_info.h> #include <asm/seccomp.h>
@@ -22,6 +23,7 @@ struct seccomp_filter;* system calls available to a process. * @filter: must always point to a valid seccomp-filter or NULL as it is * accessed without locking during system call entry. +* @landlock_prog_set: contains a set of Landlock programs. * * @filter must only be accessed from the context of current as there * is no read locking.
@@ -29,6 +31,9 @@ struct seccomp_filter;struct seccomp {int mode;struct seccomp_filter *filter; +#if defined(CONFIG_SECCOMP_FILTER ) && defined(CONFIG_SECURITY_LANDLOCK ) +struct landlock_prog_set *landlock_prog_set; +#endif /* CONFIG_SECCOMP_FILTER && CONFIG_SECURITY_LANDLOCK */ };#ifdef CONFIG_HAVE_ARCH_SECCOMP_FILTER
include/uapi/linux/seccomp.h +1 -0
@@ -16,6 +16,7 @@#define SECCOMP_SET_MODE_FILTER 1#define SECCOMP_GET_ACTION_AVAIL 2#define SECCOMP_GET_NOTIF_SIZES 3 +#define SECCOMP_PREPEND_LANDLOCK_PROG 4/* Valid flags for SECCOMP_SET_MODE_FILTER */ #define SECCOMP_FILTER_FLAG_TSYNC (1UL << 0)
kernel/fork.c +7 -1
@@ -51,6 +51,7 @@#include <linux/security.h> #include <linux/hugetlb.h> #include <linux/seccomp.h> +#include <linux/landlock.h> #include <linux/swap.h> #include <linux/syscalls.h> #include <linux/jiffies.h>
@@ -454,6 +455,7 @@ void free_task(struct task_struct *tsk)rt_mutex_debug_task_free (tsk);ftrace_graph_exit_task (tsk);put_seccomp_filter (tsk); +put_seccomp_landlock (tsk);arch_release_task_struct (tsk);if (tsk->flags &PF_KTHREAD )free_kthread_struct (tsk);
@@ -884,7 +886,10 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)* the usage counts on the error path calling free_task. */ tsk->seccomp.filter =NULL ; -#endif +#ifdef CONFIG_SECURITY_LANDLOCK + tsk->seccomp.landlock_prog_set =NULL ; +#endif /* CONFIG_SECURITY_LANDLOCK */ +#endif /* CONFIG_SECCOMP */ setup_thread_stack (tsk, orig);clear_user_return_notifier (tsk);
@@ -1598,6 +1603,7 @@ static void copy_seccomp(struct task_struct *p)/* Ref-count the new filter user, and assign it. */ get_seccomp_filter (current); +get_seccomp_landlock (current); p->seccomp = current->seccomp;/*
kernel/seccomp.c +4 -0
@@ -41,6 +41,7 @@#include <linux/tracehook.h> #include <linux/uaccess.h> #include <linux/anon_inodes.h> +#include <linux/landlock.h> enum notify_state {SECCOMP_NOTIFY_INIT ,
@@ -1397,6 +1398,9 @@ static long do_seccomp(unsigned int op, unsigned int flags,return -EINVAL ;return seccomp_get_notif_sizes (uargs); +case SECCOMP_PREPEND_LANDLOCK_PROG : +return landlock_seccomp_prepend_prog (flags, + (const int __user *)uargs);default :return -EINVAL ; }
security/landlock/Makefile +2 -1
@@ -1,3 +1,4 @@ obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o -landlock-y := init.o +landlock-y := init.o \ + enforce.o enforce_seccomp.o
security/landlock/common.h +45 -0
49 lines not on this page · raw message
security/landlock/enforce.c new file +272 -0
272 lines not on this page · raw message
security/landlock/enforce.h new file +18 -0
@@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - enforcing helpers headers +* +* Copyright © 2016-2019 Mickaël Salaün <[email protected]> +* Copyright © 2018-2019 ANSSI +*/ + +#ifndef _SECURITY_LANDLOCK_ENFORCE_H +#define _SECURITY_LANDLOCK_ENFORCE_H + +struct landlock_prog_set *landlock_prepend_prog ( +struct landlock_prog_set *current_prog_set, +struct bpf_prog *prog); +void landlock_put_prog_set (struct landlock_prog_set *prog_set); +void landlock_get_prog_set (struct landlock_prog_set *prog_set); + +#endif /* _SECURITY_LANDLOCK_ENFORCE_H */
security/landlock/enforce_seccomp.c new file +92 -0
92 lines not on this page · raw message
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 5/10 bpf,landlock: Add a new map type: inode
In reply to Mickaël SalaünThis new map store arbitrary 64-bits values referenced by inode keys. The map can be updated from user space with file descriptor pointing to inodes tied to a file system. From an eBPF (Landlock) program point of view, such a map is read-only and can only be used to retrieved a 64-bits value tied to a given inode. This is useful to recognize an inode tagged by user space, without access right to this inode (i.e. no need to have a write access to this inode).
Add dedicated BPF functions to handle this type of map:
* bpf_inode_map_update_elem()
* bpf_inode_map_lookup_elem()
* bpf_inode_map_delete_elem()
---
Changes since v8:
* remove prog chaining and object tagging to ease review
* use bpf_map_init_from_attr()
Changes since v7:
* new design with a dedicated map and a BPF function to tie a value to an inode
* add the ability to set or get a tag on an inode from a Landlock program
Changes since v6:
* remove WARN_ON() for missing dentry->d_inode
* refactor bpf_landlock_func_proto() (suggested by Kees Cook)
Changes since v5:
* cosmetic fixes and rebase
Changes since v4:
* use a file abstraction (handle) to wrap inode, dentry, path and file structs
* remove bpf_landlock_cmp_fs_beneath()
* rename the BPF helper and move it to kernel/bpf/
* tighten helpers accessible by a Landlock rule
Changes since v3:
* remove bpf_landlock_cmp_fs_prop() (suggested by Alexei Starovoitov)
* add hooks dealing with struct inode and struct path pointers:
inode_permission and inode_getattr
* add abstraction over eBPF helper arguments thanks to wrapping structs
* add bpf_landlock_get_fs_mode() helper to check file type and mode
* merge WARN_ON() (suggested by Kees Cook)
* fix and update bpf_helpers.h
* use BPF_CALL_* for eBPF helpers (suggested by Alexei Starovoitov)
* make handle arraymap safe (RCU) and remove buggy synchronize_rcu()
* factor out the arraymay walk
* use size_t to index array (suggested by Jann Horn)
Changes since v2:
* add MNT_INTERNAL check to only add file handle from user-visible FS (e.g. no anonymous inode)
* replace struct file* with struct path* in map_landlock_handle
* add BPF protos
* fix bpf_landlock_cmp_fs_prop_with_struct_file()
--- include/linux/bpf.h | 9 + include/linux/bpf_types.h | 3 + include/uapi/linux/bpf.h | 12 +- kernel/bpf/Makefile | 3 + kernel/bpf/core.c | 2 + kernel/bpf/inodemap.c | 315 +++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 27 ++- kernel/bpf/verifier.c | 14 ++ tools/include/uapi/linux/bpf.h | 12 +- tools/lib/bpf/libbpf_probes.c | 1 + 10 files changed, 395 insertions(+), 3 deletions(-) create mode 100644 kernel/bpf/inodemap.c
include/linux/bpf.h +9 -0
@@ -208,6 +208,8 @@ enum bpf_arg_type {ARG_PTR_TO_INT ,/* pointer to int */ ARG_PTR_TO_LONG ,/* pointer to long */ ARG_PTR_TO_SOCKET ,/* pointer to bpf_sock (fullsock) */ + + ARG_PTR_TO_INODE, /* pointer to a struct inode */ };/* type of values returned from helper functions */
@@ -278,6 +280,7 @@ enum bpf_reg_type {PTR_TO_TCP_SOCK_OR_NULL ,/* reg points to struct tcp_sock or NULL */ PTR_TO_TP_BUFFER ,/* reg points to a writable raw tp's buffer */ PTR_TO_XDP_SOCK ,/* reg points to struct xdp_sock */ + PTR_TO_INODE, /* reg points to struct inode */ };/* The information passed from prog-specific *_is_valid_access
@@ -485,6 +488,7 @@ struct bpf_event_entry {struct rcu_head rcu; }; +bool bpf_prog_array_compatible (struct bpf_array *array,const struct bpf_prog *fp);int bpf_prog_calc_tag (struct bpf_prog *fp);
@@ -689,6 +693,10 @@ int bpf_fd_array_map_lookup_elem(struct bpf_map *map, void *key, u32 *value);int bpf_fd_htab_map_update_elem (struct bpf_map *map,struct file *map_file,void *key,void *value,u64 map_flags);int bpf_fd_htab_map_lookup_elem (struct bpf_map *map,void *key,u32 *value); +int bpf_inode_map_update_elem (struct bpf_map *map,int *key,u64 *value, +u64 flags); +int bpf_inode_map_lookup_elem (struct bpf_map *map,int *key,u64 *value); +int bpf_inode_map_delete_elem (struct bpf_map *map,int *key);int bpf_get_file_flag (int flags); int bpf_check_uarg_tail_zero(void __user *uaddr, size_t expected_size,
@@ -1059,6 +1067,7 @@ extern const struct bpf_func_proto bpf_spin_unlock_proto;extern const struct bpf_func_proto bpf_get_local_storage_proto;extern const struct bpf_func_proto bpf_strtol_proto;extern const struct bpf_func_proto bpf_strtoul_proto; +extern const struct bpf_func_proto bpf_inode_map_lookup_proto;/* Shared helpers among cBPF and eBPF. */ void bpf_user_rnd_init_once (void );
include/linux/bpf_types.h +3 -0
@@ -79,3 +79,6 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_REUSEPORT_SOCKARRAY, reuseport_array_ops)#endif BPF_MAP_TYPE(BPF_MAP_TYPE_QUEUE, queue_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_STACK, stack_map_ops) +#ifdef CONFIG_SECURITY_LANDLOCK +BPF_MAP_TYPE(BPF_MAP_TYPE_INODE, inode_ops) +#endif
include/uapi/linux/bpf.h +11 -1
@@ -134,6 +134,7 @@ enum bpf_map_type {BPF_MAP_TYPE_QUEUE ,BPF_MAP_TYPE_STACK ,BPF_MAP_TYPE_SK_STORAGE , + BPF_MAP_TYPE_INODE, };/* Note that tracing related programs such as
@@ -2716,6 +2717,14 @@ union bpf_attr {* **-EPERM** if no permission to send the *sig*. * * **-EAGAIN** if bpf program can try again. +* +* u64 bpf_inode_map_lookup(map, key) +* Description +* Perform a lookup in *map* for an entry associated to an inode +* *key*. +* Return +* Map value associated to *key*, or **NULL** if no entry was +* found. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -2827,7 +2836,8 @@ union bpf_attr {FN (strtoul), \FN (sk_storage_get), \FN (sk_storage_delete), \ -FN (send_signal), +FN (send_signal), \ +FN (inode_map_lookup),/* integer value in 'imm' field of BPF_CALL instruction selects which helper * function eBPF program intends to call
kernel/bpf/Makefile +3 -0
@@ -22,3 +22,6 @@ obj-$(CONFIG_CGROUP_BPF) += cgroup.o ifeq ($(CONFIG_INET),y) obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o endif +ifeq ($(CONFIG_SECURITY_LANDLOCK),y) +obj-$(CONFIG_BPF_SYSCALL) += inodemap.o +endif
kernel/bpf/core.c +2 -0
@@ -2032,6 +2032,8 @@ const struct bpf_func_proto bpf_get_current_comm_proto __weak;const struct bpf_func_proto bpf_get_current_cgroup_id_proto__weak ;const struct bpf_func_proto bpf_get_local_storage_proto__weak ; +const struct bpf_func_proto bpf_inode_map_update_proto__weak ; +const struct bpf_func_proto *__weak bpf_get_trace_printk_proto (void ) {return NULL ;
kernel/bpf/inodemap.c new file +315 -0
315 lines not on this page · raw message
kernel/bpf/syscall.c +26 -1
@@ -720,6 +720,22 @@ static void *__bpf_copy_key(void __user *ukey, u64 key_size)return NULL ; } +int __weak bpf_inode_map_update_elem (struct bpf_map *map,int *key, +u64 *value,u64 flags) +{ +return -ENOTSUPP ; +} + +int __weak bpf_inode_map_lookup_elem (struct bpf_map *map,int *key,u64 *value) +{ +return -ENOTSUPP ; +} + +int __weak bpf_inode_map_delete_elem (struct bpf_map *map,int *key) +{ +return -ENOTSUPP ; +} +/* last field in 'union bpf_attr' used by this command */ #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
@@ -801,6 +817,8 @@ static int map_lookup_elem(union bpf_attr *attr) }else if (map->map_type ==BPF_MAP_TYPE_QUEUE || map->map_type ==BPF_MAP_TYPE_STACK ) { err = map->ops->map_peek_elem (map, value); + }else if (map->map_type ==BPF_MAP_TYPE_INODE ) { + err =bpf_inode_map_lookup_elem (map, key, value); }else {rcu_read_lock ();if (map->ops->map_lookup_elem_sys_only)
@@ -951,6 +969,10 @@ static int map_update_elem(union bpf_attr *attr) }else if (map->map_type ==BPF_MAP_TYPE_QUEUE || map->map_type ==BPF_MAP_TYPE_STACK ) { err = map->ops->map_push_elem (map, value, attr->flags); + }else if (map->map_type ==BPF_MAP_TYPE_INODE ) { +rcu_read_lock (); + err =bpf_inode_map_update_elem (map, key, value, attr->flags); +rcu_read_unlock (); }else {rcu_read_lock (); err = map->ops->map_update_elem (map, key, value, attr->flags);
@@ -1006,7 +1028,10 @@ static int map_delete_elem(union bpf_attr *attr)preempt_disable ();__this_cpu_inc (bpf_prog_active);rcu_read_lock (); - err = map->ops->map_delete_elem (map, key); +if (map->map_type ==BPF_MAP_TYPE_INODE ) + err =bpf_inode_map_delete_elem (map, key); +else + err = map->ops->map_delete_elem (map, key);rcu_read_unlock ();__this_cpu_dec (bpf_prog_active);preempt_enable ();
kernel/bpf/verifier.c +14 -0
@@ -400,6 +400,7 @@ static const char * const reg_type_str[] = { [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null", [PTR_TO_TP_BUFFER] = "tp_buffer", [PTR_TO_XDP_SOCK] = "xdp_sock", + [PTR_TO_INODE] = "inode", };static char slot_type_char[] = {
@@ -1801,6 +1802,7 @@ static bool is_spillable_regtype(enum bpf_reg_type type)case PTR_TO_TCP_SOCK :case PTR_TO_TCP_SOCK_OR_NULL :case PTR_TO_XDP_SOCK : +case PTR_TO_INODE :return true;default :return false;
@@ -3254,6 +3256,10 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,verbose (env,"verifier internal error\n" );return -EFAULT ; } + }else if (arg_type ==ARG_PTR_TO_INODE ) { + expected_type =PTR_TO_INODE ; +if (type != expected_type) + goto err_type; }else if (arg_type_is_mem_ptr (arg_type)) { expected_type =PTR_TO_STACK ;/* One exception here. In case function allows for NULL to be
@@ -3462,6 +3468,10 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env, func_id != BPF_FUNC_sk_storage_delete) goto error;break ; +case BPF_MAP_TYPE_INODE : +if (func_id != BPF_FUNC_inode_map_lookup) + goto error; +break ;default :break ; }
@@ -3530,6 +3540,10 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env,if (map->map_type !=BPF_MAP_TYPE_SK_STORAGE ) goto error;break ; +case BPF_FUNC_inode_map_lookup: +if (map->map_type !=BPF_MAP_TYPE_INODE ) + goto error; +break ;default :break ; }
tools/include/uapi/linux/bpf.h +11 -1
@@ -134,6 +134,7 @@ enum bpf_map_type {BPF_MAP_TYPE_QUEUE ,BPF_MAP_TYPE_STACK ,BPF_MAP_TYPE_SK_STORAGE , + BPF_MAP_TYPE_INODE, };/* Note that tracing related programs such as
@@ -2716,6 +2717,14 @@ union bpf_attr {* **-EPERM** if no permission to send the *sig*. * * **-EAGAIN** if bpf program can try again. +* +* u64 bpf_inode_map_lookup(map, key) +* Description +* Perform a lookup in *map* for an entry associated to an inode +* *key*. +* Return +* Map value associated to *key*, or **NULL** if no entry was +* found. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -2827,7 +2836,8 @@ union bpf_attr {FN (strtoul), \FN (sk_storage_get), \FN (sk_storage_delete), \ -FN (send_signal), +FN (send_signal), \ +FN (inode_map_lookup),/* integer value in 'imm' field of BPF_CALL instruction selects which helper * function eBPF program intends to call
tools/lib/bpf/libbpf_probes.c +1 -0
@@ -249,6 +249,7 @@ bool bpf_probe_map_type(enum bpf_map_type map_type, __u32 ifindex)case BPF_MAP_TYPE_XSKMAP :case BPF_MAP_TYPE_SOCKHASH :case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY : +case BPF_MAP_TYPE_INODE :default :break ; }
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 6/10 landlock: Handle filesystem access control
In reply to Mickaël SalaünThis add two Landlock hooks: FS_WALK and FS_PICK.
The FS_WALK hook is used to walk through a file path. A program tied to this hook will be evaluated for each directory traversal except the last one if it is the leaf of the path. It is important to differentiate this hook from FS_PICK to enable more powerful path evaluation in the future (cf. Landlock patch v8).
The FS_PICK hook is used to validate a set of actions requested on a file. This actions are defined with triggers (e.g. read, write, open, append...).
The Landlock LSM hook registration is done after other LSM to only run actions from user-space, via eBPF programs, if the access was granted by major (privileged) LSMs.
---
Changes since v8:
* add a new LSM_ORDER_LAST, cf. commit e2bc445b66ca ("LSM: Introduce enum lsm_order")
* add WARN_ON() for pointer dereferencement
* remove the FS_GET subtype which rely on program chaining
* remove the subtype option which was only used for chaining (with the "previous" field)
* remove inode_lookup which depends on the (removed) nameidata security blob
* remove eBPF helpers to get and set Landlock inode tags
* do not use task LSM credentials (for now)
Changes since v7:
* major rewrite with clean Landlock hooks able to deal with file paths
Changes since v6:
* add 3 more sub-events: IOCTL, LOCK, FCNTL
https://lkml.kernel.org/r/[email protected]
* use the new security_add_hooks()
* explain the -Werror=unused-function
* constify pointers
* cleanup headers
Changes since v5:
* split hooks.[ch] into hooks.[ch] and hooks_fs.[ch]
* add more documentation
* cosmetic fixes
* rebase (SCALAR_VALUE)
Changes since v4:
* add LSM hook abstraction called Landlock event
* use the compiler type checking to verify hooks use by an event
* handle all filesystem related LSM hooks (e.g. file_permission,
mmap_file, sb_mount...)
* register BPF programs for Landlock just after LSM hooks registration
* move hooks registration after other LSMs
* add failsafes to check if a hook is not used by the kernel
* allow partial raw value access form the context (needed for programs generated by LLVM)
Changes since v3:
* split commit
* add hooks dealing with struct inode and struct path pointers:
inode_permission and inode_getattr
* add abstraction over eBPF helper arguments thanks to wrapping structs
--- include/linux/lsm_hooks.h | 1 + security/landlock/Makefile | 3 +- security/landlock/common.h | 10 + security/landlock/hooks.c | 95 ++++++ security/landlock/hooks.h | 31 ++ security/landlock/hooks_fs.c | 568 +++++++++++++++++++++++++++++++++++ security/landlock/hooks_fs.h | 31 ++ security/landlock/init.c | 47 +++ security/security.c | 15 + 9 files changed, 800 insertions(+), 1 deletion(-) create mode 100644 security/landlock/hooks.c create mode 100644 security/landlock/hooks.h create mode 100644 security/landlock/hooks_fs.c create mode 100644 security/landlock/hooks_fs.h
include/linux/lsm_hooks.h +1 -0
@@ -2092,6 +2092,7 @@ extern void security_add_hooks(struct security_hook_list *hooks, int count,enum lsm_order {LSM_ORDER_FIRST =-1 ,/* This is only for capabilities. */ LSM_ORDER_MUTABLE =0 , +LSM_ORDER_LAST =1 ,/* potentially-unprivileged LSM */ };struct lsm_info {
security/landlock/Makefile +2 -1
@@ -1,4 +1,5 @@ obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o landlock-y := init.o \ - enforce.o enforce_seccomp.o + enforce.o enforce_seccomp.o \ + hooks.o hooks_fs.o
security/landlock/common.h +10 -0
@@ -11,6 +11,7 @@#include <linux/bpf.h> /* enum bpf_prog_aux */ #include <linux/filter.h> /* bpf_prog */ +#include <linux/lsm_hooks.h> /* lsm_blob_sizes */ #include <linux/refcount.h> /* refcount_t */ #include <uapi/linux/landlock.h> /* enum landlock_hook_type */
@@ -68,4 +69,13 @@ static inline enum landlock_hook_type get_type(struct bpf_prog *prog) return prog->aux->extra->subtype.landlock_hook.type; } +__maybe_unused +static bool current_has_prog_type (enum landlock_hook_type hook_type) +{ +struct landlock_prog_set *prog_set; + + prog_set = current->seccomp.landlock_prog_set; +return (prog_set && prog_set->programs[get_index (hook_type)]); +} +#endif /* _SECURITY_LANDLOCK_COMMON_H */
security/landlock/hooks.c new file +95 -0
95 lines not on this page · raw message
security/landlock/hooks.h new file +31 -0
@@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - hooks helpers +* +* Copyright © 2016-2019 Mickaël Salaün <[email protected]> +* Copyright © 2018-2019 ANSSI +*/ + +#include <asm/current.h> +#include <linux/sched.h> /* struct task_struct */ +#include <linux/seccomp.h> + +#include "hooks_fs.h" + +struct landlock_hook_ctx { +union { +struct landlock_hook_ctx_fs_walk *fs_walk; +struct landlock_hook_ctx_fs_pick *fs_pick; + }; +}; + +static inline bool landlocked (const struct task_struct *task) +{ +#ifdef CONFIG_SECCOMP_FILTER +return !!(task->seccomp.landlock_prog_set); +#else +return false; +#endif /* CONFIG_SECCOMP_FILTER */ +} + +int landlock_decide (enum landlock_hook_type ,struct landlock_hook_ctx *,u64 );
security/landlock/hooks_fs.c new file +568 -0
568 lines not on this page · raw message
security/landlock/hooks_fs.h new file +31 -0
@@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - filesystem hooks +* +* Copyright © 2017-2019 Mickaël Salaün <[email protected]> +* Copyright © 2018-2019 ANSSI +*/ + +#include <linux/bpf.h> /* enum bpf_access_type */ + +__init void landlock_add_hooks_fs (void ); + +/* fs_pick */ + +struct landlock_hook_ctx_fs_pick ; + +bool landlock_is_valid_access_fs_pick (int off,enum bpf_access_type type, +enum bpf_reg_type *reg_type,int *max_size); + +const struct landlock_ctx_fs_pick *landlock_get_ctx_fs_pick ( +const struct landlock_hook_ctx_fs_pick *hook_ctx); + +/* fs_walk */ + +struct landlock_hook_ctx_fs_walk ; + +bool landlock_is_valid_access_fs_walk (int off,enum bpf_access_type type, +enum bpf_reg_type *reg_type,int *max_size); + +const struct landlock_ctx_fs_walk *landlock_get_ctx_fs_walk ( +const struct landlock_hook_ctx_fs_walk *hook_ctx);
security/landlock/init.c +47 -0
70 lines not on this page · raw message
security/security.c +15 -0
@@ -263,6 +263,21 @@ static void __init ordered_lsm_parse(const char *order, const char *origin) } } +/* +* In case of an unprivileged access-control, we don't want to give the +* ability to any process to do some checks (e.g. through an eBPF +* program) on kernel objects (e.g. files) if a privileged security +* policy forbid their access. We must then load +* potentially-unprivileged security modules after all other LSMs. +* +* LSM_ORDER_LAST is always last and does not appear in the modifiable +* ordered list of enabled LSMs. +*/ +for (lsm = __start_lsm_info; lsm < __end_lsm_info; lsm++) { +if (lsm->order ==LSM_ORDER_LAST ) +append_ordered_lsm (lsm,"last" ); + } +/* Disable all LSMs not in the ordered list. */ for (lsm = __start_lsm_info; lsm < __end_lsm_info; lsm++) {if (exists_ordered_lsm (lsm))
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 7/10 landlock: Add ptrace restrictions
In reply to Mickaël SalaünA landlocked process has less privileges than a non-landlocked process and must then be subject to additional restrictions when manipulating processes. To be allowed to use ptrace(2) and related syscalls on a target process, a landlocked process must have a subset of the target process' rules.
---
Changes since v6:
* factor out ptrace check
* constify pointers
* cleanup headers
* use the new security_add_hooks()
--- security/landlock/Makefile | 2 +- security/landlock/hooks_ptrace.c | 121 +++++++++++++++++++++++++++++++ security/landlock/hooks_ptrace.h | 8 ++ security/landlock/init.c | 2 + 4 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 security/landlock/hooks_ptrace.c create mode 100644 security/landlock/hooks_ptrace.h
security/landlock/Makefile +1 -1
@@ -2,4 +2,4 @@ obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o landlock-y := init.o \ enforce.o enforce_seccomp.o \ - hooks.o hooks_fs.o + hooks.o hooks_fs.o hooks_ptrace.o
security/landlock/hooks_ptrace.c new file +121 -0
121 lines not on this page · raw message
security/landlock/hooks_ptrace.h new file +8 -0
@@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - ptrace hooks +* +* Copyright © 2017 Mickaël Salaün <[email protected]> +*/ + +__init void landlock_add_hooks_ptrace (void );
security/landlock/init.c +2 -0
@@ -13,6 +13,7 @@#include "common.h" /* LANDLOCK_* */ #include "hooks_fs.h" +#include "hooks_ptrace.h" static bool bpf_landlock_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog,
@@ -143,6 +144,7 @@ const struct bpf_prog_ops landlock_prog_ops = {};static int __init landlock_init (void ) {pr_info (LANDLOCK_NAME ": Initializing (sandbox with seccomp)\n" ); +landlock_add_hooks_ptrace ();landlock_add_hooks_fs ();return 0 ; }
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 8/10 bpf: Add a Landlock sandbox example
In reply to Mickaël SalaünAdd a basic sandbox tool to launch a command which is denied access to a list of files and directories.
Add to the bpf_load library the ability to handle a BPF program subtype.
---
Changes since v8:
* rewrite the landlock1 sample which deny access to a set of files or directories (i.e. simple blacklist) to fit with the previous patches
* add "landlock1" to .gitignore
* in bpf_load.c, pass the subtype with a call to bpf_load_program_xattr()
Changes since v7:
* rewrite the example using an inode map
* add to bpf_load the ability to handle subtypes per program type
Changes since v6:
* check return value of load_and_attach()
* allow to write on pipes
* rename BPF_PROG_TYPE_LANDLOCK to BPF_PROG_TYPE_LANDLOCK_RULE
* rename Landlock version to ABI to better reflect its purpose
* use const variable (suggested by Kees Cook)
* remove useless definitions (suggested by Kees Cook)
* add detailed explanations (suggested by Kees Cook)
Changes since v5:
* cosmetic fixes
* rebase
Changes since v4:
* write Landlock rule in C and compiled it with LLVM
* remove cgroup handling
* remove path handling: only handle a read-only environment
* remove errno return codes
Changes since v3:
* remove seccomp and origin field: completely free from seccomp programs
* handle more FS-related hooks
* handle inode hooks and directory traversal
* add faked but consistent view thanks to ENOENT
* add /lib64 in the example
* fix spelling
* rename some types and definitions (e.g. SECCOMP_ADD_LANDLOCK_RULE)
Changes since v2:
* use BPF_PROG_ATTACH for cgroup handling
--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 3 + samples/bpf/bpf_load.c | 76 ++++++++++++++++- samples/bpf/bpf_load.h | 7 ++ samples/bpf/landlock1.h | 8 ++ samples/bpf/landlock1_kern.c | 104 +++++++++++++++++++++++ samples/bpf/landlock1_user.c | 157 +++++++++++++++++++++++++++++++++++ 7 files changed, 352 insertions(+), 4 deletions(-) create mode 100644 samples/bpf/landlock1.h create mode 100644 samples/bpf/landlock1_kern.c create mode 100644 samples/bpf/landlock1_user.c
samples/bpf/.gitignore +1 -0
@@ -2,6 +2,7 @@ cpustat fds_example hbm ibumad +landlock1 lathist lwt_len_hist map_perf_test
samples/bpf/Makefile +3 -0
@@ -53,6 +53,7 @@ hostprogs-y += task_fd_query hostprogs-y += xdp_sample_pkts hostprogs-y += ibumad hostprogs-y += hbm +hostprogs-y += landlock1 # Libbpf dependencies LIBBPF = $(TOOLS_PATH)/lib/bpf/libbpf.a
@@ -109,6 +110,7 @@ task_fd_query-objs := bpf_load.o task_fd_query_user.o $(TRACE_HELPERS) xdp_sample_pkts-objs := xdp_sample_pkts_user.o $(TRACE_HELPERS) ibumad-objs := bpf_load.o ibumad_user.o $(TRACE_HELPERS) hbm-objs := bpf_load.o hbm.o $(CGROUP_HELPERS) +landlock1-objs := bpf_load.o landlock1_user.o # Tell kbuild to always build the programs always := $(hostprogs-y)
@@ -168,6 +170,7 @@ always += task_fd_query_kern.o always += xdp_sample_pkts_kern.o always += ibumad_kern.o always += hbm_out_kern.o +always += landlock1_kern.o KBUILD_HOSTCFLAGS += -I$(objtree)/usr/include KBUILD_HOSTCFLAGS += -I$(srctree)/tools/lib/bpf/
samples/bpf/bpf_load.c +72 -4
136 lines not on this page · raw message
samples/bpf/bpf_load.h +7 -0
@@ -24,6 +24,13 @@ struct bpf_map_data {struct bpf_load_map_def def; }; +struct bpf_subtype_data { +char *name; +int prog_id; +int prog_fd; +union bpf_prog_subtype subtype; +}; +typedef void (*fixup_map_cb )(struct bpf_map_data *map,int idx);extern int prog_fd[MAX_PROGS ];
samples/bpf/landlock1.h new file +8 -0
@@ -0,0 +1,8 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Landlock sample 1 - common header +* +* Copyright © 2018-2019 Mickaël Salaün <[email protected]> +*/ + +#define MAP_FLAG_DENY (1ULL << 0)
samples/bpf/landlock1_kern.c new file +104 -0
104 lines not on this page · raw message
samples/bpf/landlock1_user.c new file +157 -0
157 lines not on this page · raw message
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 9/10 bpf,landlock: Add tests for Landlock
In reply to Mickaël SalaünTest basic context access, ptrace protection and filesystem hooks.
---
Changes since v8:
* update eBPF include path for macros
* use TEST_GEN_PROGS and use the generic "clean" target
* add more verbose errors
* update the bpf/verifier files
* remove chain tests (from landlock and bpf/verifier)
* replace the whitelist tests with blacklist tests (because of stateless Landlock programs): remove "dotdot" tests and other depth tests
* sync the landlock Makefile with its bpf sibling directory and use bpf_load_program_xattr()
Changes since v7:
* update tests and add new ones for filesystem hierarchy and Landlock chains.
Changes since v6:
* use the new kselftest_harness.h
* use const variables
* replace ASSERT_STEP with ASSERT_*
* rename BPF_PROG_TYPE_LANDLOCK to BPF_PROG_TYPE_LANDLOCK_RULE
* force sample library rebuild
* fix install target
Changes since v5:
* add subtype test
* add ptrace tests
* split and rename files
* cleanup and rebase
--- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/bpf/bpf_helpers.h | 2 + tools/testing/selftests/bpf/test_verifier.c | 1 + .../testing/selftests/bpf/verifier/landlock.c | 35 +++ .../testing/selftests/bpf/verifier/subtype.c | 10 + tools/testing/selftests/landlock/.gitignore | 4 + tools/testing/selftests/landlock/Makefile | 39 +++ tools/testing/selftests/landlock/test.h | 48 ++++ tools/testing/selftests/landlock/test_base.c | 24 ++ tools/testing/selftests/landlock/test_fs.c | 257 ++++++++++++++++++ .../testing/selftests/landlock/test_ptrace.c | 154 +++++++++++ 11 files changed, 575 insertions(+) create mode 100644 tools/testing/selftests/bpf/verifier/landlock.c create mode 100644 tools/testing/selftests/landlock/.gitignore create mode 100644 tools/testing/selftests/landlock/Makefile create mode 100644 tools/testing/selftests/landlock/test.h create mode 100644 tools/testing/selftests/landlock/test_base.c create mode 100644 tools/testing/selftests/landlock/test_fs.c create mode 100644 tools/testing/selftests/landlock/test_ptrace.c
tools/testing/selftests/Makefile +1 -0
@@ -21,6 +21,7 @@ TARGETS += ir TARGETS += kcmp TARGETS += kexec TARGETS += kvm +TARGETS += landlock TARGETS += lib TARGETS += livepatch TARGETS += membarrier
tools/testing/selftests/bpf/bpf_helpers.h +2 -0
@@ -225,6 +225,8 @@ static void *(*bpf_sk_storage_get)(void *map, struct bpf_sock *sk,static int (*bpf_sk_storage_delete)(void *map,struct bpf_sock *sk) = (void *)BPF_FUNC_sk_storage_delete;static int (*bpf_send_signal)(unsigned sig) = (void *)BPF_FUNC_send_signal; +static unsigned long long (*bpf_inode_map_lookup)(void *map,void *key) = + (void *) BPF_FUNC_inode_map_lookup;/* llvm builtin functions that eBPF C program may use to * emit BPF_LD_ABS and BPF_LD_IND instructions
tools/testing/selftests/bpf/test_verifier.c +1 -0
@@ -30,6 +30,7 @@#include <linux/bpf.h> #include <linux/if_ether.h> #include <linux/btf.h> +#include <linux/landlock.h> #include <bpf/bpf.h> #include <bpf/libbpf.h>
tools/testing/selftests/bpf/verifier/landlock.c new file +35 -0
@@ -0,0 +1,35 @@ +{ + "landlock/fs_pick: always accept", + .insns = { +BPF_MOV32_IMM (BPF_REG_0 ,0 ), + BPF_EXIT_INSN(), + }, + .result =ACCEPT , + .prog_type = BPF_PROG_TYPE_LANDLOCK_HOOK, + .has_prog_subtype = true, + .prog_subtype = { + .landlock_hook = { + .type =LANDLOCK_HOOK_FS_PICK , + .triggers = LANDLOCK_TRIGGER_FS_PICK_READ, + } + }, +}, +{ +"landlock/fs_pick: read context" , + .insns = { +BPF_MOV64_REG (BPF_REG_6 ,BPF_REG_1 ), +BPF_LDX_MEM (BPF_DW ,BPF_REG_7 ,BPF_REG_6 , + offsetof(struct landlock_ctx_fs_pick , inode)), +BPF_MOV32_IMM (BPF_REG_0 ,0 ), + BPF_EXIT_INSN(), + }, + .result =ACCEPT , + .prog_type = BPF_PROG_TYPE_LANDLOCK_HOOK, + .has_prog_subtype = true, + .prog_subtype = { + .landlock_hook = { + .type =LANDLOCK_HOOK_FS_PICK , + .triggers = LANDLOCK_TRIGGER_FS_PICK_READ, + } + }, +},
tools/testing/selftests/bpf/verifier/subtype.c +10 -0
@@ -8,3 +8,13 @@ .result = REJECT, .has_prog_subtype = true, }, +{ + "missing subtype", + .insns = { +BPF_MOV32_IMM (BPF_REG_0 ,0 ), + BPF_EXIT_INSN(), + }, + .errstr ="" , + .result = REJECT, + .prog_type = BPF_PROG_TYPE_LANDLOCK_HOOK, +},
tools/testing/selftests/landlock/.gitignore new file +4 -0
@@ -0,0 +1,4 @@ +/test_base +/test_fs +/test_ptrace +/tmp_*
tools/testing/selftests/landlock/Makefile new file +39 -0
@@ -0,0 +1,39 @@ +LIBDIR := ../../../lib +BPFDIR := $(LIBDIR)/bpf +APIDIR := ../../../include/uapi +GENDIR := ../../../../include/generated +GENHDR := $(GENDIR)/autoconf.h + +ifneq ($(wildcard $(GENHDR)),) + GENFLAGS := -DHAVE_GENHDR +endif + +BPFOBJS := $(BPFDIR)/bpf.o $(BPFDIR)/nlattr.o +LOADOBJ := ../../../../samples/bpf/bpf_load.o + +CFLAGS += -Wl,-no-as-needed -Wall -O2 -I$(APIDIR) -I$(LIBDIR) -I$(BPFDIR) -I$(GENDIR) $(GENFLAGS) -I../../../include +LDFLAGS += -lelf + +test_src = $(wildcard test_*.c) + +test_objs := $(test_src:.c=) + +TEST_GEN_PROGS := $(test_objs) + +.PHONY: all clean force + +all: $(test_objs) + +# force a rebuild of BPFOBJS when its dependencies are updated +force: + +# rebuild bpf.o as a workaround for the samples/bpf bug +$(BPFOBJS): $(LOADOBJ) force + $(MAKE) -C $(BPFDIR) + +$(LOADOBJ): force + $(MAKE) -C $(dir $(LOADOBJ)) + +$(test_objs): $(BPFOBJS) $(LOADOBJ) ../kselftest_harness.h + +include ../lib.mk
tools/testing/selftests/landlock/test.h new file +48 -0
48 lines not on this page · raw message
tools/testing/selftests/landlock/test_base.c new file +24 -0
@@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Landlock tests - base +* +* Copyright © 2017-2019 Mickaël Salaün <[email protected]> +*/ + +#define _GNU_SOURCE +#include <errno.h> + +#include "test.h" + +TEST (seccomp_landlock) +{ +int ret; + + ret =seccomp (SECCOMP_PREPEND_LANDLOCK_PROG ,0 ,NULL ); +EXPECT_EQ (-1 , ret); + EXPECT_EQ(EFAULT, errno) { +TH_LOG ("Kernel does not support CONFIG_SECURITY_LANDLOCK" ); + } +} + +TEST_HARNESS_MAIN
tools/testing/selftests/landlock/test_fs.c new file +257 -0
257 lines not on this page · raw message
tools/testing/selftests/landlock/test_ptrace.c new file +154 -0
154 lines not on this page · raw message
Signature · 1 line
2.20.1
Mickaël Salaün
maintainerPATCH v9 10/10 landlock: Add user and kernel documentation for Landlock
In reply to Mickaël SalaünThis documentation can be built with the Sphinx framework.
---
Changes since v8:
* remove documentation related to chaining and tagging according to this patch series
Changes since v7:
* update documentation according to the Landlock revamp
Changes since v6:
* add a check for ctx->event
* rename BPF_PROG_TYPE_LANDLOCK to BPF_PROG_TYPE_LANDLOCK_RULE
* rename Landlock version to ABI to better reflect its purpose and add a dedicated changelog section
* update tables
* relax no_new_privs recommendations
* remove ABILITY_WRITE related functions
* reword rule "appending" to "prepending" and explain it
* cosmetic fixes
Changes since v5:
* update the rule hierarchy inheritance explanation
* briefly explain ctx->arg2
* add ptrace restrictions
* explain EPERM
* update example (subtype)
* use ":manpage:"
--- Documentation/security/index.rst | 1 + Documentation/security/landlock/index.rst | 20 +++ Documentation/security/landlock/kernel.rst | 99 ++++++++++++++ Documentation/security/landlock/user.rst | 148 +++++++++++++++++++++ 4 files changed, 268 insertions(+) create mode 100644 Documentation/security/landlock/index.rst create mode 100644 Documentation/security/landlock/kernel.rst create mode 100644 Documentation/security/landlock/user.rst
Documentation/security/index.rst +1 -0
@@ -12,3 +12,4 @@ Security Documentation SCTP self-protection tpm/index + landlock/index
Documentation/security/landlock/index.rst new file +20 -0
@@ -0,0 +1,20 @@ +========================================= +Landlock LSM: programmatic access control +========================================= + +Landlock is a stackable Linux Security Module (LSM) that makes it possible to +create security sandboxes, programmable access-controls or safe endpoint +security agents. This kind of sandbox is expected to help mitigate the +security impact of bugs or unexpected/malicious behaviors in user-space +applications. The current version allows only a process with the global +CAP_SYS_ADMIN capability to create such sandboxes but the ultimate goal of +Landlock is to empower any process, including unprivileged ones, to securely +restrict themselves. Landlock is inspired by seccomp-bpf but instead of +filtering syscalls and their raw arguments, a Landlock rule can inspect the use +of kernel objects like files and hence make a decision according to the kernel +semantic. + +.. toctree:: + + user + kernel
Documentation/security/landlock/kernel.rst new file +99 -0
99 lines not on this page · raw message
Documentation/security/landlock/user.rst new file +148 -0
148 lines not on this page · raw message
Signature · 1 line
2.20.1
Al Viro
maintainerRe: [PATCH bpf-next v9 05/10] bpf,landlock: Add a new map type: inode
In reply to Mickaël Salaünkernel/bpf/inodemap.c line 44
Quoted 12 lines · Mickaël Salaün
kernel/bpf/inodemap.c new file +12
-0+/* must call iput(inode) after this call */ +static struct inode *inode_from_fd (int ufd,bool check_access) +{ +struct inode *ret; +struct fd f; +int deny; + + f =fdget (ufd); +if (unlikely (!f.file || !file_inode (f.file))) { + ret =ERR_PTR (-EBADF ); + goto put_fd; + }
Just when does one get a NULL file_inode()? The reason I'm asking is that arseloads of code would break if one managed to create such a beast...
Incidentally, that should be return ERR_PTR(-EBADF); fdput() is wrong there.
kernel/bpf/inodemap.c
Quoted 4 lines
kernel/bpf/inodemap.c new file +4
-0+ } +/* check if the FD is tied to a mount point */ +/* TODO: add this check when called from an eBPF program too */ + if (unlikely(!f.file->f_path.mnt
Again, the same question - when the hell can that happen? If you are sitting on an exploitable roothole, do share it...
|| f.file->f_path.mnt->mnt_flags &
kernel/bpf/inodemap.c line 56
Quoted 3 lines
kernel/bpf/inodemap.c new file +3
-0+ MNT_INTERNAL)) { + ret =ERR_PTR (-EINVAL ); + goto put_fd;
What does it have to do with mountpoints, anyway?
kernel/bpf/inodemap.c line 95
Quoted 12 lines
kernel/bpf/inodemap.c new file +12
-0+/* called from syscall */ +static int sys_inode_map_delete_elem (struct bpf_map *map,struct inode *key) +{ + struct inode_array *array = container_of(map, struct inode_array, map); +struct inode *inode; +int i; + +WARN_ON_ONCE (!rcu_read_lock_held ()); +for (i =0 ; i < array->map.max_entries; i++) { +if (array->elems[i].inode == key) { + inode =xchg (&array->elems[i].inode,NULL ); + array->nb_entries--;
Umm... Is that intended to be atomic in any sense?
Quoted 10 lines
kernel/bpf/inodemap.c new file +10
-0+iput (inode); +return 0 ; + } + } +return -ENOENT ; +} + +/* called from syscall */ +int bpf_inode_map_delete_elem (struct bpf_map *map,int *key) +{
kernel/bpf/inodemap.c line 115
Quoted 10 lines
kernel/bpf/inodemap.c new file +10
-0+struct inode *inode; +int err; + + inode =inode_from_fd (*key, false); +if (IS_ERR (inode)) +return PTR_ERR (inode); + err =sys_inode_map_delete_elem (map, inode); +iput (inode); +return err; +}
Wait a sec... So we have those beasties that can have long-term references to arbitrary inodes stuck in them? What will happen if you get umount(2) called while such a thing exists?
Re: [PATCH bpf-next v9 02/10] bpf: Add eBPF program subtype and is_valid_subtype() verifier
In reply to Mickaël SalaünQuoted 28 lines · Mickaël Salaün
The goal of the program subtype is to be able to have different static fine-grained verifications for a unique program type.
The struct
bpf_verifier_opsgets a new optional function:is_valid_subtype(). This new verifier is called at the beginning of the eBPF program verification to check if the (optional) program subtype is valid.The new helper
bpf_load_program_xattr()enables to verify a program with subtypes.For now, only Landlock eBPF programs are using a program subtype (see next commits) but this could be used by other program types in the future.
Signed-off-by Mickaël Salaün <[email protected]>Cc Alexei Starovoitov <[email protected]>Cc Daniel Borkmann <[email protected]>Cc David S. Miller <[email protected]>---
Changes since v8:
* usebpf_load_program_xattr()instead ofbpf_load_program()and addbpf_verify_program_xattr()to deal with subtypes
* removeput_extra()since there is no more "previous" field (for now)
Quoted 4 lines
Changes since v7:
* rename LANDLOCK_SUBTYPE_* to LANDLOCK_*
* move subtype inbpf_prog_auxand use only one bit forhas_subtype(suggested by Alexei Starovoitov)
sorry to say, but I don't think the landlock will ever land, since posting huge patches once a year is missing a lot of development that is happening during that time.
This 2/10 patch is an example.
subtype concept was useful 2 years ago when v6 was posted. Since then bpf developers faced very similar problem in other parts and it was solved with 'expected_attach_type' field.
See commit 5e43f899b03a ("bpf: Check attach type at prog load time") dated March 2018.
Mickaël Salaün
maintainerRe: [PATCH bpf-next v9 02/10] bpf: Add eBPF program subtype and is_valid_subtype() verifier
Quoted 29 lines · Alexei Starovoitov
Quoted 28 lines · Mickaël Salaün
The goal of the program subtype is to be able to have different static fine-grained verifications for a unique program type.
The struct
bpf_verifier_opsgets a new optional function:is_valid_subtype(). This new verifier is called at the beginning of the eBPF program verification to check if the (optional) program subtype is valid.The new helper
bpf_load_program_xattr()enables to verify a program with subtypes.For now, only Landlock eBPF programs are using a program subtype (see next commits) but this could be used by other program types in the future.
Signed-off-by Mickaël Salaün <[email protected]>Cc Alexei Starovoitov <[email protected]>Cc Daniel Borkmann <[email protected]>Cc David S. Miller <[email protected]>---
Changes since v8:
* usebpf_load_program_xattr()instead ofbpf_load_program()and addbpf_verify_program_xattr()to deal with subtypes
* removeput_extra()since there is no more "previous" field (for now)
Quoted 8 lines
Quoted 4 lines
Changes since v7:
* rename LANDLOCK_SUBTYPE_* to LANDLOCK_*
* move subtype inbpf_prog_auxand use only one bit forhas_subtype(suggested by Alexei Starovoitov)sorry to say, but I don't think the landlock will ever land, since posting huge patches once a year is missing a lot of development that is happening during that time.
You're right that it's been a while since the last patch set, but the main reasons behind this was a lack of feedback (probably because of the size of the patch set, which is now reduce to a consistent minimum), the rework needed to address everyone's concern (Landlock modify kernel components from different maintainers), and above all, the LSM stacking infrastructure which was quite beefy and then took some time to land:
https://lore.kernel.org/lkml/[email protected]/
This stacking infrastructure was required to have a useful version of Landlock (which is used as a use case example), and it was released with Linux v5.1 (last month). Now, I think everything is finally ready to move forward.
Quoted 6 lines
This 2/10 patch is an example.
subtype concept was useful 2 years ago when v6 was posted. Since then bpf developers faced very similar problem in other parts and it was solved with 'expected_attach_type' field.
See commit5e43f899b03a("bpf: Check attach type at prog load time") dated March 2018.
I saw this nice feature but I wasn't sure if it was the right field to use. Indeed, I need more than a "type", but also some values (triggers) as shown by this patch. What do you suggest?
Re: [PATCH bpf-next v9 05/10] bpf,landlock: Add a new map type: inode
In reply to Al ViroQuoted 17 lines · Al Viro
kernel/bpf/inodemap.c line 44
Quoted 12 lines · Mickaël Salaün
kernel/bpf/inodemap.c new file +12
-0+/* must call iput(inode) after this call */ +static struct inode *inode_from_fd (int ufd,bool check_access) +{ +struct inode *ret; +struct fd f; +int deny; + + f =fdget (ufd); +if (unlikely (!f.file || !file_inode (f.file))) { + ret =ERR_PTR (-EBADF ); + goto put_fd; + }Just when does one get a NULL
file_inode()? The reason I'm asking is that arseloads of code would break if one managed to create such a beast...
I didn't find any API documentation about this guarantee, so I followed a defensive programming approach. I'll remove the file_inode() check.
Quoted 2 lines
Incidentally, that should be return
ERR_PTR(-EBADF);fdput()is wrong there.
Right, I'll fix that.
Quoted 7 lines
kernel/bpf/inodemap.c
Quoted 5 lines
kernel/bpf/inodemap.c new file +4
-0+ } +/* check if the FD is tied to a mount point */ +/* TODO: add this check when called from an eBPF program too */ + if (unlikely(!f.file->f_path.mntAgain, the same question - when the hell can that happen?
Defensive programming again, I'll remove it.
Quoted 9 lines
If you are
sitting on an exploitable roothole, do share it...|| f.file->f_path.mnt->mnt_flags & > + MNT_INTERNAL)) { > + ret = ERR_PTR(-EINVAL); > + goto put_fd;What does it have to do with mountpoints, anyway?
I want to only manage inodes tied to a userspace-visible file system (this check may not be enough though). It doesn't make sense to be able to add inodes which are not mounted, to this kind of map.
Quoted 15 lines
kernel/bpf/inodemap.c line 95
Quoted 13 lines
kernel/bpf/inodemap.c new file +12
-0+/* called from syscall */ +static int sys_inode_map_delete_elem (struct bpf_map *map,struct inode *key) +{ + struct inode_array *array = container_of(map, struct inode_array, map); +struct inode *inode; +int i; + +WARN_ON_ONCE (!rcu_read_lock_held ()); +for (i =0 ; i < array->map.max_entries; i++) { +if (array->elems[i].inode == key) { + inode =xchg (&array->elems[i].inode,NULL ); + array->nb_entries--;Umm... Is that intended to be atomic in any sense?
nb_entries is not used as a bound check but to avoid walking uselessly through the (pre-allocated) array when adding a new element, but I'll use an atomic to avoid inconsistencies anyway.
Quoted 17 lines
Quoted 17 lines
kernel/bpf/inodemap.c new file +16
-0+iput (inode); +return 0 ; + } + } +return -ENOENT ; +} + +/* called from syscall */ +int bpf_inode_map_delete_elem (struct bpf_map *map,int *key) +{ +struct inode *inode; +int err; + + inode =inode_from_fd (*key, false); +if (IS_ERR (inode)) +return PTR_ERR (inode);
Quoted 8 lines
kernel/bpf/inodemap.c line 115
Quoted 4 lines
kernel/bpf/inodemap.c new file +4
-0+ err =sys_inode_map_delete_elem (map, inode); +iput (inode); +return err; +}Wait a sec... So we have those beasties that can have long-term references to arbitrary inodes stuck in them? What will happen if you get umount(2) called while such a thing exists?
I though an umount would be denied but no, we get a self-destructed busy inode and a bug!
What about wrapping the inode's superblock->s_op->destroy_inode() to first remove the element from the map and then call the real destroy_inode(), if any?
Or I could update fs/inode.c:destroy_inode() to call inode->free_inode() if it is set, and set it when such inode is referenced by a map? Or maybe I could hold the referencing file in the map and then wrap its f_op?
--
Mickaël Salaün
ANSSI/SDE/ST/LAM
Les données à caractère personnel recueillies et traitées dans le cadre de cet échange, le sont à seule fin d’exécution d’une relation professionnelle et s’opèrent dans cette seule finalité et pour la durée nécessaire à cette relation. Si vous souhaitez faire usage de vos droits de consultation, de rectification et de suppression de vos données, veuillez contacter [email protected]. Si vous avez reçu ce message par erreur, nous vous remercions d’en informer l’expéditeur et de détruire le message. The personal data collected and processed during this exchange aims solely at completing a business relationship and is limited to the necessary duration of that relationship. If you wish to use your rights of consultation, rectification and deletion of your data, please contact: [email protected]. If you have received this message in error, we thank you for informing the sender and destroying the message.
Al Viro
maintainerRe: [PATCH bpf-next v9 05/10] bpf,landlock: Add a new map type: inode
Quoted 24 lines · Mickaël Salaün
Quoted 6 lines
Quoted 6 lines
kernel/bpf/inodemap.c new file +6
-0+/* called from syscall */ +static int sys_inode_map_delete_elem (struct bpf_map *map,struct inode *key) +{ + struct inode_array *array = container_of(map, struct inode_array, map); +struct inode *inode; +int i;Quoted 8 lines
kernel/bpf/inodemap.c line 95
Quoted 6 lines
kernel/bpf/inodemap.c new file +6
-0+ +WARN_ON_ONCE (!rcu_read_lock_held ()); +for (i =0 ; i < array->map.max_entries; i++) { +if (array->elems[i].inode == key) { + inode =xchg (&array->elems[i].inode,NULL ); + array->nb_entries--;Umm... Is that intended to be atomic in any sense?
nb_entriesis not used as a bound check but to avoid walking uselessly through the (pre-allocated) array when adding a new element, but I'll use an atomic to avoid inconsistencies anyway.Quoted 3 lines
Wait a sec... So we have those beasties that can have long-term references to arbitrary inodes stuck in them? What will happen if you get umount(2) called while such a thing exists?
Quoted 5 lines
I though an umount would be denied but no, we get a self-destructed busy inode and a bug!
What about wrapping the inode'ssuperblock->s_op->destroy_inode()to first remove the element from the map and then call the realdestroy_inode(), if any?
What do you mean, _the_ map? I don't see anything to prevent insertion of references to the same inode into any number of those...
Quoted 4 lines
Or I could update fs/inode.c:destroy_inode() to call
inode->free_inode()if it is set, and set it when such inode is referenced by a map? Or maybe I could hold the referencing file in the map and then wrap itsf_op?
First of all, anything including the word "wrap" is a non-starter. We really don't need the headache associated with the locking needed to replace the method tables on the fly, or with the code checking that ->f_op points to given method table, etc. That's not going to fly, especially since you'd end up _chaining_ those (again, the same reference can go in more than once).
Nothing is allowed to change the method tables of live objects, period. Once a struct file is opened, its ->f_op is never going to change and it entirely belongs to the device driver or filesystem it resides on. Nothing else (not VFS, not VM, not some LSM module, etc.) has any business touching that. The same goes for inodes, dentries, etc.
What kind of behaviour do you want there? Do you want the inodes you've referenced there to be forgotten on e.g. memory pressure? The thing is, I don't see how "it's getting freed" could map onto any semantics that might be useful for you - it looks like the wrong event for that.
Re: [PATCH bpf-next v9 05/10] bpf,landlock: Add a new map type: inode
Quoted 26 lines · Al Viro
Quoted 24 lines · Mickaël Salaün
Quoted 6 lines
Quoted 6 lines
kernel/bpf/inodemap.c new file +6
-0+/* called from syscall */ +static int sys_inode_map_delete_elem (struct bpf_map *map,struct inode *key) +{ + struct inode_array *array = container_of(map, struct inode_array, map); +struct inode *inode; +int i;Quoted 8 lines
kernel/bpf/inodemap.c line 95
Quoted 6 lines
kernel/bpf/inodemap.c new file +6
-0+ +WARN_ON_ONCE (!rcu_read_lock_held ()); +for (i =0 ; i < array->map.max_entries; i++) { +if (array->elems[i].inode == key) { + inode =xchg (&array->elems[i].inode,NULL ); + array->nb_entries--;Umm... Is that intended to be atomic in any sense?
nb_entriesis not used as a bound check but to avoid walking uselessly through the (pre-allocated) array when adding a new element, but I'll use an atomic to avoid inconsistencies anyway.Quoted 3 lines
Wait a sec... So we have those beasties that can have long-term references to arbitrary inodes stuck in them? What will happen if you get umount(2) called while such a thing exists?
Quoted 8 lines
Quoted 5 lines
I though an umount would be denied but no, we get a self-destructed busy inode and a bug!
What about wrapping the inode'ssuperblock->s_op->destroy_inode()to first remove the element from the map and then call the realdestroy_inode(), if any?What do you mean, _the_ map? I don't see anything to prevent insertion of references to the same inode into any number of those...
Indeed, the current design needs to check for duplicate inode references to avoid unused entries (until a reference is removed). I was planning to use an rbtree but I'm working on using a hash table instead (cf. bpf/hashtab.c), which will solve the issue anyway.
Quoted 19 lines
Quoted 5 lines
Or I could update fs/inode.c:destroy_inode() to call
inode->free_inode()if it is set, and set it when such inode is referenced by a map? Or maybe I could hold the referencing file in the map and then wrap itsf_op?First of all, anything including the word "wrap" is a non-starter. We really don't need the headache associated with the locking needed to replace the method tables on the fly, or with the code checking that ->f_op points to given method table, etc. That's not going to fly, especially since you'd end up _chaining_ those (again, the same reference can go in more than once).
Nothing is allowed to change the method tables of live objects, period. Once a struct file is opened, its ->f_op is never going to change and it entirely belongs to the device driver or filesystem it resides on. Nothing else (not VFS, not VM, not some LSM module, etc.) has any business touching that. The same goes for inodes, dentries, etc.
Quoted 4 lines
What kind of behaviour do you want there? Do you want the inodes you've referenced there to be forgotten on e.g. memory pressure? The thing is, I don't see how "it's getting freed" could map onto any semantics that might be useful for you - it looks like the wrong event for that.
At least, I would like to be able to compare an inode with the reference one if this reference may be accessible somewhere on the system. Being able to keep the inode reference as long as its superblock is alive seems to solve the problem. This enable for example to compare inodes from two bind mounts of the same file system even if one mount point is unmounted.
Storing and using the device ID and the inode number bring a new problem when an inode is removed and when its number is recycled. However, if I can be notified when such an inode is removed (preferably without using an LSM hook) and if I can know when the backing device go out of the scope of the (live) system (e.g. hot unplugging an USB drive), this should solve the problem and also enable to keep a reference to an inode as long as possible without any dangling pointer nor wrapper.
--
Mickaël Salaün
ANSSI/SDE/ST/LAM
Les données à caractère personnel recueillies et traitées dans le cadre de cet échange, le sont à seule fin d’exécution d’une relation professionnelle et s’opèrent dans cette seule finalité et pour la durée nécessaire à cette relation. Si vous souhaitez faire usage de vos droits de consultation, de rectification et de suppression de vos données, veuillez contacter [email protected]. Si vous avez reçu ce message par erreur, nous vous remercions d’en informer l’expéditeur et de détruire le message. The personal data collected and processed during this exchange aims solely at completing a business relationship and is limited to the necessary duration of that relationship. If you wish to use your rights of consultation, rectification and deletion of your data, please contact: [email protected]. If you have received this message in error, we thank you for informing the sender and destroying the message.