Skip to contentSkip to conversation

Landlock LSM

PATCH Superseded Mickaël Salaün 4 participants 49 messages Mar 16, 2021 – Mar 25, 2021

Subsystems (24)
Documentation Arm (32-bit) x86 VFS +20 more subsystems

v30 of 34 Superseded Latest is v34 →

lore
Share & tools
lore

Mickaël Salaün

author maintainer
#0 lore raw

v30 cover Landlock LSM

Hi,

This patch series is mainly a rebase on top of v5.12-rc3 and a synchronization with the new mount_setattr(2). A light cleanup of hook_sb_delete() and new tests are also included.

The SLOC count is 1329 for security/landlock/ and 2556 for tools/testing/selftest/landlock/ . Test coverage for security/landlock/ is 93.6% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions. This series is being fuzzed by syzkaller (which may cover internal kernel errors), and patches are on their way: https://github.com/google/syzkaller/pull/2380

The compiled documentation is available here:
https://landlock.io/linux-doc/landlock-v30/userspace-api/landlock.html

This series can be applied on top of v5.12-rc3 . This can be tested with CONFIG_SECURITY_LANDLOCK, CONFIG_SAMPLE_LANDLOCK and by prepending "landlock," to CONFIG_LSM. This patch series can be found in a Git repository here:
https://github.com/landlock-lsm/linux/commits/landlock-v30
This patch series seems ready for upstream and I would really appreciate final reviews.

Landlock LSM
------------

The goal of Landlock is to enable to restrict ambient rights (e.g. global filesystem access) for a set of processes. Because Landlock is a stackable LSM [1], it makes possible to create safe security sandboxes as new security layers in addition to the existing system-wide access-controls. This kind of sandbox is expected to help mitigate the security impact of bugs or unexpected/malicious behaviors in user-space applications. Landlock empowers 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 restrict the use of kernel objects like file hierarchies, according to the kernel semantic. Landlock also takes inspiration from other OS sandbox mechanisms: XNU Sandbox, FreeBSD Capsicum or OpenBSD Pledge/Unveil.

In this current form, Landlock misses some access-control features. This enables to minimize this patch series and ease review. This series still addresses multiple use cases, especially with the combined use of
seccomp-bpf: applications with built-in sandboxing, init systems, security sandbox tools and security-oriented APIs [2].

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/

Previous versions:
v29: https://lore.kernel.org/lkml/[email protected]/
v28: https://lore.kernel.org/lkml/[email protected]/
v27: https://lore.kernel.org/lkml/[email protected]/
v26: https://lore.kernel.org/lkml/[email protected]/
v25: https://lore.kernel.org/lkml/[email protected]/
v24: https://lore.kernel.org/lkml/[email protected]/
v23: https://lore.kernel.org/lkml/[email protected]/
v22: https://lore.kernel.org/lkml/[email protected]/
v21: https://lore.kernel.org/lkml/[email protected]/
v20: https://lore.kernel.org/lkml/[email protected]/
v19: https://lore.kernel.org/lkml/[email protected]/
v18: https://lore.kernel.org/lkml/[email protected]/
v17: https://lore.kernel.org/lkml/[email protected]/
v16: https://lore.kernel.org/lkml/[email protected]/
v15: https://lore.kernel.org/lkml/[email protected]/
v14: https://lore.kernel.org/lkml/[email protected]/
v13: https://lore.kernel.org/lkml/[email protected]/
v12: https://lore.kernel.org/lkml/[email protected]/
v11: https://lore.kernel.org/lkml/[email protected]/
v10: https://lore.kernel.org/lkml/[email protected]/
v9: https://lore.kernel.org/lkml/[email protected]/
v8: https://lore.kernel.org/lkml/[email protected]/
v7: https://lore.kernel.org/lkml/[email protected]/
v6: https://lore.kernel.org/lkml/[email protected]/
v5: https://lore.kernel.org/lkml/[email protected]/
v4: https://lore.kernel.org/lkml/[email protected]/
v3: https://lore.kernel.org/lkml/[email protected]/
v2: https://lore.kernel.org/lkml/[email protected]/
v1: https://lore.kernel.org/kernel-hardening/[email protected]/

Casey Schaufler (1):
LSM: Infrastructure management of the superblock

Mickaël Salaün (11):
landlock: Add object management
landlock: Add ruleset and domain management
landlock: Set up the security framework and manage credentials
landlock: Add ptrace restrictions
fs,security: Add sb_delete hook
landlock: Support filesystem access-control
landlock: Add syscall implementations
arch: Wire up Landlock syscalls
selftests/landlock: Add user space tests samples/landlock: Add a sandbox manager example
landlock: Add user and kernel documentation

 Documentation/security/index.rst              |    1 +
 Documentation/security/landlock.rst           |   79 +
 Documentation/userspace-api/index.rst         |    1 +
 Documentation/userspace-api/landlock.rst      |  307 ++
 MAINTAINERS                                   |   15 +
 arch/Kconfig                                  |    7 +
 arch/alpha/kernel/syscalls/syscall.tbl        |    3 +
 arch/arm/tools/syscall.tbl                    |    3 +
 arch/arm64/include/asm/unistd.h               |    2 +-
 arch/arm64/include/asm/unistd32.h             |    6 +
 arch/ia64/kernel/syscalls/syscall.tbl         |    3 +
 arch/m68k/kernel/syscalls/syscall.tbl         |    3 +
 arch/microblaze/kernel/syscalls/syscall.tbl   |    3 +
 arch/mips/kernel/syscalls/syscall_n32.tbl     |    3 +
 arch/mips/kernel/syscalls/syscall_n64.tbl     |    3 +
 arch/mips/kernel/syscalls/syscall_o32.tbl     |    3 +
 arch/parisc/kernel/syscalls/syscall.tbl       |    3 +
 arch/powerpc/kernel/syscalls/syscall.tbl      |    3 +
 arch/s390/kernel/syscalls/syscall.tbl         |    3 +
 arch/sh/kernel/syscalls/syscall.tbl           |    3 +
 arch/sparc/kernel/syscalls/syscall.tbl        |    3 +
 arch/um/Kconfig                               |    1 +
 arch/x86/entry/syscalls/syscall_32.tbl        |    3 +
 arch/x86/entry/syscalls/syscall_64.tbl        |    3 +
 arch/xtensa/kernel/syscalls/syscall.tbl       |    3 +
 fs/super.c                                    |    1 +
 include/linux/lsm_hook_defs.h                 |    1 +
 include/linux/lsm_hooks.h                     |    4 +
 include/linux/security.h                      |    4 +
 include/linux/syscalls.h                      |    7 +
 include/uapi/asm-generic/unistd.h             |    8 +-
 include/uapi/linux/landlock.h                 |  128 +
 kernel/sys_ni.c                               |    5 +
 samples/Kconfig                               |    7 +
 samples/Makefile                              |    1 +
 samples/landlock/.gitignore                   |    1 +
 samples/landlock/Makefile                     |   13 +
 samples/landlock/sandboxer.c                  |  238 ++
 security/Kconfig                              |   11 +-
 security/Makefile                             |    2 +
 security/landlock/Kconfig                     |   21 +
 security/landlock/Makefile                    |    4 +
 security/landlock/common.h                    |   20 +
 security/landlock/cred.c                      |   46 +
 security/landlock/cred.h                      |   58 +
 security/landlock/fs.c                        |  687 ++++
 security/landlock/fs.h                        |   56 +
 security/landlock/limits.h                    |   21 +
 security/landlock/object.c                    |   67 +
 security/landlock/object.h                    |   91 +
 security/landlock/ptrace.c                    |  120 +
 security/landlock/ptrace.h                    |   14 +
 security/landlock/ruleset.c                   |  473 +++
 security/landlock/ruleset.h                   |  165 +
 security/landlock/setup.c                     |   40 +
 security/landlock/setup.h                     |   18 +
 security/landlock/syscalls.c                  |  445 +++
 security/security.c                           |   51 +-
 security/selinux/hooks.c                      |   58 +-
 security/selinux/include/objsec.h             |    6 +
 security/selinux/ss/services.c                |    3 +-
 security/smack/smack.h                        |    6 +
 security/smack/smack_lsm.c                    |   35 +-
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/landlock/.gitignore   |    2 +
 tools/testing/selftests/landlock/Makefile     |   24 +
 tools/testing/selftests/landlock/base_test.c  |  219 ++
 tools/testing/selftests/landlock/common.h     |  183 ++
 tools/testing/selftests/landlock/config       |    7 +
 tools/testing/selftests/landlock/fs_test.c    | 2792 +++++++++++++++++
 .../testing/selftests/landlock/ptrace_test.c  |  337 ++
 tools/testing/selftests/landlock/true.c       |    5 +
 72 files changed, 6896 insertions(+), 77 deletions(-)
 create mode 100644 Documentation/security/landlock.rst
 create mode 100644 Documentation/userspace-api/landlock.rst
 create mode 100644 include/uapi/linux/landlock.h
 create mode 100644 samples/landlock/.gitignore
 create mode 100644 samples/landlock/Makefile
 create mode 100644 samples/landlock/sandboxer.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/cred.c
 create mode 100644 security/landlock/cred.h
 create mode 100644 security/landlock/fs.c
 create mode 100644 security/landlock/fs.h
 create mode 100644 security/landlock/limits.h
 create mode 100644 security/landlock/object.c
 create mode 100644 security/landlock/object.h
 create mode 100644 security/landlock/ptrace.c
 create mode 100644 security/landlock/ptrace.h
 create mode 100644 security/landlock/ruleset.c
 create mode 100644 security/landlock/ruleset.h
 create mode 100644 security/landlock/setup.c
 create mode 100644 security/landlock/setup.h
 create mode 100644 security/landlock/syscalls.c
 create mode 100644 tools/testing/selftests/landlock/.gitignore
 create mode 100644 tools/testing/selftests/landlock/Makefile
 create mode 100644 tools/testing/selftests/landlock/base_test.c
 create mode 100644 tools/testing/selftests/landlock/common.h
 create mode 100644 tools/testing/selftests/landlock/config
 create mode 100644 tools/testing/selftests/landlock/fs_test.c
 create mode 100644 tools/testing/selftests/landlock/ptrace_test.c
 create mode 100644 tools/testing/selftests/landlock/true.c

base-commit: 1e28eed17697bcf343c6743f0028cc3b5dd88bf0

Signature · 1 line
2.30.2
author maintainer
#1 lore raw

PATCH v30 1/12 landlock: Add object management

From: Mickaël Salaün <[email protected]>

A Landlock object enables to identify a kernel object (e.g. an inode). A Landlock rule is a set of access rights allowed on an object. Rules are grouped in rulesets that may be tied to a set of processes (i.e. subjects) to enforce a scoped access-control (i.e. a domain).

Because Landlock's goal is to empower any process (especially unprivileged ones) to sandbox themselves, we cannot rely on a system-wide object identification such as file extended attributes. Indeed, we need innocuous, composable and modular access-controls.

The main challenge with these constraints is to identify kernel objects while this identification is useful (i.e. when a security policy makes use of this object). But this identification data should be freed once no policy is using it. This ephemeral tagging should not and may not be written in the filesystem. We then need to manage the lifetime of a rule according to the lifetime of its objects. To avoid a global lock, this implementation make use of RCU and counters to safely reference objects.

A following commit uses this generic object management for inodes.

---

Changes since v28:
* Improve Kconfig description (suggested by Serge Hallyn).
* Add Acked-by Serge Hallyn.
* Clean up comment.

Changes since v27:
* Update Kconfig for landlock_restrict_self(2).
* Cosmetic fixes: use 80 columns in Kconfig and align Makefile declarations.

Changes since v26:
* Update Kconfig for landlock_enforce_ruleset_self(2).
* Fix spelling.

Changes since v24:
* Fix typo in comment (spotted by Jann Horn).
* Add Reviewed-by: Jann Horn <[email protected]>

Changes since v23:
* Update landlock_create_object() to return error codes instead of NULL. This help error handling in callers.
* When using make oldconfig with a previous configuration already including the CONFIG_LSM variable, no question is asked to update its content. Update the Kconfig help to warn about LSM stacking configuration.
* Constify variable (spotted by Vincent Dagonneau).

Changes since v22:
* Fix spelling (spotted by Jann Horn).

Changes since v21:
* Update Kconfig help.
* Clean up comments.

Changes since v18:
* Account objects to kmemcg.

Changes since v14:
* Simplify the object, rule and ruleset management at the expense of a less aggressive memory freeing (contributed by Jann Horn, with additional modifications):
- Remove object->list aggregating the rules tied to an object.
- Remove landlock_get_object(), landlock_drop_object(), {get,put}_object_cleaner() and landlock_rule_is_disabled().
- Rewrite landlock_put_object() to use a more simple mechanism (no tricky RCU).
- Replace enum landlock_object_type and landlock_release_object() with

    landlock_object_underops->release()

- Adjust unions and Sparse annotations.
Cf. https://lore.kernel.org/lkml/CAG48ez21bEn0wL1bbmTiiu8j9jP5iEWtHOwz4tURUJ+ki0ydYw@mail.gmail.com/
* Merge struct landlock_rule into landlock_ruleset_elem to simplify the
rule management.
* Constify variables.
* Improve kernel documentation.
* Cosmetic variable renames.
* Remove the "default" in the Kconfig (suggested by Jann Horn).
* Only use refcount_inc() through getter helpers.
* Update Kconfig description.

Changes since v13:
* New dedicated implementation, removing the need for eBPF.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 MAINTAINERS                | 10 +++++
 security/Kconfig           |  1 +
 security/Makefile          |  2 +
 security/landlock/Kconfig  | 21 +++++++++
 security/landlock/Makefile |  3 ++
 security/landlock/object.c | 67 ++++++++++++++++++++++++++++
 security/landlock/object.h | 91 ++++++++++++++++++++++++++++++++++++++
 7 files changed, 195 insertions(+)
 create mode 100644 security/landlock/Kconfig
 create mode 100644 security/landlock/Makefile
 create mode 100644 security/landlock/object.c
 create mode 100644 security/landlock/object.h
MAINTAINERS +10 -0
index aa84121c5611..87a2738dfdec 100644
@@ -9997,6 +9997,16 @@ F:	net/core/sock_map.c
 F:	net/ipv4/tcp_bpf.c
 F:	net/ipv4/udp_bpf.c
 
+LANDLOCK SECURITY MODULE
+M:	Mickaël Salaün <[email protected]>
+L:	[email protected]
+S:	Supported
+W:	https://landlock.io
+T:	git https://github.com/landlock-lsm/linux.git
+F:	security/landlock/
+K:	landlock
+K:	LANDLOCK
+
 LANTIQ / INTEL Ethernet drivers
 M:	Hauke Mehrtens <[email protected]>
 L:	[email protected]
security/Kconfig +1 -0
index 7561f6f99f1d..15a4342b5d01 100644
@@ -238,6 +238,7 @@ source "security/loadpin/Kconfig"
 source "security/yama/Kconfig"
 source "security/safesetid/Kconfig"
 source "security/lockdown/Kconfig"
+source "security/landlock/Kconfig"
 
 source "security/integrity/Kconfig"
 
security/Makefile +2 -0
index 3baf435de541..47e432900e24 100644
@@ -13,6 +13,7 @@ subdir-$(CONFIG_SECURITY_LOADPIN)	+= loadpin
 subdir-$(CONFIG_SECURITY_SAFESETID)    += safesetid
 subdir-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown
 subdir-$(CONFIG_BPF_LSM)		+= bpf
+subdir-$(CONFIG_SECURITY_LANDLOCK)	+= landlock
 
 # always enable default capabilities
 obj-y					+= commoncap.o
@@ -32,6 +33,7 @@ obj-$(CONFIG_SECURITY_SAFESETID)       += safesetid/
 obj-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown/
 obj-$(CONFIG_CGROUPS)			+= device_cgroup.o
 obj-$(CONFIG_BPF_LSM)			+= bpf/
+obj-$(CONFIG_SECURITY_LANDLOCK)		+= landlock/
 
 # Object integrity file lists
 subdir-$(CONFIG_INTEGRITY)		+= integrity
security/landlock/Kconfig new file +21 -0
new file mode 100644
index 000000000000..c1e862a38410
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+config SECURITY_LANDLOCK
+	bool "Landlock support"
+	depends on SECURITY
+	select SECURITY_PATH
+	help
+	  Landlock is a sandboxing mechanism that enables processes to restrict
+	  themselves (and their future children) by gradually enforcing
+	  tailored access control policies.  A Landlock security policy is a
+	  set of access rights (e.g. open a file in read-only, make a
+	  directory, etc.) tied to a file hierarchy.  Such policy can be
+	  configured and enforced by any processes for themselves using the
+	  dedicated system calls: landlock_create_ruleset(),
+	  landlock_add_rule(), and landlock_restrict_self().
+
+	  See Documentation/userspace-api/landlock.rst for further information.
+
+	  If you are unsure how to answer this question, answer N.  Otherwise,
+	  you should also prepend "landlock," to the content of CONFIG_LSM to
+	  enable Landlock at boot time.
security/landlock/Makefile new file +3 -0
new file mode 100644
index 000000000000..cb6deefbf4c0
@@ -0,0 +1,3 @@
+obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
+
+landlock-y := object.o
security/landlock/object.c new file +67 -0

67 lines not on this page · raw message

security/landlock/object.h new file +91 -0

91 lines not on this page · raw message

Signature · 1 line
2.30.2
Reviewed-by on v30 1/12
#2 lore raw

Re: [PATCH v30 01/12] landlock: Add object management

Quoted 222 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

A Landlock object enables to identify a kernel object (e.g. an inode). A Landlock rule is a set of access rights allowed on an object. Rules are grouped in rulesets that may be tied to a set of processes (i.e. subjects) to enforce a scoped access-control (i.e. a domain).

Because Landlock's goal is to empower any process (especially unprivileged ones) to sandbox themselves, we cannot rely on a system-wide object identification such as file extended attributes. Indeed, we need innocuous, composable and modular access-controls.

The main challenge with these constraints is to identify kernel objects while this identification is useful (i.e. when a security policy makes use of this object). But this identification data should be freed once no policy is using it. This ephemeral tagging should not and may not be written in the filesystem. We then need to manage the lifetime of a rule according to the lifetime of its objects. To avoid a global lock, this implementation make use of RCU and counters to safely reference objects.

A following commit uses this generic object management for inodes.

---

Changes since v28:
* Improve Kconfig description (suggested by Serge Hallyn).
* Add Acked-by Serge Hallyn.
* Clean up comment.

Changes since v27:
* Update Kconfig for landlock_restrict_self(2).
* Cosmetic fixes: use 80 columns in Kconfig and align Makefile declarations.

Changes since v26:
* Update Kconfig for landlock_enforce_ruleset_self(2).
* Fix spelling.

Changes since v24:
* Fix typo in comment (spotted by Jann Horn).
* Add Reviewed-by: Jann Horn <[email protected]>

Changes since v23:
* Update landlock_create_object() to return error codes instead of NULL. This help error handling in callers.
* When using make oldconfig with a previous configuration already including the CONFIG_LSM variable, no question is asked to update its content. Update the Kconfig help to warn about LSM stacking configuration.
* Constify variable (spotted by Vincent Dagonneau).

Changes since v22:
* Fix spelling (spotted by Jann Horn).

Changes since v21:
* Update Kconfig help.
* Clean up comments.

Changes since v18:
* Account objects to kmemcg.

Changes since v14:
* Simplify the object, rule and ruleset management at the expense of a less aggressive memory freeing (contributed by Jann Horn, with additional modifications):
- Remove object->list aggregating the rules tied to an object.
- Remove landlock_get_object(), landlock_drop_object(), {get,put}_object_cleaner() and landlock_rule_is_disabled().
- Rewrite landlock_put_object() to use a more simple mechanism (no tricky RCU).
- Replace enum landlock_object_type and landlock_release_object() with

    landlock_object_underops->release()

- Adjust unions and Sparse annotations.
Cf. https://lore.kernel.org/lkml/CAG48ez21bEn0wL1bbmTiiu8j9jP5iEWtHOwz4tURUJ+ki0ydYw@mail.gmail.com/
* Merge struct landlock_rule into landlock_ruleset_elem to simplify the
rule management.
* Constify variables.
* Improve kernel documentation.
* Cosmetic variable renames.
* Remove the "default" in the Kconfig (suggested by Jann Horn).
* Only use refcount_inc() through getter helpers.
* Update Kconfig description.

Changes since v13:
* New dedicated implementation, removing the need for eBPF.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 MAINTAINERS                | 10 +++++
 security/Kconfig           |  1 +
 security/Makefile          |  2 +
 security/landlock/Kconfig  | 21 +++++++++
 security/landlock/Makefile |  3 ++
 security/landlock/object.c | 67 ++++++++++++++++++++++++++++
 security/landlock/object.h | 91 ++++++++++++++++++++++++++++++++++++++
 7 files changed, 195 insertions(+)
 create mode 100644 security/landlock/Kconfig
 create mode 100644 security/landlock/Makefile
 create mode 100644 security/landlock/object.c
 create mode 100644 security/landlock/object.h
MAINTAINERS +10 -0
index aa84121c5611..87a2738dfdec 100644
@@ -9997,6 +9997,16 @@ F:	net/core/sock_map.c
 F:	net/ipv4/tcp_bpf.c
 F:	net/ipv4/udp_bpf.c
 
+LANDLOCK SECURITY MODULE
+M:	Mickaël Salaün <[email protected]>
+L:	[email protected]
+S:	Supported
+W:	https://landlock.io
+T:	git https://github.com/landlock-lsm/linux.git
+F:	security/landlock/
+K:	landlock
+K:	LANDLOCK
+
 LANTIQ / INTEL Ethernet drivers
 M:	Hauke Mehrtens <[email protected]>
 L:	[email protected]
security/Kconfig +1 -0
index 7561f6f99f1d..15a4342b5d01 100644
@@ -238,6 +238,7 @@ source "security/loadpin/Kconfig"
 source "security/yama/Kconfig"
 source "security/safesetid/Kconfig"
 source "security/lockdown/Kconfig"
+source "security/landlock/Kconfig"
 
 source "security/integrity/Kconfig"
 
security/Makefile +2 -0
index 3baf435de541..47e432900e24 100644
@@ -13,6 +13,7 @@ subdir-$(CONFIG_SECURITY_LOADPIN)	+= loadpin
 subdir-$(CONFIG_SECURITY_SAFESETID)    += safesetid
 subdir-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown
 subdir-$(CONFIG_BPF_LSM)		+= bpf
+subdir-$(CONFIG_SECURITY_LANDLOCK)	+= landlock
 
 # always enable default capabilities
 obj-y					+= commoncap.o
@@ -32,6 +33,7 @@ obj-$(CONFIG_SECURITY_SAFESETID)       += safesetid/
 obj-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown/
 obj-$(CONFIG_CGROUPS)			+= device_cgroup.o
 obj-$(CONFIG_BPF_LSM)			+= bpf/
+obj-$(CONFIG_SECURITY_LANDLOCK)		+= landlock/
 
 # Object integrity file lists
 subdir-$(CONFIG_INTEGRITY)		+= integrity
security/landlock/Kconfig new file +21 -0
new file mode 100644
index 000000000000..c1e862a38410
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+config SECURITY_LANDLOCK
+	bool "Landlock support"
+	depends on SECURITY
+	select SECURITY_PATH
+	help
+	  Landlock is a sandboxing mechanism that enables processes to restrict
+	  themselves (and their future children) by gradually enforcing
+	  tailored access control policies.  A Landlock security policy is a
+	  set of access rights (e.g. open a file in read-only, make a
+	  directory, etc.) tied to a file hierarchy.  Such policy can be
+	  configured and enforced by any processes for themselves using the
+	  dedicated system calls: landlock_create_ruleset(),
+	  landlock_add_rule(), and landlock_restrict_self().
+
+	  See Documentation/userspace-api/landlock.rst for further information.
+
+	  If you are unsure how to answer this question, answer N.  Otherwise,
+	  you should also prepend "landlock," to the content of CONFIG_LSM to
+	  enable Landlock at boot time.
security/landlock/Makefile new file +3 -0
new file mode 100644
index 000000000000..cb6deefbf4c0
@@ -0,0 +1,3 @@
+obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
+
+landlock-y := object.o
security/landlock/object.c new file +18 -0
new file mode 100644
index 000000000000..d674fdf9ff04
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Landlock LSM - Object management
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#include <linux/bug.h>
+#include <linux/compiler_types.h>
+#include <linux/err.h>
+#include <linux/kernel.h>
+#include <linux/rcupdate.h>
+#include <linux/refcount.h>
+#include <linux/slab.h>
+#include <linux/spinlock.h>
+
+#include "object.h"

security/landlock/object.c line 28

Quoted 10 lines
security/landlock/object.c new file +10 -0
+
+struct landlock_object *landlock_create_object(
+		const struct landlock_object_underops *const underops,
+		void *const underobj)
+{
+	struct landlock_object *new_object;
+
+	if (WARN_ON_ONCE(!underops || !underobj))
+		return ERR_PTR(-ENOENT);
+	new_object = kzalloc(sizeof(*new_object), GFP_KERNEL_ACCOUNT);

Is there any benefit to using a dedicated kmem_cache instead of kmalloc? I see later that you end up with variable-sized allocations, so this might be fine as-is.

Quoted 139 lines
security/landlock/object.c new file +39 -0
+	if (!new_object)
+		return ERR_PTR(-ENOMEM);
+	refcount_set(&new_object->usage, 1);
+	spin_lock_init(&new_object->lock);
+	new_object->underops = underops;
+	new_object->underobj = underobj;
+	return new_object;
+}
+
+/*
+ * The caller must own the object (i.e. thanks to object->usage) to safely put
+ * it.
+ */
+void landlock_put_object(struct landlock_object *const object)
+{
+	/*
+	 * The call to @object->underops->release(object) might sleep, e.g.
+	 * because of iput().
+	 */
+	might_sleep();
+	if (!object)
+		return;
+
+	/*
+	 * If the @object's refcount cannot drop to zero, we can just decrement
+	 * the refcount without holding a lock. Otherwise, the decrement must
+	 * happen under @object->lock for synchronization with things like
+	 * get_inode_object().
+	 */
+	if (refcount_dec_and_lock(&object->usage, &object->lock)) {
+		__acquire(&object->lock);
+		/*
+		 * With @object->lock initially held, remove the reference from
+		 * @object->underobj to @object (if it still exists).
+		 */
+		object->underops->release(object);
+		kfree_rcu(object, rcu_free);
+	}
+}
security/landlock/object.h new file +91 -0
new file mode 100644
index 000000000000..3e5d5b6941c3
@@ -0,0 +1,91 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Object management
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_OBJECT_H
+#define _SECURITY_LANDLOCK_OBJECT_H
+
+#include <linux/compiler_types.h>
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+
+struct landlock_object;
+
+/**
+ * struct landlock_object_underops - Operations on an underlying object
+ */
+struct landlock_object_underops {
+	/**
+	 * @release: Releases the underlying object (e.g. iput() for an inode).
+	 */
+	void (*release)(struct landlock_object *const object)
+		__releases(object->lock);
+};
+
+/**
+ * struct landlock_object - Security blob tied to a kernel object
+ *
+ * The goal of this structure is to enable to tie a set of ephemeral access
+ * rights (pertaining to different domains) to a kernel object (e.g an inode)
+ * in a safe way.  This implies to handle concurrent use and modification.
+ *
+ * The lifetime of a &struct landlock_object depends of the rules referring to
+ * it.
+ */
+struct landlock_object {
+	/**
+	 * @usage: This counter is used to tie an object to the rules matching
+	 * it or to keep it alive while adding a new rule.  If this counter
+	 * reaches zero, this struct must not be modified, but this counter can
+	 * still be read from within an RCU read-side critical section.  When
+	 * adding a new rule to an object with a usage counter of zero, we must
+	 * wait until the pointer to this object is set to NULL (or recycled).
+	 */
+	refcount_t usage;
+	/**
+	 * @lock: Protects against concurrent modifications.  This lock must be
+	 * held from the time @usage drops to zero until any weak references
+	 * from @underobj to this object have been cleaned up.
+	 *
+	 * Lock ordering: inode->i_lock nests inside this.
+	 */
+	spinlock_t lock;
+	/**
+	 * @underobj: Used when cleaning up an object and to mark an object as
+	 * tied to its underlying kernel structure.  This pointer is protected
+	 * by @lock.  Cf. landlock_release_inodes() and release_inode().
+	 */
+	void *underobj;
+	union {
+		/**
+		 * @rcu_free: Enables lockless use of @usage, @lock and
+		 * @underobj from within an RCU read-side critical section.
+		 * @rcu_free and @underops are only used by
+		 * landlock_put_object().
+		 */
+		struct rcu_head rcu_free;
+		/**
+		 * @underops: Enables landlock_put_object() to release the
+		 * underlying object (e.g. inode).
+		 */
+		const struct landlock_object_underops *underops;
+	};
+};
+
+struct landlock_object *landlock_create_object(
+		const struct landlock_object_underops *const underops,
+		void *const underobj);
+
+void landlock_put_object(struct landlock_object *const object);
+
+static inline void landlock_get_object(struct landlock_object *const object)
+{
+	if (object)
+		refcount_inc(&object->usage);
+}
+
+#endif /* _SECURITY_LANDLOCK_OBJECT_H */
Signature · 1 line
2.30.2

Either way, this object lifetime management looks okay to me:

Signature · 1 line
Kees Cook
author maintainer
#3 lore raw

Re: [PATCH v30 01/12] landlock: Add object management

Quoted 229 lines · Kees Cook
Quoted 228 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

A Landlock object enables to identify a kernel object (e.g. an inode). A Landlock rule is a set of access rights allowed on an object. Rules are grouped in rulesets that may be tied to a set of processes (i.e. subjects) to enforce a scoped access-control (i.e. a domain).

Because Landlock's goal is to empower any process (especially unprivileged ones) to sandbox themselves, we cannot rely on a system-wide object identification such as file extended attributes. Indeed, we need innocuous, composable and modular access-controls.

The main challenge with these constraints is to identify kernel objects while this identification is useful (i.e. when a security policy makes use of this object). But this identification data should be freed once no policy is using it. This ephemeral tagging should not and may not be written in the filesystem. We then need to manage the lifetime of a rule according to the lifetime of its objects. To avoid a global lock, this implementation make use of RCU and counters to safely reference objects.

A following commit uses this generic object management for inodes.

---

Changes since v28:
* Improve Kconfig description (suggested by Serge Hallyn).
* Add Acked-by Serge Hallyn.
* Clean up comment.

Changes since v27:
* Update Kconfig for landlock_restrict_self(2).
* Cosmetic fixes: use 80 columns in Kconfig and align Makefile declarations.

Changes since v26:
* Update Kconfig for landlock_enforce_ruleset_self(2).
* Fix spelling.

Changes since v24:
* Fix typo in comment (spotted by Jann Horn).
* Add Reviewed-by: Jann Horn <[email protected]>

Changes since v23:
* Update landlock_create_object() to return error codes instead of NULL. This help error handling in callers.
* When using make oldconfig with a previous configuration already including the CONFIG_LSM variable, no question is asked to update its content. Update the Kconfig help to warn about LSM stacking configuration.
* Constify variable (spotted by Vincent Dagonneau).

Changes since v22:
* Fix spelling (spotted by Jann Horn).

Changes since v21:
* Update Kconfig help.
* Clean up comments.

Changes since v18:
* Account objects to kmemcg.

Changes since v14:
* Simplify the object, rule and ruleset management at the expense of a less aggressive memory freeing (contributed by Jann Horn, with additional modifications):
- Remove object->list aggregating the rules tied to an object.
- Remove landlock_get_object(), landlock_drop_object(), {get,put}_object_cleaner() and landlock_rule_is_disabled().
- Rewrite landlock_put_object() to use a more simple mechanism (no tricky RCU).
- Replace enum landlock_object_type and landlock_release_object() with

    landlock_object_underops->release()

- Adjust unions and Sparse annotations.
Cf. https://lore.kernel.org/lkml/CAG48ez21bEn0wL1bbmTiiu8j9jP5iEWtHOwz4tURUJ+ki0ydYw@mail.gmail.com/
* Merge struct landlock_rule into landlock_ruleset_elem to simplify the
rule management.
* Constify variables.
* Improve kernel documentation.
* Cosmetic variable renames.
* Remove the "default" in the Kconfig (suggested by Jann Horn).
* Only use refcount_inc() through getter helpers.
* Update Kconfig description.

Changes since v13:
* New dedicated implementation, removing the need for eBPF.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 MAINTAINERS                | 10 +++++
 security/Kconfig           |  1 +
 security/Makefile          |  2 +
 security/landlock/Kconfig  | 21 +++++++++
 security/landlock/Makefile |  3 ++
 security/landlock/object.c | 67 ++++++++++++++++++++++++++++
 security/landlock/object.h | 91 ++++++++++++++++++++++++++++++++++++++
 7 files changed, 195 insertions(+)
 create mode 100644 security/landlock/Kconfig
 create mode 100644 security/landlock/Makefile
 create mode 100644 security/landlock/object.c
 create mode 100644 security/landlock/object.h
MAINTAINERS +10 -0
index aa84121c5611..87a2738dfdec 100644
@@ -9997,6 +9997,16 @@ F:	net/core/sock_map.c
 F:	net/ipv4/tcp_bpf.c
 F:	net/ipv4/udp_bpf.c
 
+LANDLOCK SECURITY MODULE
+M:	Mickaël Salaün <[email protected]>
+L:	[email protected]
+S:	Supported
+W:	https://landlock.io
+T:	git https://github.com/landlock-lsm/linux.git
+F:	security/landlock/
+K:	landlock
+K:	LANDLOCK
+
 LANTIQ / INTEL Ethernet drivers
 M:	Hauke Mehrtens <[email protected]>
 L:	[email protected]
security/Kconfig +1 -0
index 7561f6f99f1d..15a4342b5d01 100644
@@ -238,6 +238,7 @@ source "security/loadpin/Kconfig"
 source "security/yama/Kconfig"
 source "security/safesetid/Kconfig"
 source "security/lockdown/Kconfig"
+source "security/landlock/Kconfig"
 
 source "security/integrity/Kconfig"
 
security/Makefile +2 -0
index 3baf435de541..47e432900e24 100644
@@ -13,6 +13,7 @@ subdir-$(CONFIG_SECURITY_LOADPIN)	+= loadpin
 subdir-$(CONFIG_SECURITY_SAFESETID)    += safesetid
 subdir-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown
 subdir-$(CONFIG_BPF_LSM)		+= bpf
+subdir-$(CONFIG_SECURITY_LANDLOCK)	+= landlock
 
 # always enable default capabilities
 obj-y					+= commoncap.o
@@ -32,6 +33,7 @@ obj-$(CONFIG_SECURITY_SAFESETID)       += safesetid/
 obj-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown/
 obj-$(CONFIG_CGROUPS)			+= device_cgroup.o
 obj-$(CONFIG_BPF_LSM)			+= bpf/
+obj-$(CONFIG_SECURITY_LANDLOCK)		+= landlock/
 
 # Object integrity file lists
 subdir-$(CONFIG_INTEGRITY)		+= integrity
security/landlock/Kconfig new file +21 -0
new file mode 100644
index 000000000000..c1e862a38410
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+config SECURITY_LANDLOCK
+	bool "Landlock support"
+	depends on SECURITY
+	select SECURITY_PATH
+	help
+	  Landlock is a sandboxing mechanism that enables processes to restrict
+	  themselves (and their future children) by gradually enforcing
+	  tailored access control policies.  A Landlock security policy is a
+	  set of access rights (e.g. open a file in read-only, make a
+	  directory, etc.) tied to a file hierarchy.  Such policy can be
+	  configured and enforced by any processes for themselves using the
+	  dedicated system calls: landlock_create_ruleset(),
+	  landlock_add_rule(), and landlock_restrict_self().
+
+	  See Documentation/userspace-api/landlock.rst for further information.
+
+	  If you are unsure how to answer this question, answer N.  Otherwise,
+	  you should also prepend "landlock," to the content of CONFIG_LSM to
+	  enable Landlock at boot time.
security/landlock/Makefile new file +3 -0
new file mode 100644
index 000000000000..cb6deefbf4c0
@@ -0,0 +1,3 @@
+obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
+
+landlock-y := object.o
security/landlock/object.c new file +24 -0
new file mode 100644
index 000000000000..d674fdf9ff04
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Landlock LSM - Object management
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#include <linux/bug.h>
+#include <linux/compiler_types.h>
+#include <linux/err.h>
+#include <linux/kernel.h>
+#include <linux/rcupdate.h>
+#include <linux/refcount.h>
+#include <linux/slab.h>
+#include <linux/spinlock.h>
+
+#include "object.h"
+
+struct landlock_object *landlock_create_object(
+		const struct landlock_object_underops *const underops,
+		void *const underobj)
+{
+	struct landlock_object *new_object;
Quoted 8 lines

security/landlock/object.c line 28

Quoted 4 lines
security/landlock/object.c new file +4 -0
+
+	if (WARN_ON_ONCE(!underops || !underobj))
+		return ERR_PTR(-ENOENT);
+	new_object = kzalloc(sizeof(*new_object), GFP_KERNEL_ACCOUNT);

Is there any benefit to using a dedicated kmem_cache instead of kmalloc? I see later that you end up with variable-sized allocations, so this might be fine as-is.

I though about that, but for the sake of simplicity I choose to not use that in this series. It may comes with a future update if there is a visible performance improvement though.

Quoted 145 lines
Quoted 140 lines
security/landlock/object.c new file +39 -0
+	if (!new_object)
+		return ERR_PTR(-ENOMEM);
+	refcount_set(&new_object->usage, 1);
+	spin_lock_init(&new_object->lock);
+	new_object->underops = underops;
+	new_object->underobj = underobj;
+	return new_object;
+}
+
+/*
+ * The caller must own the object (i.e. thanks to object->usage) to safely put
+ * it.
+ */
+void landlock_put_object(struct landlock_object *const object)
+{
+	/*
+	 * The call to @object->underops->release(object) might sleep, e.g.
+	 * because of iput().
+	 */
+	might_sleep();
+	if (!object)
+		return;
+
+	/*
+	 * If the @object's refcount cannot drop to zero, we can just decrement
+	 * the refcount without holding a lock. Otherwise, the decrement must
+	 * happen under @object->lock for synchronization with things like
+	 * get_inode_object().
+	 */
+	if (refcount_dec_and_lock(&object->usage, &object->lock)) {
+		__acquire(&object->lock);
+		/*
+		 * With @object->lock initially held, remove the reference from
+		 * @object->underobj to @object (if it still exists).
+		 */
+		object->underops->release(object);
+		kfree_rcu(object, rcu_free);
+	}
+}
security/landlock/object.h new file +91 -0
new file mode 100644
index 000000000000..3e5d5b6941c3
@@ -0,0 +1,91 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Object management
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_OBJECT_H
+#define _SECURITY_LANDLOCK_OBJECT_H
+
+#include <linux/compiler_types.h>
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+
+struct landlock_object;
+
+/**
+ * struct landlock_object_underops - Operations on an underlying object
+ */
+struct landlock_object_underops {
+	/**
+	 * @release: Releases the underlying object (e.g. iput() for an inode).
+	 */
+	void (*release)(struct landlock_object *const object)
+		__releases(object->lock);
+};
+
+/**
+ * struct landlock_object - Security blob tied to a kernel object
+ *
+ * The goal of this structure is to enable to tie a set of ephemeral access
+ * rights (pertaining to different domains) to a kernel object (e.g an inode)
+ * in a safe way.  This implies to handle concurrent use and modification.
+ *
+ * The lifetime of a &struct landlock_object depends of the rules referring to
+ * it.
+ */
+struct landlock_object {
+	/**
+	 * @usage: This counter is used to tie an object to the rules matching
+	 * it or to keep it alive while adding a new rule.  If this counter
+	 * reaches zero, this struct must not be modified, but this counter can
+	 * still be read from within an RCU read-side critical section.  When
+	 * adding a new rule to an object with a usage counter of zero, we must
+	 * wait until the pointer to this object is set to NULL (or recycled).
+	 */
+	refcount_t usage;
+	/**
+	 * @lock: Protects against concurrent modifications.  This lock must be
+	 * held from the time @usage drops to zero until any weak references
+	 * from @underobj to this object have been cleaned up.
+	 *
+	 * Lock ordering: inode->i_lock nests inside this.
+	 */
+	spinlock_t lock;
+	/**
+	 * @underobj: Used when cleaning up an object and to mark an object as
+	 * tied to its underlying kernel structure.  This pointer is protected
+	 * by @lock.  Cf. landlock_release_inodes() and release_inode().
+	 */
+	void *underobj;
+	union {
+		/**
+		 * @rcu_free: Enables lockless use of @usage, @lock and
+		 * @underobj from within an RCU read-side critical section.
+		 * @rcu_free and @underops are only used by
+		 * landlock_put_object().
+		 */
+		struct rcu_head rcu_free;
+		/**
+		 * @underops: Enables landlock_put_object() to release the
+		 * underlying object (e.g. inode).
+		 */
+		const struct landlock_object_underops *underops;
+	};
+};
+
+struct landlock_object *landlock_create_object(
+		const struct landlock_object_underops *const underops,
+		void *const underobj);
+
+void landlock_put_object(struct landlock_object *const object);
+
+static inline void landlock_get_object(struct landlock_object *const object)
+{
+	if (object)
+		refcount_inc(&object->usage);
+}
+
+#endif /* _SECURITY_LANDLOCK_OBJECT_H */
Signature · 1 line
2.30.2

Either way, this object lifetime management looks okay to me:

author maintainer
#4 lore raw

PATCH v30 2/12 landlock: Add ruleset and domain management

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

A Landlock ruleset is mainly a red-black tree with Landlock rules as nodes. This enables quick update and lookup to match a requested access, e.g. to a file. A ruleset is usable through a dedicated file descriptor (cf. following commit implementing syscalls) which enables a process to create and populate a ruleset with new rules.

A domain is a ruleset tied to a set of processes. This group of rules defines the security policy enforced on these processes and their future children. A domain can transition to a new domain which is the intersection of all its constraints and those of a ruleset provided by the current process. This modification only impact the current process. This means that a process can only gain more constraints (i.e. lose accesses) over time.

---

Changes since v28:
* Add Acked-by Serge Hallyn.
* Clean up comment.

Changes since v27:
* Fix domains with layers of non-overlapping access rights.
* Add stricter limit checks (same semantic).
* Change the grow direction of a rule layer stack to make it the same as the new ruleset fs_access_masks stack (cosmetic change).
* Cosmetic fix for a comment block.

Changes since v26:
* Fix spelling.

Changes since v25:
* Add build-time checks for the num_layers and num_rules variables according to LANDLOCK_MAX_NUM_LAYERS and LANDLOCK_MAX_NUM_RULES, and move these limits to a dedicated file.
* Cosmetic variable renames.

Changes since v24:
* Update struct landlock_rule with a layer stack. This reverts "Always intersect access rights" from v24 and also adds the ability to tie access rights with their policy layer. As noted by Jann Horn, always intersecting access rights made some use cases uselessly more difficult to handle in user space. Thanks to this new stack, we still have a deterministic policy behavior whatever their level in the stack of policies, while using a "union" of accesses when building a ruleset. The implementation use a FAM to keep the access checks quick and memory efficient (4 bytes per layer per inode). Update insert_rule() accordingly.

Changes since v23:
* Always intersect access rights. Following the filesystem change logic, make ruleset updates more consistent by always intersecting access rights (boolean AND) instead of combining them (boolean OR) for the same layer. This defensive approach could also help avoid user space to inadvertently allow multiple access rights for the same object (e.g. write and execute access on a path hierarchy) instead of dealing with such inconsistency. This can happen when there is no deduplication of objects (e.g. paths and underlying inodes) whereas they get different access rights with landlock_add_rule(2).
* Add extra checks to make sure that:
- there is always an (allocated) object in each used rules;
- when updating a ruleset with a new rule (i.e. not merging two rulesets), the ruleset doesn't contain multiple layers.
* Hide merge parameter from the public landlock_insert_rule() API. This helps avoid misuse of this function.
* Replace a remaining hardcoded 1 with SINGLE_DEPTH_NESTING.

Changes since v22:
* Explicitely use RB_ROOT and SINGLE_DEPTH_NESTING (suggested by Jann Horn).
* Improve comments and fix spelling (suggested by Jann Horn).

Changes since v21:
* Add and clean up comments.

Changes since v18:
* Account rulesets to kmemcg.
* Remove struct holes.
* Cosmetic changes.

Changes since v17:
* Move include/uapi/linux/landlock.h and _LANDLOCK_ACCESS_FS_* to a following patch.

Changes since v16:
* Allow enforcement of empty ruleset, which enables deny-all policies.

Changes since v15:
* Replace layer_levels and layer_depth with a bitfield of layers, cf. filesystem commit.
* Rename the LANDLOCK_ACCESS_FS_{UNLINK,RMDIR} with LANDLOCK_ACCESS_FS_REMOVE_{FILE,DIR} because it makes sense to use them for the action of renaming a file or a directory, which may lead to the removal of the source file or directory. Removes the LANDLOCK_ACCESS_FS_{LINK_TO,RENAME_FROM,RENAME_TO} which are now replaced with LANDLOCK_ACCESS_FS_REMOVE_{FILE,DIR} and LANDLOCK_ACCESS_FS_MAKE_* .
* Update the documentation accordingly and highlight how the access rights are taken into account.
* Change nb_rules from atomic_t to u32 because it is not use anymore by show_fdinfo().
* Add safeguard for level variables types.
* Check max number of rules.
* Replace struct landlock_access (self and beneath bitfields) with one bitfield.
* Remove useless variable.
* Add comments.

Changes since v14:
* Simplify the object, rule and ruleset management at the expense of a
less aggressive memory freeing (contributed by Jann Horn, with
additional modifications):
- Make a domain immutable (remove the opportunistic cleaning).
- Remove RCU pointers.
- Merge struct landlock_ref and struct landlock_ruleset_elem into
landlock_rule: get ride of rule's RCU.
- Adjust union.
- Remove the landlock_insert_rule() check about a new object with the
same address as a previously disabled one, because it is not
possible to disable a rule anymore.
Cf. https://lore.kernel.org/lkml/CAG48ez21bEn0wL1bbmTiiu8j9jP5iEWtHOwz4tURUJ+ki0ydYw@mail.gmail.com/
* Fix nested domains by implementing a notion of layer level and depth:
- Update landlock_insert_rule() to manage such layers.
- Add an inherit_ruleset() helper to properly create a new domain.
- Rename landlock_find_access() to landlock_find_rule() and return a
full rule reference.
- Add a layer_level and a layer_depth fields to struct landlock_rule.
- Add a top_layer_level field to struct landlock_ruleset.
* Remove access rights that may be required for FD-only requests:
truncate, getattr, lock, chmod, chown, chgrp, ioctl. This will be
handle in a future evolution of Landlock, but right now the goal is to
lighten the code to ease review.
* Remove LANDLOCK_ACCESS_FS_OPEN and rename
LANDLOCK_ACCESS_FS_{READ,WRITE} with a FILE suffix.
* Rename LANDLOCK_ACCESS_FS_READDIR to match the *_FILE pattern.
* Remove LANDLOCK_ACCESS_FS_MAP which was useless.
* Fix memory leak in put_hierarchy() (reported by Jann Horn).
* Fix user-after-free and rename free_ruleset() (reported by Jann Horn).
* Replace the for loops with rbtree_postorder_for_each_entry_safe().
* Constify variables.
* Only use refcount_inc() through getter helpers.
* Change Landlock_insert_ruleset_access() to
Landlock_insert_ruleset_rule().
* Rename landlock_put_ruleset_enqueue() to landlock_put_ruleset_deferred().
* Improve kernel documentation and add a warning about the unhandled
access/syscall families.
* Move ABI check to syscall.c .

Changes since v13:
* New implementation, inspired by the previous inode eBPF map, but agnostic to the underlying kernel object.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 security/landlock/Makefile  |   2 +-
 security/landlock/limits.h  |  17 ++
 security/landlock/ruleset.c | 469 ++++++++++++++++++++++++++++++++++++
 security/landlock/ruleset.h | 165 +++++++++++++
 4 files changed, 652 insertions(+), 1 deletion(-)
 create mode 100644 security/landlock/limits.h
 create mode 100644 security/landlock/ruleset.c
 create mode 100644 security/landlock/ruleset.h
security/landlock/Makefile +1 -1
index cb6deefbf4c0..d846eba445bb 100644
@@ -1,3 +1,3 @@
 obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
 
-landlock-y := object.o
+landlock-y := object.o ruleset.o
security/landlock/limits.h new file +17 -0
new file mode 100644
index 000000000000..b734f597bb0e
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Limits for different components
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_LIMITS_H
+#define _SECURITY_LANDLOCK_LIMITS_H
+
+#include <linux/limits.h>
+
+#define LANDLOCK_MAX_NUM_LAYERS		64
+#define LANDLOCK_MAX_NUM_RULES		U32_MAX
+
+#endif /* _SECURITY_LANDLOCK_LIMITS_H */
security/landlock/ruleset.c new file +469 -0

469 lines not on this page · raw message

security/landlock/ruleset.h new file +165 -0

165 lines not on this page · raw message

Signature · 1 line
2.30.2
Reviewed-by on v30 2/12
#5 lore raw

Re: [PATCH v30 02/12] landlock: Add ruleset and domain management

Quoted 16 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

A Landlock ruleset is mainly a red-black tree with Landlock rules as nodes. This enables quick update and lookup to match a requested access, e.g. to a file. A ruleset is usable through a dedicated file descriptor (cf. following commit implementing syscalls) which enables a process to create and populate a ruleset with new rules.

A domain is a ruleset tied to a set of processes. This group of rules defines the security policy enforced on these processes and their future children. A domain can transition to a new domain which is the intersection of all its constraints and those of a ruleset provided by the current process. This modification only impact the current process. This means that a process can only gain more constraints (i.e. lose accesses) over time.

Quoted 6 lines

(Aside: you appear to be self-adding your Link: tags -- AIUI, this is normally done by whoever pulls your series. I've only seen Link: tags added when needing to refer to something else not included in the series.)

security/landlock/ruleset.c line 111

Quoted 9 lines

[...]

security/landlock/ruleset.c new file +8 -0
+static void put_rule(struct landlock_rule *const rule)
+{
+	might_sleep();
+	if (!rule)
+		return;
+	landlock_put_object(rule->object);
+	kfree(rule);
+}

I'd expect this to be named "release" rather than "put" since it doesn't do any lifetime reference counting.

security/landlock/ruleset.c line 122

Quoted 10 lines
security/landlock/ruleset.c new file +10 -0
+static void build_check_ruleset(void)
+{
+	const struct landlock_ruleset ruleset = {
+		.num_rules = ~0,
+		.num_layers = ~0,
+	};
+
+	BUILD_BUG_ON(ruleset.num_rules < LANDLOCK_MAX_NUM_RULES);
+	BUILD_BUG_ON(ruleset.num_layers < LANDLOCK_MAX_NUM_LAYERS);
+}

This is checking that the largest possible stored value is correctly within the LANDLOCK_MAX_* macro value?

Quoted 1 line

[...]

The locking all looks right, and given your test coverage and syzkaller work, it's hard for me to think of ways to prove it out any better. :)

Signature · 1 line
Kees Cook
author maintainer
#6 lore raw

Re: [PATCH v30 02/12] landlock: Add ruleset and domain management

Quoted 24 lines · Kees Cook
Quoted 16 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

A Landlock ruleset is mainly a red-black tree with Landlock rules as nodes. This enables quick update and lookup to match a requested access, e.g. to a file. A ruleset is usable through a dedicated file descriptor (cf. following commit implementing syscalls) which enables a process to create and populate a ruleset with new rules.

A domain is a ruleset tied to a set of processes. This group of rules defines the security policy enforced on these processes and their future children. A domain can transition to a new domain which is the intersection of all its constraints and those of a ruleset provided by the current process. This modification only impact the current process. This means that a process can only gain more constraints (i.e. lose accesses) over time.

Quoted 6 lines
Quoted 4 lines

(Aside: you appear to be self-adding your Link: tags -- AIUI, this is normally done by whoever pulls your series. I've only seen Link: tags added when needing to refer to something else not included in the series.)

It is an insurance to not lose history. :)

Quoted 13 lines

security/landlock/ruleset.c line 111

Quoted 10 lines

[...]

security/landlock/ruleset.c new file +8 -0
+static void put_rule(struct landlock_rule *const rule)
+{
+	might_sleep();
+	if (!rule)
+		return;
+	landlock_put_object(rule->object);
+	kfree(rule);
+}

I'd expect this to be named "release" rather than "put" since it doesn't do any lifetime reference counting.

It does decrement rule->object->usage .

Quoted 14 lines

security/landlock/ruleset.c line 122

Quoted 11 lines
security/landlock/ruleset.c new file +10 -0
+static void build_check_ruleset(void)
+{
+	const struct landlock_ruleset ruleset = {
+		.num_rules = ~0,
+		.num_layers = ~0,
+	};
+
+	BUILD_BUG_ON(ruleset.num_rules < LANDLOCK_MAX_NUM_RULES);
+	BUILD_BUG_ON(ruleset.num_layers < LANDLOCK_MAX_NUM_LAYERS);
+}

This is checking that the largest possible stored value is correctly within the LANDLOCK_MAX_* macro value?

Yes, there is builtin checks for all Landlock limits.

Quoted 5 lines
Quoted 2 lines

[...]

The locking all looks right, and given your test coverage and syzkaller work, it's hard for me to think of ways to prove it out any better. :)

Thanks!

Quoted 4 lines
#7 lore raw

Re: [PATCH v30 02/12] landlock: Add ruleset and domain management

Quoted 15 lines · Mickaël Salaün
Quoted 13 lines · Kees Cook

security/landlock/ruleset.c line 111

Quoted 9 lines · Mickaël Salaün

[...]

security/landlock/ruleset.c new file +8 -0
+static void put_rule(struct landlock_rule *const rule)
+{
+	might_sleep();
+	if (!rule)
+		return;
+	landlock_put_object(rule->object);
+	kfree(rule);
+}

I'd expect this to be named "release" rather than "put" since it doesn't do any lifetime reference counting.

Quoted 1 line

It does decrement rule->object->usage .

Well, landlock_put_object() decrements rule->object's lifetime. It seems "rule" doesn't have a lifetime. (There is no refcounter on rule.) I just find it strange to see "put" without a matching "get". Not a big deal.

Signature · 1 line
Kees Cook
maintainer
#8 lore raw

Re: [PATCH v30 02/12] landlock: Add ruleset and domain management

In reply to Mickaël Salaün
Quoted 6 lines · Mickaël Salaün
Quoted 6 lines
Quoted 5 lines
Quoted 6 lines
Quoted 4 lines

(Aside: you appear to be self-adding your Link: tags -- AIUI, this is normally done by whoever pulls your series. I've only seen Link: tags added when needing to refer to something else not included in the series.)

It is an insurance to not lose history. :)

How will history be lost? The code is in the repo and discussions can easily be found by searching for subjects or message IDs.

Is anyone else doing this self linking?

Signature · 2 lines
James Morris
<[email protected]>
author maintainer
#9 lore raw

Re: [PATCH v30 02/12] landlock: Add ruleset and domain management

Quoted 13 lines · James Morris
Quoted 11 lines · Mickaël Salaün
Quoted 10 lines
Quoted 5 lines

(Aside: you appear to be self-adding your Link: tags -- AIUI, this is normally done by whoever pulls your series. I've only seen Link: tags added when needing to refer to something else not included in the series.)

Quoted 4 lines
Quoted 1 line

It is an insurance to not lose history. :)

How will history be lost? The code is in the repo and discussions can easily be found by searching for subjects or message IDs.

The (full and ordered) history may be hard to find without any Message-ID in commit messages. The Lore links keep that information (in the commit message) and redirect to the related archived email thread, which is very handy. For instance, Linus can rely on those links to judge the quality of a patch:
https://lore.kernel.org/lkml/CAHk-=wh7xY3UF7zEc0BNVNjOox59jYBW-Gfi7=emm+BXPWc6nQ@mail.gmail.com/

Quoted 3 lines

Is anyone else doing this self linking?

I don't know, but it doesn't hurt. This way, if you're using git am without b4 am -l (or forgot to add links manually), the history is still pointed out by these self-reference links. I find it convenient and it is a safeguard to not forget them, no matter who takes the patches.

Reviewed-by on v30 2/12
#10 lore raw

Re: [PATCH v30 02/12] landlock: Add ruleset and domain management

In reply to Mickaël Salaün
Quoted 14 lines · Mickaël Salaün

A Landlock ruleset is mainly a red-black tree with Landlock rules as nodes. This enables quick update and lookup to match a requested access, e.g. to a file. A ruleset is usable through a dedicated file descriptor (cf. following commit implementing syscalls) which enables a process to create and populate a ruleset with new rules.

A domain is a ruleset tied to a set of processes. This group of rules defines the security policy enforced on these processes and their future children. A domain can transition to a new domain which is the intersection of all its constraints and those of a ruleset provided by the current process. This modification only impact the current process. This means that a process can only gain more constraints (i.e. lose accesses) over time.

Quoted 6 lines
author maintainer
#11 lore raw

PATCH v30 3/12 landlock: Set up the security framework and manage credentials

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Process's credentials point to a Landlock domain, which is underneath implemented with a ruleset. In the following commits, this domain is used to check and enforce the ptrace and filesystem security policies. A domain is inherited from a parent to its child the same way a thread inherits a seccomp policy.

---

Changes since v28:
* Add Acked-by Serge Hallyn.

Changes since v25:
* Rename function to landlock_add_cred_hooks().

Changes since v23:
* Add an early check for the current domain in hook_cred_free() to avoid superfluous call.
* Cosmetic cleanup to make the code more readable.

Changes since v22:
* Add Reviewed-by Jann Horn.

Changes since v21:
* Fix copyright dates.

Changes since v17:
* Constify returned domain pointers from landlock_get_current_domain() and landlock_get_task_domain() helpers.

Changes since v15:
* Optimize landlocked() for current thread.
* Display the greeting message when everything is initialized.

Changes since v14:
* Uses pr_fmt from common.h .
* Constify variables.
* Remove useless NULL initialization.

Changes since v13:
* totally get ride of the seccomp dependency
* only keep credential management and LSM setup.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 security/Kconfig           | 10 +++----
 security/landlock/Makefile |  3 +-
 security/landlock/common.h | 20 +++++++++++++
 security/landlock/cred.c   | 46 ++++++++++++++++++++++++++++++
 security/landlock/cred.h   | 58 ++++++++++++++++++++++++++++++++++++++
 security/landlock/setup.c  | 31 ++++++++++++++++++++
 security/landlock/setup.h  | 16 +++++++++++
 7 files changed, 178 insertions(+), 6 deletions(-)
 create mode 100644 security/landlock/common.h
 create mode 100644 security/landlock/cred.c
 create mode 100644 security/landlock/cred.h
 create mode 100644 security/landlock/setup.c
 create mode 100644 security/landlock/setup.h
security/Kconfig +5 -5
index 15a4342b5d01..0ced7fd33e4d 100644
@@ -278,11 +278,11 @@ endchoice
 
 config LSM
 	string "Ordered list of enabled LSMs"
-	default "lockdown,yama,loadpin,safesetid,integrity,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
-	default "lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
-	default "lockdown,yama,loadpin,safesetid,integrity,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
-	default "lockdown,yama,loadpin,safesetid,integrity,bpf" if DEFAULT_SECURITY_DAC
-	default "lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf"
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,bpf" if DEFAULT_SECURITY_DAC
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf"
 	help
 	  A comma-separated list of LSMs, in initialization order.
 	  Any LSMs left off this list will be ignored. This can be
security/landlock/Makefile +2 -1
index d846eba445bb..041ea242e627 100644
@@ -1,3 +1,4 @@
 obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
 
-landlock-y := object.o ruleset.o
+landlock-y := setup.o object.o ruleset.o \
+	cred.o
security/landlock/common.h new file +20 -0
new file mode 100644
index 000000000000..5dc0fe15707d
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Common constants and helpers
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_COMMON_H
+#define _SECURITY_LANDLOCK_COMMON_H
+
+#define LANDLOCK_NAME "landlock"
+
+#ifdef pr_fmt
+#undef pr_fmt
+#endif
+
+#define pr_fmt(fmt) LANDLOCK_NAME ": " fmt
+
+#endif /* _SECURITY_LANDLOCK_COMMON_H */
security/landlock/cred.c new file +46 -0

46 lines not on this page · raw message

security/landlock/cred.h new file +58 -0

58 lines not on this page · raw message

security/landlock/setup.c new file +31 -0
new file mode 100644
index 000000000000..8661112fb238
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Landlock LSM - Security framework setup
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#include <linux/init.h>
+#include <linux/lsm_hooks.h>
+
+#include "common.h"
+#include "cred.h"
+#include "setup.h"
+
+struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
+	.lbs_cred = sizeof(struct landlock_cred_security),
+};
+
+static int __init landlock_init(void)
+{
+	landlock_add_cred_hooks();
+	pr_info("Up and running.\n");
+	return 0;
+}
+
+DEFINE_LSM(LANDLOCK_NAME) = {
+	.name = LANDLOCK_NAME,
+	.init = landlock_init,
+	.blobs = &landlock_blob_sizes,
+};
security/landlock/setup.h new file +16 -0
new file mode 100644
index 000000000000..9fdbf33fcc33
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Security framework setup
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_SETUP_H
+#define _SECURITY_LANDLOCK_SETUP_H
+
+#include <linux/lsm_hooks.h>
+
+extern struct lsm_blob_sizes landlock_blob_sizes;
+
+#endif /* _SECURITY_LANDLOCK_SETUP_H */
Signature · 1 line
2.30.2
Reviewed-by on v30 3/12
#12 lore raw

Re: [PATCH v30 03/12] landlock: Set up the security framework and manage credentials

Quoted 5 lines · Mickaël Salaün

config LSM

security/Kconfig +0 -3
 	string "Ordered list of enabled LSMs"
-	default "lockdown,yama,loadpin,safesetid,integrity,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
-	default "lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
-	default "lockdown,yama,loadpin,safesetid,integrity,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO

security/Kconfig endchoice · line 288

Quoted 10 lines
security/Kconfig +5 -2
-	default "lockdown,yama,loadpin,safesetid,integrity,bpf" if DEFAULT_SECURITY_DAC
-	default "lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf"
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,bpf" if DEFAULT_SECURITY_DAC
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf"
 	help
 	  A comma-separated list of LSMs, in initialization order.
 	  Any LSMs left off this list will be ignored. This can be

There was some discussion long ago about landlock needing to be last in the list because it was unprivileged. Is that no longer true? (And what is the justification for its position in the list?)

Quoted 12 lines
security/landlock/common.h new file +6 -0
new file mode 100644
index 000000000000..5dc0fe15707d
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Common constants and helpers
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI

security/landlock/common.h line 16

Quoted 10 lines
security/landlock/common.h new file +10 -0
+ */
+
+#ifndef _SECURITY_LANDLOCK_COMMON_H
+#define _SECURITY_LANDLOCK_COMMON_H
+
+#define LANDLOCK_NAME "landlock"
+
+#ifdef pr_fmt
+#undef pr_fmt
+#endif

When I see "#undef pr_fmt" I think there is a header ordering problem.

Quoted 1 line

[...]

Everything else looks like regular boilerplate for an LSM. :)

Signature · 1 line
Kees Cook
author maintainer
#13 lore raw

Re: [PATCH v30 03/12] landlock: Set up the security framework and manage credentials

Quoted 12 lines · Kees Cook
Quoted 11 lines · Mickaël Salaün

config LSM

security/Kconfig +4 -5
 	string "Ordered list of enabled LSMs"
-	default "lockdown,yama,loadpin,safesetid,integrity,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
-	default "lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
-	default "lockdown,yama,loadpin,safesetid,integrity,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
-	default "lockdown,yama,loadpin,safesetid,integrity,bpf" if DEFAULT_SECURITY_DAC
-	default "lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf"
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,smack,selinux,tomoyo,apparmor,bpf" if DEFAULT_SECURITY_SMACK
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf" if DEFAULT_SECURITY_APPARMOR
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,tomoyo,bpf" if DEFAULT_SECURITY_TOMOYO
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,bpf" if DEFAULT_SECURITY_DAC
Quoted 8 lines

security/Kconfig endchoice · line 288

Quoted 4 lines
security/Kconfig +1 -0
+	default "landlock,lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf"
 	help
 	  A comma-separated list of LSMs, in initialization order.
 	  Any LSMs left off this list will be ignored. This can be

There was some discussion long ago about landlock needing to be last in the list because it was unprivileged. Is that no longer true? (And what is the justification for its position in the list?)

Indeed, I wanted to put Landlock last because it was an unprivileged programmable access-control, which could lead to side-channel attacks against other access-controls (e.g. to infer enforced policies). This is not valid anymore because Landlock is not using eBPF, only the BPF LSM does that (which is not the only reason why it is the last stacked).

Quoted 17 lines
Quoted 17 lines
security/landlock/common.h new file +10 -0
new file mode 100644
index 000000000000..5dc0fe15707d
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Common constants and helpers
+ *
+ * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
+ * Copyright © 2018-2020 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_COMMON_H
+#define _SECURITY_LANDLOCK_COMMON_H
Quoted 8 lines

security/landlock/common.h line 16

Quoted 6 lines
security/landlock/common.h new file +6 -0
+
+#define LANDLOCK_NAME "landlock"
+
+#ifdef pr_fmt
+#undef pr_fmt
+#endif

When I see "#undef pr_fmt" I think there is a header ordering problem.

Not is this case, it's a "namespace" definition. :)

Quoted 7 lines
Quoted 2 lines

[...]

Everything else looks like regular boilerplate for an LSM. :)

author maintainer
#14 lore raw

PATCH v30 4/12 landlock: Add ptrace restrictions

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Using ptrace(2) and related debug features on a target process can lead to a privilege escalation. Indeed, ptrace(2) can be used by an attacker to impersonate another task and to remain undetected while performing malicious activities. Thanks to ptrace_may_access(), various part of the kernel can check if a tracer is more privileged than a tracee.

A landlocked process has fewer 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's rules (i.e. the tracee must be in a sub-domain of the tracer).

---

Changes since v28:
* Add Acked-by Serge Hallyn.

Changes since v25:
* Rename function to landlock_add_ptrace_hooks().

Changes since v22:
* Add Reviewed-by: Jann Horn <[email protected]>

Changes since v21:
* Fix copyright dates.

Changes since v14:
* Constify variables.

Changes since v13:
* Make the ptrace restriction mandatory, like in the v10.
* Remove the eBPF dependency.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 security/landlock/Makefile |   2 +-
 security/landlock/ptrace.c | 120 +++++++++++++++++++++++++++++++++++++
 security/landlock/ptrace.h |  14 +++++
 security/landlock/setup.c  |   2 +
 4 files changed, 137 insertions(+), 1 deletion(-)
 create mode 100644 security/landlock/ptrace.c
 create mode 100644 security/landlock/ptrace.h
security/landlock/Makefile +1 -1
index 041ea242e627..f1d1eb72fa76 100644
@@ -1,4 +1,4 @@
 obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
 
 landlock-y := setup.o object.o ruleset.o \
-	cred.o
+	cred.o ptrace.o
security/landlock/ptrace.c new file +120 -0

120 lines not on this page · raw message

security/landlock/ptrace.h new file +14 -0
new file mode 100644
index 000000000000..265b220ae3bf
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock LSM - Ptrace hooks
+ *
+ * Copyright © 2017-2019 Mickaël Salaün <[email protected]>
+ * Copyright © 2019 ANSSI
+ */
+
+#ifndef _SECURITY_LANDLOCK_PTRACE_H
+#define _SECURITY_LANDLOCK_PTRACE_H
+
+__init void landlock_add_ptrace_hooks(void);
+
+#endif /* _SECURITY_LANDLOCK_PTRACE_H */
security/landlock/setup.c +2 -0
index 8661112fb238..a5d6ef334991 100644
@@ -11,6 +11,7 @@
 
 #include "common.h"
 #include "cred.h"
+#include "ptrace.h"
 #include "setup.h"
 
 struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
@@ -20,6 +21,7 @@ struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
 static int __init landlock_init(void)
 {
 	landlock_add_cred_hooks();
+	landlock_add_ptrace_hooks();
 	pr_info("Up and running.\n");
 	return 0;
 }
Signature · 1 line
2.30.2
Reviewed-by on v30 4/12
#15 lore raw

Re: [PATCH v30 04/12] landlock: Add ptrace restrictions

Quoted 14 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Using ptrace(2) and related debug features on a target process can lead to a privilege escalation. Indeed, ptrace(2) can be used by an attacker to impersonate another task and to remain undetected while performing malicious activities. Thanks to ptrace_may_access(), various part of the kernel can check if a tracer is more privileged than a tracee.

A landlocked process has fewer 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's rules (i.e. the tracee must be in a sub-domain of the tracer).

Quoted 3 lines
Signature · 1 line
Kees Cook
author maintainer
#16 lore raw

PATCH v30 5/12 LSM: Infrastructure management of the superblock

In reply to Mickaël Salaün

From: Casey Schaufler <[email protected]>

Move management of the superblock->sb_security blob out of the individual security modules and into the security infrastructure. Instead of allocating the blobs from within the modules, the modules tell the infrastructure how much space is required, and the space is allocated there.

---

Changes since v28:
* Add Acked-by Serge Hallyn.

Changes since v26:
* Rebase on commit b159e86b5a2a ("selinux: drop super_block backpointer from superblock_security_struct"). No change in the patch itself, only a trivial conflict because of an updated nearby line in selinux_set_mnt_opts() variable declarations.

Changes since v20:
* Remove all Reviewed-by except Stephen Smalley:
https://lore.kernel.org/lkml/CAEjxPJ7ARJO57MBW66=xsBzMMRb=9uLgqocK5eskHCaiVMx7Vw@mail.gmail.com/
* Cosmetic fix in the commit message.

Changes since v17:
* Rebase the original LSM stacking patch from v5.3 to v5.7: I fixed some diff conflicts caused by code moves and function renames in selinux/include/objsec.h and selinux/hooks.c . I checked that it builds but I didn't test the changes for SELinux nor SMACK.
https://lore.kernel.org/r/[email protected]

---
 include/linux/lsm_hooks.h         |  1 +
 security/security.c               | 46 ++++++++++++++++++++----
 security/selinux/hooks.c          | 58 ++++++++++++-------------------
 security/selinux/include/objsec.h |  6 ++++
 security/selinux/ss/services.c    |  3 +-
 security/smack/smack.h            |  6 ++++
 security/smack/smack_lsm.c        | 35 +++++--------------
 7 files changed, 85 insertions(+), 70 deletions(-)
include/linux/lsm_hooks.h +1 -0
index fb7f3193753d..75715998a95f 100644
@@ -1573,6 +1573,7 @@ struct lsm_blob_sizes {
 	int	lbs_cred;
 	int	lbs_file;
 	int	lbs_inode;
+	int	lbs_superblock;
 	int	lbs_ipc;
 	int	lbs_msg_msg;
 	int	lbs_task;
security/security.c +39 -7

75 lines not on this page · raw message

security/selinux/hooks.c +22 -36

188 lines not on this page · raw message

security/selinux/include/objsec.h +6 -0
index ca4d7ab6a835..2953132408bf 100644
@@ -188,4 +188,10 @@ static inline u32 current_sid(void)
 	return tsec->sid;
 }
 
+static inline struct superblock_security_struct *selinux_superblock(
+					const struct super_block *superblock)
+{
+	return superblock->s_security + selinux_blob_sizes.lbs_superblock;
+}
+
 #endif /* _SELINUX_OBJSEC_H_ */
security/selinux/ss/services.c +2 -1
index 3438d0130378..9cea2e6c809f 100644
@@ -47,6 +47,7 @@
 #include <linux/sched.h>
 #include <linux/audit.h>
 #include <linux/vmalloc.h>
+#include <linux/lsm_hooks.h>
 #include <net/netlabel.h>
 
 #include "flask.h"
@@ -2875,7 +2876,7 @@ int security_fs_use(struct selinux_state *state, struct super_block *sb)
 	struct sidtab *sidtab;
 	int rc = 0;
 	struct ocontext *c;
-	struct superblock_security_struct *sbsec = sb->s_security;
+	struct superblock_security_struct *sbsec = selinux_superblock(sb);
 	const char *fstype = sb->s_type->name;
 
 	if (!selinux_initialized(state)) {
security/smack/smack.h +6 -0
index a9768b12716b..7077b18c79ec 100644
@@ -357,6 +357,12 @@ static inline struct smack_known **smack_ipc(const struct kern_ipc_perm *ipc)
 	return ipc->security + smack_blob_sizes.lbs_ipc;
 }
 
+static inline struct superblock_smack *smack_superblock(
+					const struct super_block *superblock)
+{
+	return superblock->s_security + smack_blob_sizes.lbs_superblock;
+}
+
 /*
  * Is the directory transmuting?
  */
security/smack/smack_lsm.c +9 -26
index 12a45e61c1a5..ee3e29603c9c 100644
@@ -535,12 +535,7 @@ static int smack_syslog(int typefrom_file)
  */
 static int smack_sb_alloc_security(struct super_block *sb)
 {
-	struct superblock_smack *sbsp;
-
-	sbsp = kzalloc(sizeof(struct superblock_smack), GFP_KERNEL);
-
-	if (sbsp == NULL)
-		return -ENOMEM;
+	struct superblock_smack *sbsp = smack_superblock(sb);
 
 	sbsp->smk_root = &smack_known_floor;
 	sbsp->smk_default = &smack_known_floor;
@@ -549,22 +544,10 @@ static int smack_sb_alloc_security(struct super_block *sb)
 	/*
 	 * SMK_SB_INITIALIZED will be zero from kzalloc.
 	 */
-	sb->s_security = sbsp;
 
 	return 0;
 }
 
-/**
- * smack_sb_free_security - free a superblock blob
- * @sb: the superblock getting the blob
- *
- */
-static void smack_sb_free_security(struct super_block *sb)
-{
-	kfree(sb->s_security);
-	sb->s_security = NULL;
-}
-
 struct smack_mnt_opts {
 	const char *fsdefault, *fsfloor, *fshat, *fsroot, *fstransmute;
 };
@@ -772,7 +755,7 @@ static int smack_set_mnt_opts(struct super_block *sb,
 {
 	struct dentry *root = sb->s_root;
 	struct inode *inode = d_backing_inode(root);
-	struct superblock_smack *sp = sb->s_security;
+	struct superblock_smack *sp = smack_superblock(sb);
 	struct inode_smack *isp;
 	struct smack_known *skp;
 	struct smack_mnt_opts *opts = mnt_opts;
@@ -871,7 +854,7 @@ static int smack_set_mnt_opts(struct super_block *sb,
  */
 static int smack_sb_statfs(struct dentry *dentry)
 {
-	struct superblock_smack *sbp = dentry->d_sb->s_security;
+	struct superblock_smack *sbp = smack_superblock(dentry->d_sb);
 	int rc;
 	struct smk_audit_info ad;
 
@@ -905,7 +888,7 @@ static int smack_bprm_creds_for_exec(struct linux_binprm *bprm)
 	if (isp->smk_task == NULL || isp->smk_task == bsp->smk_task)
 		return 0;
 
-	sbsp = inode->i_sb->s_security;
+	sbsp = smack_superblock(inode->i_sb);
 	if ((sbsp->smk_flags & SMK_SB_UNTRUSTED) &&
 	    isp->smk_task != sbsp->smk_root)
 		return 0;
@@ -1157,7 +1140,7 @@ static int smack_inode_rename(struct inode *old_inode,
  */
 static int smack_inode_permission(struct inode *inode, int mask)
 {
-	struct superblock_smack *sbsp = inode->i_sb->s_security;
+	struct superblock_smack *sbsp = smack_superblock(inode->i_sb);
 	struct smk_audit_info ad;
 	int no_block = mask & MAY_NOT_BLOCK;
 	int rc;
@@ -1400,7 +1383,7 @@ static int smack_inode_removexattr(struct user_namespace *mnt_userns,
 	 */
 	if (strcmp(name, XATTR_NAME_SMACK) == 0) {
 		struct super_block *sbp = dentry->d_sb;
-		struct superblock_smack *sbsp = sbp->s_security;
+		struct superblock_smack *sbsp = smack_superblock(sbp);
 
 		isp->smk_inode = sbsp->smk_default;
 	} else if (strcmp(name, XATTR_NAME_SMACKEXEC) == 0)
@@ -1670,7 +1653,7 @@ static int smack_mmap_file(struct file *file,
 	isp = smack_inode(file_inode(file));
 	if (isp->smk_mmap == NULL)
 		return 0;
-	sbsp = file_inode(file)->i_sb->s_security;
+	sbsp = smack_superblock(file_inode(file)->i_sb);
 	if (sbsp->smk_flags & SMK_SB_UNTRUSTED &&
 	    isp->smk_mmap != sbsp->smk_root)
 		return -EACCES;
@@ -3285,7 +3268,7 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
 		return;
 
 	sbp = inode->i_sb;
-	sbsp = sbp->s_security;
+	sbsp = smack_superblock(sbp);
 	/*
 	 * We're going to use the superblock default label
 	 * if there's no label on the file.
@@ -4700,6 +4683,7 @@ struct lsm_blob_sizes smack_blob_sizes __lsm_ro_after_init = {
 	.lbs_inode = sizeof(struct inode_smack),
 	.lbs_ipc = sizeof(struct smack_known *),
 	.lbs_msg_msg = sizeof(struct smack_known *),
+	.lbs_superblock = sizeof(struct superblock_smack),
 };
 
 static struct security_hook_list smack_hooks[] __lsm_ro_after_init = {
@@ -4711,7 +4695,6 @@ static struct security_hook_list smack_hooks[] __lsm_ro_after_init = {
 	LSM_HOOK_INIT(fs_context_parse_param, smack_fs_context_parse_param),
 
 	LSM_HOOK_INIT(sb_alloc_security, smack_sb_alloc_security),
-	LSM_HOOK_INIT(sb_free_security, smack_sb_free_security),
 	LSM_HOOK_INIT(sb_free_mnt_opts, smack_free_mnt_opts),
 	LSM_HOOK_INIT(sb_eat_lsm_opts, smack_sb_eat_lsm_opts),
 	LSM_HOOK_INIT(sb_statfs, smack_sb_statfs),
Signature · 1 line
2.30.2
Reviewed-by on v30 5/12
#17 lore raw

Re: [PATCH v30 05/12] LSM: Infrastructure management of the superblock

Quoted 11 lines · Mickaël Salaün

From: Casey Schaufler <[email protected]>

Move management of the superblock->sb_security blob out of the individual security modules and into the security infrastructure. Instead of allocating the blobs from within the modules, the modules tell the infrastructure how much space is required, and the space is allocated there.

Cc Kees Cook <[email protected]>
Cc John Johansen <[email protected]>
Signature · 1 line
Kees Cook
author maintainer
#18 lore raw

PATCH v30 6/12 fs,security: Add sb_delete hook

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

The sb_delete security hook is called when shutting down a superblock, which may be useful to release kernel objects tied to the superblock's lifetime (e.g. inodes).

This new hook is needed by Landlock to release (ephemerally) tagged struct inodes. This comes from the unprivileged nature of Landlock described in the next commit.

---

Changes since v28:
* Extend hook description (suggested by Serge Hallyn).
* Add Acked-by Serge Hallyn.

Changes since v22:
* Add Reviewed-by: Jann Horn <[email protected]>

Changes since v17:
* Initial patch to replace the direct call to landlock_release_inodes() (requested by James Morris).
https://lore.kernel.org/lkml/[email protected]/

---
 fs/super.c                    | 1 +
 include/linux/lsm_hook_defs.h | 1 +
 include/linux/lsm_hooks.h     | 3 +++
 include/linux/security.h      | 4 ++++
 security/security.c           | 5 +++++
 5 files changed, 14 insertions(+)
fs/super.c +1 -0
index 8c1baca35c16..11b7e7213fd1 100644
@@ -454,6 +454,7 @@ void generic_shutdown_super(struct super_block *sb)
 		evict_inodes(sb);
 		/* only nonzero refcount inodes can have marks */
 		fsnotify_sb_delete(sb);
+		security_sb_delete(sb);
 
 		if (sb->s_dio_done_wq) {
 			destroy_workqueue(sb->s_dio_done_wq);
include/linux/lsm_hook_defs.h +1 -0
index 477a597db013..e8adadbf9581 100644
@@ -59,6 +59,7 @@ LSM_HOOK(int, 0, fs_context_dup, struct fs_context *fc,
 LSM_HOOK(int, -ENOPARAM, fs_context_parse_param, struct fs_context *fc,
 	 struct fs_parameter *param)
 LSM_HOOK(int, 0, sb_alloc_security, struct super_block *sb)
+LSM_HOOK(void, LSM_RET_VOID, sb_delete, struct super_block *sb)
 LSM_HOOK(void, LSM_RET_VOID, sb_free_security, struct super_block *sb)
 LSM_HOOK(void, LSM_RET_VOID, sb_free_mnt_opts, void *mnt_opts)
 LSM_HOOK(int, 0, sb_eat_lsm_opts, char *orig, void **mnt_opts)
include/linux/lsm_hooks.h +3 -0
index 75715998a95f..cc2eaaaec0e4 100644
@@ -108,6 +108,9 @@
  *	allocated.
  *	@sb contains the super_block structure to be modified.
  *	Return 0 if operation was successful.
+ * @sb_delete:
+ *	Release objects tied to a superblock (e.g. inodes).
+ *	@sb contains the super_block structure being released.
  * @sb_free_security:
  *	Deallocate and clear the sb->s_security field.
  *	@sb contains the super_block structure to be modified.
include/linux/security.h +4 -0
index 8aeebd6646dc..90298baa4551 100644
@@ -291,6 +291,7 @@ void security_bprm_committed_creds(struct linux_binprm *bprm);
 int security_fs_context_dup(struct fs_context *fc, struct fs_context *src_fc);
 int security_fs_context_parse_param(struct fs_context *fc, struct fs_parameter *param);
 int security_sb_alloc(struct super_block *sb);
+void security_sb_delete(struct super_block *sb);
 void security_sb_free(struct super_block *sb);
 void security_free_mnt_opts(void **mnt_opts);
 int security_sb_eat_lsm_opts(char *options, void **mnt_opts);
@@ -631,6 +632,9 @@ static inline int security_sb_alloc(struct super_block *sb)
 	return 0;
 }
 
+static inline void security_sb_delete(struct super_block *sb)
+{ }
+
 static inline void security_sb_free(struct super_block *sb)
 { }
 
security/security.c +5 -0
index e9c29480eb18..bb666f992497 100644
@@ -900,6 +900,11 @@ int security_sb_alloc(struct super_block *sb)
 	return rc;
 }
 
+void security_sb_delete(struct super_block *sb)
+{
+	call_void_hook(sb_delete, sb);
+}
+
 void security_sb_free(struct super_block *sb)
 {
 	call_void_hook(sb_free_security, sb);
Signature · 1 line
2.30.2
Reviewed-by on v30 6/12
#19 lore raw

Re: [PATCH v30 06/12] fs,security: Add sb_delete hook

Quoted 6 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

The sb_delete security hook is called when shutting down a superblock, which may be useful to release kernel objects tied to the superblock's lifetime (e.g. inodes).

Quoted 8 lines

This new hook is needed by Landlock to release (ephemerally) tagged struct inodes. This comes from the unprivileged nature of Landlock described in the next commit.

Signature · 1 line
Kees Cook
author maintainer
#20 lore raw

PATCH v30 7/12 landlock: Support filesystem access-control

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain. To enable an unprivileged process to express a file hierarchy, it first needs to open a directory (or a file) and pass this file descriptor to the kernel through landlock_add_rule(2). When checking if a file access request is allowed, we walk from the requested dentry to the real root, following the different mount layers. The access to each "tagged" inodes are collected according to their rule layer level, and ANDed to create access to the requested file hierarchy. This makes possible to identify a lot of files without tagging every inodes nor modifying the filesystem, while still following the view and understanding the user has from the filesystem.

Add a new ARCH_EPHEMERAL_INODES for UML because it currently does not keep the same struct inodes for the same inodes whereas these inodes are in use.

This commit adds a minimal set of supported filesystem access-control which doesn't enable to restrict all file-related actions. This is the result of multiple discussions to minimize the code of Landlock to ease review. Thanks to the Landlock design, extending this access-control without breaking user space will not be a problem. Moreover, seccomp filters can be used to restrict the use of syscall families which may not be currently handled by Landlock.

Cc Al Viro <[email protected]>
Cc Anton Ivanov <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jeff Dike <[email protected]>
Cc Kees Cook <[email protected]>
Cc Richard Weinberger <[email protected]>
Cc Serge E. Hallyn <[email protected]>

---

Changes since v29:
* Remove a useless unlock/lock for the first loop walk in hook_sb_delete(). This also makes the code clearer but doesn't change the garantees for iput().
* Rename iput_inode to prev_inode, which shows its origin.

Changes since v28:
* Fix race conditions that could be caused by concurrent calls to release_inode() and hook_sb_delete().
* Avoid livelock when a lot of inodes are tagged.
* Improve concurrency locking and add comments to explain the specific lock rules.
* Add an inode_free_security hook to check that release_inode() and hook_sb_delete() do their job.
* Add early return to check_access_path() to check if the access request is empty. This doesn't change the semantic.
* Reword the first description sentence (suggested by Serge Hallyn).

Changes since v27:
* Fix domains with layers of non-overlapping access rights (cf. layout1.non_overlapping_accesses test) thanks to a stack of access rights per layer (replacing ORed access rights). This avoids too-restrictive domains.
* Cosmetic fixes and updates in comments and Kconfig.

Changes since v26:
* Check each rule of a path to enable a more permissive and pragmatic access control per layer. Suggested by Jann Horn:
https://lore.kernel.org/lkml/CAG48ez1O0VTwEiRd3KqexoF78WR+cmP5bGk5Kh5Cs7aPepiDVg@mail.gmail.com/
* Rename check_access_path_continue() to unmask_layers() and make it return the new layer mask.
* Avoid double domain check in hook_file_open().
* In the documentation, add utime(2) as another example of unhandled syscalls. Indeed, using touch to test write access may be tempting.
* Remove outdated comment about OverlayFS.
* Rename the landlock.h ifdef to align with most similar files.
* Fix spelling.

Changes since v25:
* Move build_check_layer() to ruleset.c, and add built-time checks for the fs_access_mask and access variables according to _LANDLOCK_ACCESS_FS_MASK.
* Move limits to a dedicated file and rename them:
_LANDLOCK_ACCESS_FS_LAST and _LANDLOCK_ACCESS_FS_MASK.
* Set build_check_layer() as non-inline to trigger a warning if it is not called.
* Use BITS_PER_TYPE() macro.
* Rename function to landlock_add_fs_hooks().
* Cosmetic variable renames.

Changes since v24:
* Use the new struct landlock_rule and landlock_layer to not mix accesses from different layers. Revert "Enforce deterministic interleaved path rules" from v24, and fix the layer check. This enables to follow a sane semantic: an access is granted if, for each policy layer, at least one rule encountered on the pathwalk grants the access, regardless of their position in the layer stack (suggested by Jann Horn). See layout1.interleaved_masked_accesses tests from tools/testing/selftests/landlock/fs_test.c for corner cases.
* Add build-time checks for layers.
* Use the new landlock_insert_rule() API.

Changes since v23:
* Enforce deterministic interleaved path rules. To have consistent layered rules, granting access to a path implies that all accesses tied to inodes, from the requested file to the real root, must be checked. Otherwise, stacked rules may result to overzealous restrictions. By excluding the ability to add exceptions in the same layer (e.g. /a allowed, /a/b denied, and /a/b/c allowed), we get deterministic interleaved path rules. This removes an optimization which could be replaced by a proper cache mechanism. This also further simplifies and explain check_access_path_continue().
* Fix memory allocation error handling in landlock_create_object() calls. This prevent to inadvertently hold an inode.
* In get_inode_object(), improve comments, make code more readable and move kfree() call out of the lock window.
* Use the simplified landlock_insert_rule() API.

Changes since v22:
* Simplify check_access_path_continue() (suggested by Jann Horn).
* Remove prefetch() call for now (suggested by Jann Horn).
* Fix spelling and remove superfluous comment (spotted by Jann Horn).
* Cosmetic variable renaming.

Changes since v21:
* Rename ARCH_EPHEMERAL_STATES to ARCH_EPHEMERAL_INODES (suggested by James Morris).
* Remove the LANDLOCK_ACCESS_FS_CHROOT right because chroot(2) (which requires CAP_SYS_CHROOT) doesn't enable to bypass Landlock (as tests demonstrate it), and because it is often used by sandboxes, it would be counterproductive to forbid it. This also reduces the code size.
* Clean up documentation.

Changes since v19:
* Fix spelling (spotted by Randy Dunlap).

Changes since v18:
* Remove useless include.
* Fix spelling.

Changes since v17:
* Replace landlock_release_inodes() with security_sb_delete() (requested by James Morris).
* Replace struct super_block->s_landlock_inode_refs with the LSM infrastructure management of the superblock (requested by James Morris).
* Fix mknod restriction with a zero mode (spotted by Vincent Dagonneau).
* Minimize executed code in path_mknod and file_open hooks when the current tasks is not sandboxed.
* Remove useless checks on the file pointer and inode in hook_file_open() .
* Constify domain pointers.
* Rename inode_landlock() to landlock_inode().
* Import include/uapi/linux/landlock.h and _LANDLOCK_ACCESS_FS_* from the ruleset and domain management patch.
* Explain the rational of this minimal set of access-control.
https://lore.kernel.org/lkml/[email protected]/

Changes since v16:
* Add ARCH_EPHEMERAL_STATES and enable it for UML.

Changes since v15:
* Replace layer_levels and layer_depth with a bitfield of layers: this enables to properly manage superset and subset of access rights, whatever their order in the stack of layers.
Cf. https://lore.kernel.org/lkml/[email protected]/
* Allow to open pipes and similar special files through /proc/self/fd/.
* Properly handle internal filesystems such as nsfs: always allow these kind of roots because disconnected path cannot be evaluated.
* Remove the LANDLOCK_ACCESS_FS_LINK_TO and LANDLOCK_ACCESS_FS_RENAME_{TO,FROM}, but use the LANDLOCK_ACCESS_FS_REMOVE_{FILE,DIR} and LANDLOCK_ACCESS_FS_MAKE_* instead. Indeed, it is not possible for now (and not really useful) to express the semantic of a source and a destination.
* Check access rights to remove a directory or a file with rename(2).
* Forbid reparenting when linking or renaming. This is needed to easily protect against possible privilege escalation by changing the place of a file or directory in relation to an enforced access policy (from the set of layers). This will be relaxed in the future.
* Update hooks to take into account replacement of the object's self and beneath access bitfields with one. Simplify the code.
* Check file related access rights.
* Check d_is_negative() instead of !d_backing_inode() in check_access_path_continue(), and continue the path walk while there is no mapped inode e.g., with rename(2).
* Check private inode in check_access_path().
* Optimize get_file_access() when dealing with a directory.
* Add missing atomic.h .

Changes since v14:
* Simplify the object, rule and ruleset management at the expense of a
less aggressive memory freeing (contributed by Jann Horn, with
additional modifications):
- Rewrite release_inode() to use inode->sb->s_landlock_inode_refs.
- Remove useless checks in landlock_release_inodes(), clean object
pointer according to the new struct landlock_object and wait for all
iput() to complete.
- Rewrite get_inode_object() according to the new struct
landlock_object. If there is a race-condition when cleaning up an
object, we retry until the concurrent thread finished the object
cleaning.
Cf. https://lore.kernel.org/lkml/CAG48ez21bEn0wL1bbmTiiu8j9jP5iEWtHOwz4tURUJ+ki0ydYw@mail.gmail.com/
* Fix nested domains by implementing a notion of layer level and depth:
- Check for matching level ranges when walking through a file path.
- Only allow access if every layer granted the access request.
* Handles files without mount points (e.g. pipes).
* Hardens path walk by checking inode pointer values.
* Prefetches d_parent when walking to the root directory.
* Remove useless inode_alloc_security hook() (suggested by Jann Horn):
already initialized by lsm_inode_alloc().
* Remove the inode_free_security hook.
* Remove access checks that may be required for FD-only requests:
truncate, getattr, lock, chmod, chown, chgrp, ioctl. This will be
handle in a future evolution of Landlock, but right now the goal is to
lighten the code to ease review.
* Constify variables.
* Move ABI checks into syscall.c .
* Cosmetic variable renames.

Changes since v11:
* Add back, revamp and make a fully working filesystem access-control based on paths and inodes.
* Remove the eBPF dependency.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 MAINTAINERS                   |   1 +
 arch/Kconfig                  |   7 +
 arch/um/Kconfig               |   1 +
 include/uapi/linux/landlock.h |  75 ++++
 security/landlock/Kconfig     |   2 +-
 security/landlock/Makefile    |   2 +-
 security/landlock/fs.c        | 687 ++++++++++++++++++++++++++++++++++
 security/landlock/fs.h        |  56 +++
 security/landlock/limits.h    |   4 +
 security/landlock/ruleset.c   |   4 +
 security/landlock/setup.c     |   7 +
 security/landlock/setup.h     |   2 +
 12 files changed, 846 insertions(+), 2 deletions(-)
 create mode 100644 include/uapi/linux/landlock.h
 create mode 100644 security/landlock/fs.c
 create mode 100644 security/landlock/fs.h
MAINTAINERS +1 -0
index 87a2738dfdec..70ec117efa8a 100644
@@ -10003,6 +10003,7 @@ L:	[email protected]
 S:	Supported
 W:	https://landlock.io
 T:	git https://github.com/landlock-lsm/linux.git
+F:	include/uapi/linux/landlock.h
 F:	security/landlock/
 K:	landlock
 K:	LANDLOCK
arch/Kconfig +7 -0
index ecfd3520b676..8160ab7e3e03 100644
@@ -1013,6 +1013,13 @@ config COMPAT_32BIT_TIME
 config ARCH_NO_PREEMPT
 	bool
 
+config ARCH_EPHEMERAL_INODES
+	def_bool n
+	help
+	  An arch should select this symbol if it doesn't keep track of inode
+	  instances on its own, but instead relies on something else (e.g. the
+	  host kernel for an UML kernel).
+
 config ARCH_SUPPORTS_RT
 	bool
 
arch/um/Kconfig +1 -0
index c3030db3325f..57cfd9a1c082 100644
@@ -5,6 +5,7 @@ menu "UML-specific options"
 config UML
 	bool
 	default y
+	select ARCH_EPHEMERAL_INODES
 	select ARCH_HAS_KCOV
 	select ARCH_NO_PREEMPT
 	select HAVE_ARCH_AUDITSYSCALL
include/uapi/linux/landlock.h new file +75 -0

75 lines not on this page · raw message

security/landlock/Kconfig +1 -1
index c1e862a38410..8e33c4e8ffb8 100644
@@ -2,7 +2,7 @@
 
 config SECURITY_LANDLOCK
 	bool "Landlock support"
-	depends on SECURITY
+	depends on SECURITY && !ARCH_EPHEMERAL_INODES
 	select SECURITY_PATH
 	help
 	  Landlock is a sandboxing mechanism that enables processes to restrict
security/landlock/Makefile +1 -1
index f1d1eb72fa76..92e3d80ab8ed 100644
@@ -1,4 +1,4 @@
 obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
 
 landlock-y := setup.o object.o ruleset.o \
-	cred.o ptrace.o
+	cred.o ptrace.o fs.o
security/landlock/fs.c new file +687 -0

687 lines not on this page · raw message

security/landlock/fs.h new file +56 -0

56 lines not on this page · raw message

security/landlock/limits.h +4 -0
index b734f597bb0e..2a0a1095ee27 100644
@@ -10,8 +10,12 @@
 #define _SECURITY_LANDLOCK_LIMITS_H
 
 #include <linux/limits.h>
+#include <uapi/linux/landlock.h>
 
 #define LANDLOCK_MAX_NUM_LAYERS		64
 #define LANDLOCK_MAX_NUM_RULES		U32_MAX
 
+#define LANDLOCK_LAST_ACCESS_FS		LANDLOCK_ACCESS_FS_MAKE_SYM
+#define LANDLOCK_MASK_ACCESS_FS		((LANDLOCK_LAST_ACCESS_FS << 1) - 1)
+
 #endif /* _SECURITY_LANDLOCK_LIMITS_H */
security/landlock/ruleset.c +4 -0
index 59c86126ea1c..9c15aea180a1 100644
@@ -116,9 +116,11 @@ static void build_check_ruleset(void)
 		.num_rules = ~0,
 		.num_layers = ~0,
 	};
+	typeof(ruleset.fs_access_masks[0]) fs_access_mask = ~0;
 
 	BUILD_BUG_ON(ruleset.num_rules < LANDLOCK_MAX_NUM_RULES);
 	BUILD_BUG_ON(ruleset.num_layers < LANDLOCK_MAX_NUM_LAYERS);
+	BUILD_BUG_ON(fs_access_mask < LANDLOCK_MASK_ACCESS_FS);
 }
 
 /**
@@ -217,9 +219,11 @@ static void build_check_layer(void)
 {
 	const struct landlock_layer layer = {
 		.level = ~0,
+		.access = ~0,
 	};
 
 	BUILD_BUG_ON(layer.level < LANDLOCK_MAX_NUM_LAYERS);
+	BUILD_BUG_ON(layer.access < LANDLOCK_MASK_ACCESS_FS);
 }
 
 /* @ruleset must be locked by the caller. */
security/landlock/setup.c +7 -0
index a5d6ef334991..f8e8e980454c 100644
@@ -11,17 +11,24 @@
 
 #include "common.h"
 #include "cred.h"
+#include "fs.h"
 #include "ptrace.h"
 #include "setup.h"
 
+bool landlock_initialized __lsm_ro_after_init = false;
+
 struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
 	.lbs_cred = sizeof(struct landlock_cred_security),
+	.lbs_inode = sizeof(struct landlock_inode_security),
+	.lbs_superblock = sizeof(struct landlock_superblock_security),
 };
 
 static int __init landlock_init(void)
 {
 	landlock_add_cred_hooks();
 	landlock_add_ptrace_hooks();
+	landlock_add_fs_hooks();
+	landlock_initialized = true;
 	pr_info("Up and running.\n");
 	return 0;
 }
security/landlock/setup.h +2 -0
index 9fdbf33fcc33..1daffab1ab4b 100644
@@ -11,6 +11,8 @@
 
 #include <linux/lsm_hooks.h>
 
+extern bool landlock_initialized;
+
 extern struct lsm_blob_sizes landlock_blob_sizes;
 
 #endif /* _SECURITY_LANDLOCK_SETUP_H */
Signature · 1 line
2.30.2
maintainer
#21 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 3 lines

This commit adds a minimal set of supported filesystem access-control which doesn't enable to restrict all file-related actions.

It would be great to get some more review/acks on this patch, particularly from VFS/FS folk.

Signature · 2 lines
James Morris
<[email protected]>
Reviewed-by on v30 7/12
#22 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

In reply to Mickaël Salaün
Quoted 48 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain. To enable an unprivileged process to express a file hierarchy, it first needs to open a directory (or a file) and pass this file descriptor to the kernel through landlock_add_rule(2). When checking if a file access request is allowed, we walk from the requested dentry to the real root, following the different mount layers. The access to each "tagged" inodes are collected according to their rule layer level, and ANDed to create access to the requested file hierarchy. This makes possible to identify a lot of files without tagging every inodes nor modifying the filesystem, while still following the view and understanding the user has from the filesystem.

Add a new ARCH_EPHEMERAL_INODES for UML because it currently does not keep the same struct inodes for the same inodes whereas these inodes are in use.

This commit adds a minimal set of supported filesystem access-control which doesn't enable to restrict all file-related actions. This is the result of multiple discussions to minimize the code of Landlock to ease review. Thanks to the Landlock design, extending this access-control without breaking user space will not be a problem. Moreover, seccomp filters can be used to restrict the use of syscall families which may not be currently handled by Landlock.

Cc Al Viro <[email protected]>
Cc Anton Ivanov <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jeff Dike <[email protected]>
Cc Kees Cook <[email protected]>
Cc Richard Weinberger <[email protected]>
Cc Serge E. Hallyn <[email protected]>
[...]
security/landlock/fs.c new file +10 -0
+	spin_lock(&sb->s_inode_list_lock);
+	list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
+		struct landlock_object *object;
+
+		/* Only handles referenced inodes. */
+		if (!atomic_read(&inode->i_count))
+			continue;
+
+		/*
+		 * Checks I_FREEING and I_WILL_FREE  to protect against a race

security/landlock/fs.c line 363

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+		 * condition when release_inode() just called iput(), which
+		 * could lead to a NULL dereference of inode->security or a
+		 * second call to iput() for the same Landlock object.  Also
+		 * checks I_NEW because such inode cannot be tied to an object.
+		 */
+		spin_lock(&inode->i_lock);
+		if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
+			spin_unlock(&inode->i_lock);
+			continue;
+		}

This (and elsewhere here) seems like a lot of inode internals getting exposed. Can any of this be repurposed into helpers? I see this test scattered around the kernel a fair bit:

$ git grep I_FREEING | grep I_WILL_FREE | grep I_NEW | wc -l
9
Quoted 13 lines
security/landlock/fs.c new file +13 -0
+static inline u32 get_mode_access(const umode_t mode)
+{
+	switch (mode & S_IFMT) {
+	case S_IFLNK:
+		return LANDLOCK_ACCESS_FS_MAKE_SYM;
+	case 0:
+		/* A zero mode translates to S_IFREG. */
+	case S_IFREG:
+		return LANDLOCK_ACCESS_FS_MAKE_REG;
+	case S_IFDIR:
+		return LANDLOCK_ACCESS_FS_MAKE_DIR;
+	case S_IFCHR:
+		return LANDLOCK_ACCESS_FS_MAKE_CHAR;

security/landlock/fs.c line 531

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+	case S_IFBLK:
+		return LANDLOCK_ACCESS_FS_MAKE_BLOCK;
+	case S_IFIFO:
+		return LANDLOCK_ACCESS_FS_MAKE_FIFO;
+	case S_IFSOCK:
+		return LANDLOCK_ACCESS_FS_MAKE_SOCK;
+	default:
+		WARN_ON_ONCE(1);
+		return 0;
+	}

I'm assuming this won't be reachable from userspace.

Quoted 16 lines

[...]
index a5d6ef334991..f8e8e980454c 100644

security/landlock/setup.c +3 -0
@@ -11,17 +11,24 @@
 
 #include "common.h"
 #include "cred.h"
+#include "fs.h"
 #include "ptrace.h"
 #include "setup.h"
 
+bool landlock_initialized __lsm_ro_after_init = false;
+
 struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
 	.lbs_cred = sizeof(struct landlock_cred_security),

security/landlock/setup.c line 31

Quoted 10 lines
security/landlock/setup.c +4 -0
+	.lbs_inode = sizeof(struct landlock_inode_security),
+	.lbs_superblock = sizeof(struct landlock_superblock_security),
 };
 
 static int __init landlock_init(void)
 {
 	landlock_add_cred_hooks();
 	landlock_add_ptrace_hooks();
+	landlock_add_fs_hooks();
+	landlock_initialized = true;

I think this landlock_initialized is logically separate from the optional DEFINE_LSM "enabled" variable, but I thought I'd double check. :)

It seems like it's used here to avoid releasing superblocks before landlock_init() is called? What is the scenario where that happens?

Quoted 19 lines
security/landlock/setup.c +0 -0
 	pr_info("Up and running.\n");
 	return 0;
 }
security/landlock/setup.h +2 -0
index 9fdbf33fcc33..1daffab1ab4b 100644
@@ -11,6 +11,8 @@
 
 #include <linux/lsm_hooks.h>
 
+extern bool landlock_initialized;
+
 extern struct lsm_blob_sizes landlock_blob_sizes;
 
 #endif /* _SECURITY_LANDLOCK_SETUP_H */
Signature · 1 line
2.30.2

The locking and inode semantics are pretty complex, but since, again, it's got significant test and syzkaller coverage, it looks good to me.

With the inode helper cleanup:

Signature · 1 line
Kees Cook
author maintainer
#23 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 64 lines · Kees Cook
Quoted 48 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain. To enable an unprivileged process to express a file hierarchy, it first needs to open a directory (or a file) and pass this file descriptor to the kernel through landlock_add_rule(2). When checking if a file access request is allowed, we walk from the requested dentry to the real root, following the different mount layers. The access to each "tagged" inodes are collected according to their rule layer level, and ANDed to create access to the requested file hierarchy. This makes possible to identify a lot of files without tagging every inodes nor modifying the filesystem, while still following the view and understanding the user has from the filesystem.

Add a new ARCH_EPHEMERAL_INODES for UML because it currently does not keep the same struct inodes for the same inodes whereas these inodes are in use.

This commit adds a minimal set of supported filesystem access-control which doesn't enable to restrict all file-related actions. This is the result of multiple discussions to minimize the code of Landlock to ease review. Thanks to the Landlock design, extending this access-control without breaking user space will not be a problem. Moreover, seccomp filters can be used to restrict the use of syscall families which may not be currently handled by Landlock.

Cc Al Viro <[email protected]>
Cc Anton Ivanov <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jeff Dike <[email protected]>
Cc Kees Cook <[email protected]>
Cc Richard Weinberger <[email protected]>
Cc Serge E. Hallyn <[email protected]>
[...]
security/landlock/fs.c new file +10 -0
+	spin_lock(&sb->s_inode_list_lock);
+	list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
+		struct landlock_object *object;
+
+		/* Only handles referenced inodes. */
+		if (!atomic_read(&inode->i_count))
+			continue;
+
+		/*
+		 * Checks I_FREEING and I_WILL_FREE  to protect against a race

security/landlock/fs.c line 363

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+		 * condition when release_inode() just called iput(), which
+		 * could lead to a NULL dereference of inode->security or a
+		 * second call to iput() for the same Landlock object.  Also
+		 * checks I_NEW because such inode cannot be tied to an object.
+		 */
+		spin_lock(&inode->i_lock);
+		if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
+			spin_unlock(&inode->i_lock);
+			continue;
+		}

This (and elsewhere here) seems like a lot of inode internals getting exposed. Can any of this be repurposed into helpers? I see this test scattered around the kernel a fair bit:

Quoted 2 lines
$ git grep I_FREEING | grep I_WILL_FREE | grep I_NEW | wc -l
9

Dealing with the filesystem is complex. Some helpers could probably be added, but with a series dedicated to the filesystem. I can work on that once this series is merged.

Quoted 18 lines
Quoted 18 lines
security/landlock/fs.c new file +17 -0
+static inline u32 get_mode_access(const umode_t mode)
+{
+	switch (mode & S_IFMT) {
+	case S_IFLNK:
+		return LANDLOCK_ACCESS_FS_MAKE_SYM;
+	case 0:
+		/* A zero mode translates to S_IFREG. */
+	case S_IFREG:
+		return LANDLOCK_ACCESS_FS_MAKE_REG;
+	case S_IFDIR:
+		return LANDLOCK_ACCESS_FS_MAKE_DIR;
+	case S_IFCHR:
+		return LANDLOCK_ACCESS_FS_MAKE_CHAR;
+	case S_IFBLK:
+		return LANDLOCK_ACCESS_FS_MAKE_BLOCK;
+	case S_IFIFO:
+		return LANDLOCK_ACCESS_FS_MAKE_FIFO;
Quoted 8 lines

security/landlock/fs.c line 531

Quoted 6 lines
security/landlock/fs.c new file +6 -0
+	case S_IFSOCK:
+		return LANDLOCK_ACCESS_FS_MAKE_SOCK;
+	default:
+		WARN_ON_ONCE(1);
+		return 0;
+	}

I'm assuming this won't be reachable from userspace.

It should not, only a bogus kernel code could.

Quoted 21 lines
Quoted 21 lines

[...]
index a5d6ef334991..f8e8e980454c 100644

security/landlock/setup.c +5 -0
@@ -11,17 +11,24 @@
 
 #include "common.h"
 #include "cred.h"
+#include "fs.h"
 #include "ptrace.h"
 #include "setup.h"
 
+bool landlock_initialized __lsm_ro_after_init = false;
+
 struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
 	.lbs_cred = sizeof(struct landlock_cred_security),
+	.lbs_inode = sizeof(struct landlock_inode_security),
+	.lbs_superblock = sizeof(struct landlock_superblock_security),
 };
 
Quoted 9 lines

security/landlock/setup.c line 31

Quoted 6 lines
security/landlock/setup.c +2 -0
 static int __init landlock_init(void)
 {
 	landlock_add_cred_hooks();
 	landlock_add_ptrace_hooks();
+	landlock_add_fs_hooks();
+	landlock_initialized = true;

I think this landlock_initialized is logically separate from the optional DEFINE_LSM "enabled" variable, but I thought I'd double check. :)

An LSM can be marked as enabled (at boot) but not yet initialized.

Quoted 3 lines

It seems like it's used here to avoid releasing superblocks before landlock_init() is called? What is the scenario where that happens?

It is a condition for LSM hooks, syscalls and superblock management.

Quoted 28 lines
Quoted 20 lines
security/landlock/setup.c +0 -0
 	pr_info("Up and running.\n");
 	return 0;
 }
security/landlock/setup.h +2 -0
index 9fdbf33fcc33..1daffab1ab4b 100644
@@ -11,6 +11,8 @@
 
 #include <linux/lsm_hooks.h>
 
+extern bool landlock_initialized;
+
 extern struct lsm_blob_sizes landlock_blob_sizes;
 
 #endif /* _SECURITY_LANDLOCK_SETUP_H */
Signature · 1 line
2.30.2

The locking and inode semantics are pretty complex, but since, again, it's got significant test and syzkaller coverage, it looks good to me.

With the inode helper cleanup:

author maintainer
#24 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 133 lines · Mickaël Salaün
Quoted 64 lines · Kees Cook
Quoted 48 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain. To enable an unprivileged process to express a file hierarchy, it first needs to open a directory (or a file) and pass this file descriptor to the kernel through landlock_add_rule(2). When checking if a file access request is allowed, we walk from the requested dentry to the real root, following the different mount layers. The access to each "tagged" inodes are collected according to their rule layer level, and ANDed to create access to the requested file hierarchy. This makes possible to identify a lot of files without tagging every inodes nor modifying the filesystem, while still following the view and understanding the user has from the filesystem.

Add a new ARCH_EPHEMERAL_INODES for UML because it currently does not keep the same struct inodes for the same inodes whereas these inodes are in use.

This commit adds a minimal set of supported filesystem access-control which doesn't enable to restrict all file-related actions. This is the result of multiple discussions to minimize the code of Landlock to ease review. Thanks to the Landlock design, extending this access-control without breaking user space will not be a problem. Moreover, seccomp filters can be used to restrict the use of syscall families which may not be currently handled by Landlock.

Cc Al Viro <[email protected]>
Cc Anton Ivanov <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jeff Dike <[email protected]>
Cc Kees Cook <[email protected]>
Cc Richard Weinberger <[email protected]>
Cc Serge E. Hallyn <[email protected]>
[...]
security/landlock/fs.c new file +10 -0
+	spin_lock(&sb->s_inode_list_lock);
+	list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
+		struct landlock_object *object;
+
+		/* Only handles referenced inodes. */
+		if (!atomic_read(&inode->i_count))
+			continue;
+
+		/*
+		 * Checks I_FREEING and I_WILL_FREE  to protect against a race

security/landlock/fs.c line 363

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+		 * condition when release_inode() just called iput(), which
+		 * could lead to a NULL dereference of inode->security or a
+		 * second call to iput() for the same Landlock object.  Also
+		 * checks I_NEW because such inode cannot be tied to an object.
+		 */
+		spin_lock(&inode->i_lock);
+		if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
+			spin_unlock(&inode->i_lock);
+			continue;
+		}

This (and elsewhere here) seems like a lot of inode internals getting exposed. Can any of this be repurposed into helpers? I see this test scattered around the kernel a fair bit:

Quoted 2 lines
$ git grep I_FREEING | grep I_WILL_FREE | grep I_NEW | wc -l
9

Dealing with the filesystem is complex. Some helpers could probably be added, but with a series dedicated to the filesystem. I can work on that once this series is merged.

Quoted 18 lines
Quoted 18 lines
security/landlock/fs.c new file +17 -0
+static inline u32 get_mode_access(const umode_t mode)
+{
+	switch (mode & S_IFMT) {
+	case S_IFLNK:
+		return LANDLOCK_ACCESS_FS_MAKE_SYM;
+	case 0:
+		/* A zero mode translates to S_IFREG. */
+	case S_IFREG:
+		return LANDLOCK_ACCESS_FS_MAKE_REG;
+	case S_IFDIR:
+		return LANDLOCK_ACCESS_FS_MAKE_DIR;
+	case S_IFCHR:
+		return LANDLOCK_ACCESS_FS_MAKE_CHAR;
+	case S_IFBLK:
+		return LANDLOCK_ACCESS_FS_MAKE_BLOCK;
+	case S_IFIFO:
+		return LANDLOCK_ACCESS_FS_MAKE_FIFO;
Quoted 8 lines

security/landlock/fs.c line 531

Quoted 6 lines
security/landlock/fs.c new file +6 -0
+	case S_IFSOCK:
+		return LANDLOCK_ACCESS_FS_MAKE_SOCK;
+	default:
+		WARN_ON_ONCE(1);
+		return 0;
+	}

I'm assuming this won't be reachable from userspace.

It should not, only a bogus kernel code could.

Quoted 21 lines
Quoted 21 lines

[...]
index a5d6ef334991..f8e8e980454c 100644

security/landlock/setup.c +5 -0
@@ -11,17 +11,24 @@
 
 #include "common.h"
 #include "cred.h"
+#include "fs.h"
 #include "ptrace.h"
 #include "setup.h"
 
+bool landlock_initialized __lsm_ro_after_init = false;
+
 struct lsm_blob_sizes landlock_blob_sizes __lsm_ro_after_init = {
 	.lbs_cred = sizeof(struct landlock_cred_security),
+	.lbs_inode = sizeof(struct landlock_inode_security),
+	.lbs_superblock = sizeof(struct landlock_superblock_security),
 };
 
Quoted 9 lines

security/landlock/setup.c line 31

Quoted 6 lines
security/landlock/setup.c +2 -0
 static int __init landlock_init(void)
 {
 	landlock_add_cred_hooks();
 	landlock_add_ptrace_hooks();
+	landlock_add_fs_hooks();
+	landlock_initialized = true;

I think this landlock_initialized is logically separate from the optional DEFINE_LSM "enabled" variable, but I thought I'd double check. :)

Quoted 33 lines

An LSM can be marked as enabled (at boot) but not yet initialized.

Quoted 3 lines

It seems like it's used here to avoid releasing superblocks before landlock_init() is called? What is the scenario where that happens?

It is a condition for LSM hooks, syscalls and superblock management.

Quoted 25 lines
Quoted 20 lines
security/landlock/setup.c +0 -0
 	pr_info("Up and running.\n");
 	return 0;
 }
security/landlock/setup.h +2 -0
index 9fdbf33fcc33..1daffab1ab4b 100644
@@ -11,6 +11,8 @@
 
 #include <linux/lsm_hooks.h>
 
+extern bool landlock_initialized;
+
 extern struct lsm_blob_sizes landlock_blob_sizes;
 
 #endif /* _SECURITY_LANDLOCK_SETUP_H */
Signature · 1 line
2.30.2

The locking and inode semantics are pretty complex, but since, again, it's got significant test and syzkaller coverage, it looks good to me.

With the inode helper cleanup:

I think the inode helper would have to be in a separate patch focused on fs/ (like all matches of your greps, except Landlock). Are you OK if I send a patch for that once Landlock is merged?

Quoted 3 lines
Quoted 3 lines
#25 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

In reply to Mickaël Salaün
Quoted 2 lines · Mickaël Salaün

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain.

[...]

Quoted 38 lines
security/landlock/fs.c new file +38 -0
+static void release_inode(struct landlock_object *const object)
+       __releases(object->lock)
+{
+       struct inode *const inode = object->underobj;
+       struct super_block *sb;
+
+       if (!inode) {
+               spin_unlock(&object->lock);
+               return;
+       }
+
+       /*
+        * Protects against concurrent use by hook_sb_delete() of the reference
+        * to the underlying inode.
+        */
+       object->underobj = NULL;
+       /*
+        * Makes sure that if the filesystem is concurrently unmounted,
+        * hook_sb_delete() will wait for us to finish iput().
+        */
+       sb = inode->i_sb;
+       atomic_long_inc(&landlock_superblock(sb)->inode_refs);
+       spin_unlock(&object->lock);
+       /*
+        * Because object->underobj was not NULL, hook_sb_delete() and
+        * get_inode_object() guarantee that it is safe to reset
+        * landlock_inode(inode)->object while it is not NULL.  It is therefore
+        * not necessary to lock inode->i_lock.
+        */
+       rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+       /*
+        * Now, new rules can safely be tied to @inode with get_inode_object().
+        */
+
+       iput(inode);
+       if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
+               wake_up_var(&landlock_superblock(sb)->inode_refs);
+}

[...]

Quoted 25 lines
security/landlock/fs.c new file +25 -0
+static struct landlock_object *get_inode_object(struct inode *const inode)
+{
+       struct landlock_object *object, *new_object;
+       struct landlock_inode_security *inode_sec = landlock_inode(inode);
+
+       rcu_read_lock();
+retry:
+       object = rcu_dereference(inode_sec->object);
+       if (object) {
+               if (likely(refcount_inc_not_zero(&object->usage))) {
+                       rcu_read_unlock();
+                       return object;
+               }
+               /*
+                * We are racing with release_inode(), the object is going
+                * away.  Wait for release_inode(), then retry.
+                */
+               spin_lock(&object->lock);
+               spin_unlock(&object->lock);
+               goto retry;
+       }
+       rcu_read_unlock();
+
+       /*
+        * If there is no object tied to @inode, then create a new one (without

security/landlock/fs.c line 121

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+        * holding any locks).
+        */
+       new_object = landlock_create_object(&landlock_fs_underops, inode);
+       if (IS_ERR(new_object))
+               return new_object;
+
+       /* Protects against concurrent get_inode_object() calls. */
+       spin_lock(&inode->i_lock);
+       object = rcu_dereference_protected(inode_sec->object,
+                       lockdep_is_held(&inode->i_lock));

rcu_dereference_protected() requires that inode_sec->object is not concurrently changed, but I think another thread could call get_inode_object() while we're in landlock_create_object(), and then we could race with the NULL write in release_inode() here? (It wouldn't actually be a UAF though because we're not actually accessing object here.) Or am I missing a lock that prevents this?

In v28 this wasn't an issue because release_inode() was holding inode->i_lock (and object->lock) during the NULL store; but in v29 and this version the NULL store in release_inode() moved out of the locked region. I think you could just move the NULL store in release_inode() back up (and maybe add a comment explaining the locking rules for landlock_inode(...)->object)?

(Or alternatively you could use rcu_dereference_raw() with a comment explaining that the read pointer is only used to check for NULL-ness, and that it is guaranteed that the pointer can't change if it is NULL and we're holding the lock. But that'd be needlessly complicated, I think.)

Quoted 18 lines
security/landlock/fs.c new file +18 -0
+       if (unlikely(object)) {
+               /* Someone else just created the object, bail out and retry. */
+               spin_unlock(&inode->i_lock);
+               kfree(new_object);
+
+               rcu_read_lock();
+               goto retry;
+       }
+
+       rcu_assign_pointer(inode_sec->object, new_object);
+       /*
+        * @inode will be released by hook_sb_delete() on its superblock
+        * shutdown.
+        */
+       ihold(inode);
+       spin_unlock(&inode->i_lock);
+       return new_object;
+}
author maintainer
#26 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 93 lines · Jann Horn
Quoted 2 lines · Mickaël Salaün

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain.

[...]

Quoted 38 lines
security/landlock/fs.c new file +38 -0
+static void release_inode(struct landlock_object *const object)
+       __releases(object->lock)
+{
+       struct inode *const inode = object->underobj;
+       struct super_block *sb;
+
+       if (!inode) {
+               spin_unlock(&object->lock);
+               return;
+       }
+
+       /*
+        * Protects against concurrent use by hook_sb_delete() of the reference
+        * to the underlying inode.
+        */
+       object->underobj = NULL;
+       /*
+        * Makes sure that if the filesystem is concurrently unmounted,
+        * hook_sb_delete() will wait for us to finish iput().
+        */
+       sb = inode->i_sb;
+       atomic_long_inc(&landlock_superblock(sb)->inode_refs);
+       spin_unlock(&object->lock);
+       /*
+        * Because object->underobj was not NULL, hook_sb_delete() and
+        * get_inode_object() guarantee that it is safe to reset
+        * landlock_inode(inode)->object while it is not NULL.  It is therefore
+        * not necessary to lock inode->i_lock.
+        */
+       rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+       /*
+        * Now, new rules can safely be tied to @inode with get_inode_object().
+        */
+
+       iput(inode);
+       if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
+               wake_up_var(&landlock_superblock(sb)->inode_refs);
+}

[...]

Quoted 25 lines
security/landlock/fs.c new file +25 -0
+static struct landlock_object *get_inode_object(struct inode *const inode)
+{
+       struct landlock_object *object, *new_object;
+       struct landlock_inode_security *inode_sec = landlock_inode(inode);
+
+       rcu_read_lock();
+retry:
+       object = rcu_dereference(inode_sec->object);
+       if (object) {
+               if (likely(refcount_inc_not_zero(&object->usage))) {
+                       rcu_read_unlock();
+                       return object;
+               }
+               /*
+                * We are racing with release_inode(), the object is going
+                * away.  Wait for release_inode(), then retry.
+                */
+               spin_lock(&object->lock);
+               spin_unlock(&object->lock);
+               goto retry;
+       }
+       rcu_read_unlock();
+
+       /*
+        * If there is no object tied to @inode, then create a new one (without

security/landlock/fs.c line 121

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+        * holding any locks).
+        */
+       new_object = landlock_create_object(&landlock_fs_underops, inode);
+       if (IS_ERR(new_object))
+               return new_object;
+
+       /* Protects against concurrent get_inode_object() calls. */
+       spin_lock(&inode->i_lock);
+       object = rcu_dereference_protected(inode_sec->object,
+                       lockdep_is_held(&inode->i_lock));

rcu_dereference_protected() requires that inode_sec->object is not concurrently changed, but I think another thread could call get_inode_object() while we're in landlock_create_object(), and then we could race with the NULL write in release_inode() here? (It wouldn't actually be a UAF though because we're not actually accessing object here.) Or am I missing a lock that prevents this?

In v28 this wasn't an issue because release_inode() was holding inode->i_lock (and object->lock) during the NULL store; but in v29 and this version the NULL store in release_inode() moved out of the locked region. I think you could just move the NULL store in release_inode() back up (and maybe add a comment explaining the locking rules for landlock_inode(...)->object)?

Quoted 5 lines

(Or alternatively you could use rcu_dereference_raw() with a comment explaining that the read pointer is only used to check for NULL-ness, and that it is guaranteed that the pointer can't change if it is NULL and we're holding the lock. But that'd be needlessly complicated, I think.)

To reach rcu_assign_pointer(landlock_inode(inode)->object, NULL) in release_inode() or in hook_sb_delete(), the landlock_inode(inode)->object need to be non-NULL, which implies that a call to get_inode_object(inode) either "retry" (because release_inode is only called by landlock_put_object, which set object->usage to 0) until it creates a new object, or reuses the existing referenced object (and increments object->usage). The worse case would be if get_inode_object(inode) is called just before the rcu_assign_pointer(landlock_inode(inode)->object, NULL) from hook_sb_delete(), which would result in an object with a NULL underobj, which is the expected behavior (and checked by release_inode).

The line rcu_assign_pointer(inode_sec->object, new_object) from get_inode_object() can only be reached if the underlying inode doesn't reference an object, in which case hook_sb_delete() will not reach the rcu_assign_pointer(landlock_inode(inode)->object, NULL) line for this same inode.

This works because get_inode_object(inode) is mutually exclusive to itself with the same inode (i.e. an inode can only point to an object that references this same inode).

I tried to explain this with the comment "Protects against concurrent get_inode_object() calls" in get_inode_object(), and the comments just before both rcu_assign_pointer(landlock_inode(inode)->object, NULL).

Quoted 20 lines
Quoted 20 lines
security/landlock/fs.c new file +18 -0
+       if (unlikely(object)) {
+               /* Someone else just created the object, bail out and retry. */
+               spin_unlock(&inode->i_lock);
+               kfree(new_object);
+
+               rcu_read_lock();
+               goto retry;
+       }
+
+       rcu_assign_pointer(inode_sec->object, new_object);
+       /*
+        * @inode will be released by hook_sb_delete() on its superblock
+        * shutdown.
+        */
+       ihold(inode);
+       spin_unlock(&inode->i_lock);
+       return new_object;
+}
#27 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 100 lines · Mickaël Salaün
Quoted 93 lines · Jann Horn
Quoted 2 lines · Mickaël Salaün

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain.

[...]

Quoted 38 lines
security/landlock/fs.c new file +38 -0
+static void release_inode(struct landlock_object *const object)
+       __releases(object->lock)
+{
+       struct inode *const inode = object->underobj;
+       struct super_block *sb;
+
+       if (!inode) {
+               spin_unlock(&object->lock);
+               return;
+       }
+
+       /*
+        * Protects against concurrent use by hook_sb_delete() of the reference
+        * to the underlying inode.
+        */
+       object->underobj = NULL;
+       /*
+        * Makes sure that if the filesystem is concurrently unmounted,
+        * hook_sb_delete() will wait for us to finish iput().
+        */
+       sb = inode->i_sb;
+       atomic_long_inc(&landlock_superblock(sb)->inode_refs);
+       spin_unlock(&object->lock);
+       /*
+        * Because object->underobj was not NULL, hook_sb_delete() and
+        * get_inode_object() guarantee that it is safe to reset
+        * landlock_inode(inode)->object while it is not NULL.  It is therefore
+        * not necessary to lock inode->i_lock.
+        */
+       rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+       /*
+        * Now, new rules can safely be tied to @inode with get_inode_object().
+        */
+
+       iput(inode);
+       if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
+               wake_up_var(&landlock_superblock(sb)->inode_refs);
+}

[...]

Quoted 25 lines
security/landlock/fs.c new file +25 -0
+static struct landlock_object *get_inode_object(struct inode *const inode)
+{
+       struct landlock_object *object, *new_object;
+       struct landlock_inode_security *inode_sec = landlock_inode(inode);
+
+       rcu_read_lock();
+retry:
+       object = rcu_dereference(inode_sec->object);
+       if (object) {
+               if (likely(refcount_inc_not_zero(&object->usage))) {
+                       rcu_read_unlock();
+                       return object;
+               }
+               /*
+                * We are racing with release_inode(), the object is going
+                * away.  Wait for release_inode(), then retry.
+                */
+               spin_lock(&object->lock);
+               spin_unlock(&object->lock);
+               goto retry;
+       }
+       rcu_read_unlock();
+
+       /*
+        * If there is no object tied to @inode, then create a new one (without

security/landlock/fs.c line 121

Quoted 10 lines
security/landlock/fs.c new file +10 -0
+        * holding any locks).
+        */
+       new_object = landlock_create_object(&landlock_fs_underops, inode);
+       if (IS_ERR(new_object))
+               return new_object;
+
+       /* Protects against concurrent get_inode_object() calls. */
+       spin_lock(&inode->i_lock);
+       object = rcu_dereference_protected(inode_sec->object,
+                       lockdep_is_held(&inode->i_lock));

rcu_dereference_protected() requires that inode_sec->object is not concurrently changed, but I think another thread could call get_inode_object() while we're in landlock_create_object(), and then we could race with the NULL write in release_inode() here? (It wouldn't actually be a UAF though because we're not actually accessing object here.) Or am I missing a lock that prevents this?

In v28 this wasn't an issue because release_inode() was holding inode->i_lock (and object->lock) during the NULL store; but in v29 and this version the NULL store in release_inode() moved out of the locked region. I think you could just move the NULL store in release_inode() back up (and maybe add a comment explaining the locking rules for landlock_inode(...)->object)?

Quoted 5 lines

(Or alternatively you could use rcu_dereference_raw() with a comment explaining that the read pointer is only used to check for NULL-ness, and that it is guaranteed that the pointer can't change if it is NULL and we're holding the lock. But that'd be needlessly complicated, I think.)

Quoted 3 lines

To reach rcu_assign_pointer(landlock_inode(inode)->object, NULL) in release_inode() or in hook_sb_delete(), the landlock_inode(inode)->object need to be non-NULL,

Yes.

Quoted 5 lines

which implies that a
call to get_inode_object(inode) either "retry" (because release_inode is only called by landlock_put_object, which set object->usage to 0) until it creates a new object, or reuses the existing referenced object (and increments object->usage).

But it can be that landlock_inode(inode)->object only becomes non-NULL after get_inode_object() has checked rcu_dereference(inode_sec->object).

Quoted 5 lines

The worse case would be if
get_inode_object(inode) is called just before the rcu_assign_pointer(landlock_inode(inode)->object, NULL) from hook_sb_delete(), which would result in an object with a NULL underobj, which is the expected behavior (and checked by release_inode).

The scenario I'm talking about doesn't involve hook_sb_delete().

Quoted 3 lines

The line rcu_assign_pointer(inode_sec->object, new_object) from get_inode_object() can only be reached if the underlying inode doesn't reference an object,

Yes.

Quoted 7 lines

in which case hook_sb_delete() will not reach the rcu_assign_pointer(landlock_inode(inode)->object, NULL) line for this same inode.

This works because get_inode_object(inode) is mutually exclusive to itself with the same inode (i.e. an inode can only point to an object that references this same inode).

To clarify: You can concurrently call get_inode_object() multiple times on the same inode, right? There are no locks held on entry to that function.

Quoted 3 lines

I tried to explain this with the comment "Protects against concurrent get_inode_object() calls" in get_inode_object(), and the comments just before both rcu_assign_pointer(landlock_inode(inode)->object, NULL).

The scenario I'm talking about is:

Initially the inode does not have an associated landlock_object. There are two threads A and B. Thread A is going to execute get_inode_object(). Thread B is going to execute get_inode_object() followed immediately by landlock_put_object().

thread A: enters get_inode_object()
thread A: rcu_dereference(inode_sec->object) returns NULL thread A: enters landlock_create_object()
thread B: enters get_inode_object()
thread B: rcu_dereference(inode_sec->object) returns NULL thread B: calls landlock_create_object()
thread B: sets inode_sec->object while holding inode->i_lock thread B: leaves get_inode_object()
thread B: enters landlock_put_object()
thread B: object->usage drops to 0, object->lock is taken thread B: calls release_inode()
thread B: drops object->lock
thread A: returns from landlock_create_object() thread A: takes inode->i_lock

At this point, thread B will run:

    rcu_assign_pointer(landlock_inode(inode)->object, NULL);

while thread A runs:

    rcu_dereference_protected(inode_sec->object,
        lockdep_is_held(&inode->i_lock));

meaning there is a (theoretical) data race, since rcu_dereference_protected() doesn't use READ_ONCE().

Quoted 18 lines
Quoted 18 lines
Quoted 18 lines
security/landlock/fs.c new file +18 -0
+       if (unlikely(object)) {
+               /* Someone else just created the object, bail out and retry. */
+               spin_unlock(&inode->i_lock);
+               kfree(new_object);
+
+               rcu_read_lock();
+               goto retry;
+       }
+
+       rcu_assign_pointer(inode_sec->object, new_object);
+       /*
+        * @inode will be released by hook_sb_delete() on its superblock
+        * shutdown.
+        */
+       ihold(inode);
+       spin_unlock(&inode->i_lock);
+       return new_object;
+}
author maintainer
#28 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 173 lines · Jann Horn
Quoted 100 lines · Mickaël Salaün
Quoted 93 lines · Jann Horn
Quoted 2 lines · Mickaël Salaün

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain.

[...]

Quoted 38 lines
(quoted diff) +38 -0
+static void release_inode(struct landlock_object *const object)
+       __releases(object->lock)
+{
+       struct inode *const inode = object->underobj;
+       struct super_block *sb;
+
+       if (!inode) {
+               spin_unlock(&object->lock);
+               return;
+       }
+
+       /*
+        * Protects against concurrent use by hook_sb_delete() of the reference
+        * to the underlying inode.
+        */
+       object->underobj = NULL;
+       /*
+        * Makes sure that if the filesystem is concurrently unmounted,
+        * hook_sb_delete() will wait for us to finish iput().
+        */
+       sb = inode->i_sb;
+       atomic_long_inc(&landlock_superblock(sb)->inode_refs);
+       spin_unlock(&object->lock);
+       /*
+        * Because object->underobj was not NULL, hook_sb_delete() and
+        * get_inode_object() guarantee that it is safe to reset
+        * landlock_inode(inode)->object while it is not NULL.  It is therefore
+        * not necessary to lock inode->i_lock.
+        */
+       rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+       /*
+        * Now, new rules can safely be tied to @inode with get_inode_object().
+        */
+
+       iput(inode);
+       if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
+               wake_up_var(&landlock_superblock(sb)->inode_refs);
+}

[...]

Quoted 25 lines
(quoted diff) +25 -0
+static struct landlock_object *get_inode_object(struct inode *const inode)
+{
+       struct landlock_object *object, *new_object;
+       struct landlock_inode_security *inode_sec = landlock_inode(inode);
+
+       rcu_read_lock();
+retry:
+       object = rcu_dereference(inode_sec->object);
+       if (object) {
+               if (likely(refcount_inc_not_zero(&object->usage))) {
+                       rcu_read_unlock();
+                       return object;
+               }
+               /*
+                * We are racing with release_inode(), the object is going
+                * away.  Wait for release_inode(), then retry.
+                */
+               spin_lock(&object->lock);
+               spin_unlock(&object->lock);
+               goto retry;
+       }
+       rcu_read_unlock();
+
+       /*
+        * If there is no object tied to @inode, then create a new one (without

Review

Quoted 10 lines
(quoted diff) +10 -0
+        * holding any locks).
+        */
+       new_object = landlock_create_object(&landlock_fs_underops, inode);
+       if (IS_ERR(new_object))
+               return new_object;
+
+       /* Protects against concurrent get_inode_object() calls. */
+       spin_lock(&inode->i_lock);
+       object = rcu_dereference_protected(inode_sec->object,
+                       lockdep_is_held(&inode->i_lock));

rcu_dereference_protected() requires that inode_sec->object is not concurrently changed, but I think another thread could call get_inode_object() while we're in landlock_create_object(), and then we could race with the NULL write in release_inode() here? (It wouldn't actually be a UAF though because we're not actually accessing object here.) Or am I missing a lock that prevents this?

In v28 this wasn't an issue because release_inode() was holding inode->i_lock (and object->lock) during the NULL store; but in v29 and this version the NULL store in release_inode() moved out of the locked region. I think you could just move the NULL store in release_inode() back up (and maybe add a comment explaining the locking rules for landlock_inode(...)->object)?

Quoted 5 lines

(Or alternatively you could use rcu_dereference_raw() with a comment explaining that the read pointer is only used to check for NULL-ness, and that it is guaranteed that the pointer can't change if it is NULL and we're holding the lock. But that'd be needlessly complicated, I think.)

Quoted 3 lines

To reach rcu_assign_pointer(landlock_inode(inode)->object, NULL) in release_inode() or in hook_sb_delete(), the landlock_inode(inode)->object need to be non-NULL,

Yes.

Quoted 5 lines

which implies that a
call to get_inode_object(inode) either "retry" (because release_inode is only called by landlock_put_object, which set object->usage to 0) until it creates a new object, or reuses the existing referenced object (and increments object->usage).

But it can be that landlock_inode(inode)->object only becomes non-NULL after get_inode_object() has checked rcu_dereference(inode_sec->object).

Quoted 5 lines

The worse case would be if
get_inode_object(inode) is called just before the rcu_assign_pointer(landlock_inode(inode)->object, NULL) from hook_sb_delete(), which would result in an object with a NULL underobj, which is the expected behavior (and checked by release_inode).

The scenario I'm talking about doesn't involve hook_sb_delete().

Quoted 3 lines

The line rcu_assign_pointer(inode_sec->object, new_object) from get_inode_object() can only be reached if the underlying inode doesn't reference an object,

Yes.

Quoted 7 lines

in which case hook_sb_delete() will not reach the rcu_assign_pointer(landlock_inode(inode)->object, NULL) line for this same inode.

This works because get_inode_object(inode) is mutually exclusive to itself with the same inode (i.e. an inode can only point to an object that references this same inode).

To clarify: You can concurrently call get_inode_object() multiple times on the same inode, right? There are no locks held on entry to that function.

Quoted 3 lines

I tried to explain this with the comment "Protects against concurrent get_inode_object() calls" in get_inode_object(), and the comments just before both rcu_assign_pointer(landlock_inode(inode)->object, NULL).

The scenario I'm talking about is:

Initially the inode does not have an associated landlock_object. There are two threads A and B. Thread A is going to execute get_inode_object(). Thread B is going to execute get_inode_object() followed immediately by landlock_put_object().

thread A: enters get_inode_object()
thread A: rcu_dereference(inode_sec->object) returns NULL thread A: enters landlock_create_object()
thread B: enters get_inode_object()
thread B: rcu_dereference(inode_sec->object) returns NULL thread B: calls landlock_create_object()
thread B: sets inode_sec->object while holding inode->i_lock thread B: leaves get_inode_object()
thread B: enters landlock_put_object()
thread B: object->usage drops to 0, object->lock is taken thread B: calls release_inode()
thread B: drops object->lock
thread A: returns from landlock_create_object() thread A: takes inode->i_lock

At this point, thread B will run:

    rcu_assign_pointer(landlock_inode(inode)->object, NULL);
Quoted 7 lines

while thread A runs:

    rcu_dereference_protected(inode_sec->object,
        lockdep_is_held(&inode->i_lock));

meaning there is a (theoretical) data race, since rcu_dereference_protected() doesn't use READ_ONCE().

Hum, I see, that is what I was missing. And that explain why there is (in practice) no impact on winning the race.

I would prefer to use rcu_access_pointer() instead of rcu_dereference_protected() to avoid pitfall, and it reflects what I was expecting:

security/landlock/fs.c +0 -0
@@ -117,9 +117,7 @@ static struct landlock_object

*get_inode_object(struct inode *const inode)

        /* Protects against concurrent get_inode_object() calls. */
        spin_lock(&inode->i_lock);
-       object = rcu_dereference_protected(inode_sec->object,
-                       lockdep_is_held(&inode->i_lock));
-       if (unlikely(object)) {
+       if (unlikely(rcu_access_pointer(inode_sec->object))) {
                /* Someone else just created the object, bail out and
retry. */
                spin_unlock(&inode->i_lock);
                kfree(new_object);

But I'm not sure about your proposition to move the NULL store in release_inode() back up. Do you mean to add back the inode lock in release_inode() like this?

security/landlock/fs.c +0 -0
@@ -59,16 +59,12 @@ static void release_inode(struct landlock_object

*const object)
* Makes sure that if the filesystem is concurrently unmounted,
* hook_sb_delete() will wait for us to finish iput().
*/
+ spin_lock(&inode->i_lock);
sb = inode->i_sb; atomic_long_inc(&landlock_superblock(sb)->inode_refs); spin_unlock(&object->lock);
- /*
- * Because object->underobj was not NULL, hook_sb_delete() and
- * get_inode_object() guarantee that it is safe to reset
- * landlock_inode(inode)->object while it is not NULL. It is therefore
- * not necessary to lock inode->i_lock.
- */
rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+ spin_unlock(&inode->i_lock);
/*
* Now, new rules can safely be tied to @inode with get_inode_object(). */

I would prefer to avoid nested locks if it is not necessary though.

Quoted 19 lines
Quoted 19 lines
Quoted 19 lines
Quoted 19 lines
(quoted diff) +18 -0
+       if (unlikely(object)) {
+               /* Someone else just created the object, bail out and retry. */
+               spin_unlock(&inode->i_lock);
+               kfree(new_object);
+
+               rcu_read_lock();
+               goto retry;
+       }
+
+       rcu_assign_pointer(inode_sec->object, new_object);
+       /*
+        * @inode will be released by hook_sb_delete() on its superblock
+        * shutdown.
+        */
+       ihold(inode);
+       spin_unlock(&inode->i_lock);
+       return new_object;
+}
#29 lore raw

Re: [PATCH v30 07/12] landlock: Support filesystem access-control

Quoted 202 lines · Mickaël Salaün
Quoted 173 lines · Jann Horn
Quoted 100 lines · Mickaël Salaün
Quoted 93 lines · Jann Horn
Quoted 2 lines · Mickaël Salaün

Using Landlock objects and ruleset, it is possible to tag inodes according to a process's domain.

[...]

Quoted 38 lines
(quoted diff) +38 -0
+static void release_inode(struct landlock_object *const object)
+       __releases(object->lock)
+{
+       struct inode *const inode = object->underobj;
+       struct super_block *sb;
+
+       if (!inode) {
+               spin_unlock(&object->lock);
+               return;
+       }
+
+       /*
+        * Protects against concurrent use by hook_sb_delete() of the reference
+        * to the underlying inode.
+        */
+       object->underobj = NULL;
+       /*
+        * Makes sure that if the filesystem is concurrently unmounted,
+        * hook_sb_delete() will wait for us to finish iput().
+        */
+       sb = inode->i_sb;
+       atomic_long_inc(&landlock_superblock(sb)->inode_refs);
+       spin_unlock(&object->lock);
+       /*
+        * Because object->underobj was not NULL, hook_sb_delete() and
+        * get_inode_object() guarantee that it is safe to reset
+        * landlock_inode(inode)->object while it is not NULL.  It is therefore
+        * not necessary to lock inode->i_lock.
+        */
+       rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+       /*
+        * Now, new rules can safely be tied to @inode with get_inode_object().
+        */
+
+       iput(inode);
+       if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
+               wake_up_var(&landlock_superblock(sb)->inode_refs);
+}

[...]

Quoted 25 lines
(quoted diff) +25 -0
+static struct landlock_object *get_inode_object(struct inode *const inode)
+{
+       struct landlock_object *object, *new_object;
+       struct landlock_inode_security *inode_sec = landlock_inode(inode);
+
+       rcu_read_lock();
+retry:
+       object = rcu_dereference(inode_sec->object);
+       if (object) {
+               if (likely(refcount_inc_not_zero(&object->usage))) {
+                       rcu_read_unlock();
+                       return object;
+               }
+               /*
+                * We are racing with release_inode(), the object is going
+                * away.  Wait for release_inode(), then retry.
+                */
+               spin_lock(&object->lock);
+               spin_unlock(&object->lock);
+               goto retry;
+       }
+       rcu_read_unlock();
+
+       /*
+        * If there is no object tied to @inode, then create a new one (without

Review

Quoted 10 lines
(quoted diff) +10 -0
+        * holding any locks).
+        */
+       new_object = landlock_create_object(&landlock_fs_underops, inode);
+       if (IS_ERR(new_object))
+               return new_object;
+
+       /* Protects against concurrent get_inode_object() calls. */
+       spin_lock(&inode->i_lock);
+       object = rcu_dereference_protected(inode_sec->object,
+                       lockdep_is_held(&inode->i_lock));

rcu_dereference_protected() requires that inode_sec->object is not concurrently changed, but I think another thread could call get_inode_object() while we're in landlock_create_object(), and then we could race with the NULL write in release_inode() here? (It wouldn't actually be a UAF though because we're not actually accessing object here.) Or am I missing a lock that prevents this?

In v28 this wasn't an issue because release_inode() was holding inode->i_lock (and object->lock) during the NULL store; but in v29 and this version the NULL store in release_inode() moved out of the locked region. I think you could just move the NULL store in release_inode() back up (and maybe add a comment explaining the locking rules for landlock_inode(...)->object)?

Quoted 5 lines

(Or alternatively you could use rcu_dereference_raw() with a comment explaining that the read pointer is only used to check for NULL-ness, and that it is guaranteed that the pointer can't change if it is NULL and we're holding the lock. But that'd be needlessly complicated, I think.)

Quoted 3 lines

To reach rcu_assign_pointer(landlock_inode(inode)->object, NULL) in release_inode() or in hook_sb_delete(), the landlock_inode(inode)->object need to be non-NULL,

Yes.

Quoted 5 lines

which implies that a
call to get_inode_object(inode) either "retry" (because release_inode is only called by landlock_put_object, which set object->usage to 0) until it creates a new object, or reuses the existing referenced object (and increments object->usage).

But it can be that landlock_inode(inode)->object only becomes non-NULL after get_inode_object() has checked rcu_dereference(inode_sec->object).

Quoted 5 lines

The worse case would be if
get_inode_object(inode) is called just before the rcu_assign_pointer(landlock_inode(inode)->object, NULL) from hook_sb_delete(), which would result in an object with a NULL underobj, which is the expected behavior (and checked by release_inode).

The scenario I'm talking about doesn't involve hook_sb_delete().

Quoted 3 lines

The line rcu_assign_pointer(inode_sec->object, new_object) from get_inode_object() can only be reached if the underlying inode doesn't reference an object,

Yes.

Quoted 7 lines

in which case hook_sb_delete() will not reach the rcu_assign_pointer(landlock_inode(inode)->object, NULL) line for this same inode.

This works because get_inode_object(inode) is mutually exclusive to itself with the same inode (i.e. an inode can only point to an object that references this same inode).

To clarify: You can concurrently call get_inode_object() multiple times on the same inode, right? There are no locks held on entry to that function.

Quoted 3 lines

I tried to explain this with the comment "Protects against concurrent get_inode_object() calls" in get_inode_object(), and the comments just before both rcu_assign_pointer(landlock_inode(inode)->object, NULL).

The scenario I'm talking about is:

Initially the inode does not have an associated landlock_object. There are two threads A and B. Thread A is going to execute get_inode_object(). Thread B is going to execute get_inode_object() followed immediately by landlock_put_object().

thread A: enters get_inode_object()
thread A: rcu_dereference(inode_sec->object) returns NULL thread A: enters landlock_create_object()
thread B: enters get_inode_object()
thread B: rcu_dereference(inode_sec->object) returns NULL thread B: calls landlock_create_object()
thread B: sets inode_sec->object while holding inode->i_lock thread B: leaves get_inode_object()
thread B: enters landlock_put_object()
thread B: object->usage drops to 0, object->lock is taken thread B: calls release_inode()
thread B: drops object->lock
thread A: returns from landlock_create_object() thread A: takes inode->i_lock

At this point, thread B will run:

    rcu_assign_pointer(landlock_inode(inode)->object, NULL);
Quoted 7 lines

while thread A runs:

    rcu_dereference_protected(inode_sec->object,
        lockdep_is_held(&inode->i_lock));

meaning there is a (theoretical) data race, since rcu_dereference_protected() doesn't use READ_ONCE().

Hum, I see, that is what I was missing. And that explain why there is (in practice) no impact on winning the race.

I would prefer to use rcu_access_pointer() instead of rcu_dereference_protected() to avoid pitfall, and it reflects what I was expecting:

security/landlock/fs.c +1 -3
@@ -117,9 +117,7 @@ static struct landlock_object
 *get_inode_object(struct inode *const inode)
 
        /* Protects against concurrent get_inode_object() calls. */
        spin_lock(&inode->i_lock);
-       object = rcu_dereference_protected(inode_sec->object,
-                       lockdep_is_held(&inode->i_lock));
-       if (unlikely(object)) {
+       if (unlikely(rcu_access_pointer(inode_sec->object))) {
                /* Someone else just created the object, bail out and

retry. */

Quoted 2 lines
                spin_unlock(&inode->i_lock);
                kfree(new_object);

Ah, yeah, that should work. I had forgotten about rcu_access_pointer().

Quoted 28 lines

But I'm not sure about your proposition to move the NULL store in release_inode() back up. Do you mean to add back the inode lock in release_inode() like this?

security/landlock/fs.c +2 -6
@@ -59,16 +59,12 @@ static void release_inode(struct landlock_object
 *const object)
         * Makes sure that if the filesystem is concurrently unmounted,
         * hook_sb_delete() will wait for us to finish iput().
         */
+       spin_lock(&inode->i_lock);
        sb = inode->i_sb;
        atomic_long_inc(&landlock_superblock(sb)->inode_refs);
        spin_unlock(&object->lock);
-       /*
-        * Because object->underobj was not NULL, hook_sb_delete() and
-        * get_inode_object() guarantee that it is safe to reset
-        * landlock_inode(inode)->object while it is not NULL.  It is therefore
-        * not necessary to lock inode->i_lock.
-        */
        rcu_assign_pointer(landlock_inode(inode)->object, NULL);
+       spin_unlock(&inode->i_lock);
        /*
         * Now, new rules can safely be tied to @inode with get_inode_object().
         */
Quoted 1 line

I would prefer to avoid nested locks if it is not necessary though.

Hm, yeah, you have a point there.

Doing it locklessly does make the locking rules a little complicated though, and you'll have to update the comment inside struct landlock_inode_security. At the moment, it says:

* @object: Weak pointer to an allocated object. All writes (i.e.
* creating a new object or removing one) are protected by the
* underlying inode->i_lock. Disassociating @object from the inode is
* additionally protected by @object->lock, from the time @object's
* usage refcount drops to zero to the time this pointer is nulled out.

which isn't true anymore.

author maintainer
#30 lore raw

PATCH v30 8/12 landlock: Add syscall implementations

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

These 3 system calls are designed to be used by unprivileged processes to sandbox themselves:
* landlock_create_ruleset(2): Creates a ruleset and returns its file descriptor.
* landlock_add_rule(2): Adds a rule (e.g. file hierarchy access) to a ruleset, identified by the dedicated file descriptor.
* landlock_restrict_self(2): Enforces a ruleset on the calling thread and its future children (similar to seccomp). This syscall has the same usage restrictions as seccomp(2): the caller must have the no_new_privs attribute set or have CAP_SYS_ADMIN in the current user namespace.

All these syscalls have a "flags" argument (not currently used) to enable extensibility.

Here are the motivations for these new syscalls:
* A sandboxed process may not have access to file systems, including /dev, /sys or /proc, but it should still be able to add more restrictions to itself.
* Neither prctl(2) nor seccomp(2) (which was used in a previous version) fit well with the current definition of a Landlock security policy.

All passed structs (attributes) are checked at build time to ensure that they don't contain holes and that they are aligned the same way for each architecture.

See the user and kernel documentation for more details (provided by a following commit):
* Documentation/userspace-api/landlock.rst
* Documentation/security/landlock.rst

---

Changes since v29:
* Rebase on v5.12-rc3 and fix trivial conflict with mount_setattr(2).

Changes since v28:
* Add Acked-by Serge Hallyn.
* Add extra check to be sure to not include ruleset FDs in a dependency of a ruleset (e.g. a path_beneath rule). This case was already forbiden thanks to FMODE_PATH and other flags check, but it makes it explicit now.

Changes since v27:
* Forbid creation of rules with an empty allowed_access value because they are now ignored (since v26) in path walks.
* Rename landlock_enforce_ruleset_self(2) to landlock_restrict_self(2):
shorter and consistent with the two other syscalls (i.e. verb + direct object).
* Update ruleset access check according to the new access stack.
* Improve landlock_add_rule(2) documentation.
* Fix comment.
* Remove Reviewed-by Jann Horn because of the above changes.

Changes since v26:
* Rename landlock_enforce_ruleset_current(2) to landlock_enforce_ruleset_self(2). "current" makes sense for a kernel developer, but much less from a user space developer stand point. "self" is widely used to refer to the current task (e.g. /proc/self). "current" may refer to temporal properties, which could be added later to this syscall flags (cf. /proc/self/attr/{current,exec}).
* Simplify build_check_abi().
* Rename syscall.c to syscalls.c .
* Use less ambiguous comments.
* Fix spelling.

Changes since v25:
* Revert build_check_abi() as non-inline to trigger a warning if it is not called.
* Use the new limit names.

Changes since v24:
* Add Reviewed-by: Jann Horn <[email protected]>
* Set build_check_abi() as inline.

Changes since v23:
* Rewrite get_ruleset_from_fd() to please the 0-DAY CI Kernel Test Service that reported an uninitialized variable (false positive):
https://lore.kernel.org/linux-security-module/[email protected]/
Anyway, it is cleaner like this.
* Add a comment about E2BIG which can be returned by landlock_enforce_ruleset_current(2) when there is no more room for another stacked ruleset (i.e. domain).

Changes since v22:
* Replace security_capable() with ns_capable_noaudit() (suggested by Jann Horn) and explicitly return EPERM.
* Fix landlock_enforce_ruleset_current(2)'s out_put_creds (spotted by Jann Horn).
* Add __always_inline to copy_min_struct_from_user() to make its BUILD_BUG_ON() checks reliable (suggested by Jann Horn).
* Simplify path assignation in get_path_from_fd() (suggested by Jann Horn).
* Fix spelling (spotted by Jann Horn).

Changes since v21:
* Fix and improve comments.

Changes since v20:
* Remove two arguments to landlock_enforce_ruleset(2) (requested by Arnd Bergmann) and rename it to landlock_enforce_ruleset_current(2): remove the enum landlock_target_type and the target file descriptor (not used for now). A ruleset can only be enforced on the current thread.
* Remove the size argument in landlock_add_rule() (requested by Arnd Bergmann).
* Remove landlock_get_features(2) (suggested by Arnd Bergmann).
* Simplify and rename copy_struct_if_any_from_user() to copy_min_struct_from_user().
* Rename "options" to "flags" to allign with current syscalls.
* Rename some types and variables in a more consistent way.
* Fix missing type declarations in syscalls.h .

Changes since v19:
* Replace the landlock(2) syscall with 4 syscalls (one for each command): landlock_get_features(2), landlock_create_ruleset(2), landlock_add_rule(2) and landlock_enforce_ruleset(2) (suggested by Arnd Bergmann).
https://lore.kernel.org/lkml/[email protected]/
* Return EOPNOTSUPP (instead of ENOPKG) when Landlock is disabled.
* Add two new fields to landlock_attr_features to fit with the new
syscalls: last_rule_type and last_target_type. This enable to easily identify which types are supported.
* Pack landlock_attr_path_beneath struct because of the removed ruleset_fd.
* Update documentation and fix spelling.

Changes since v18:
* Remove useless include.
* Remove LLATTR_SIZE() which was only used to shorten lines. Cf. commit bdc48fa11e46 ("checkpatch/coding-style: deprecate 80-column warning").

Changes since v17:
* Synchronize syscall declaration.
* Fix comment.

Changes since v16:
* Add a size_attr_features field to struct landlock_attr_features for self-introspection, and move the access_fs field to be more consistent.
* Replace __aligned_u64 types of attribute fields with __u16, __s32, __u32 and __u64, and check at build time that these structures does not contain hole and that they are aligned the same way (8-bits) on all architectures. This shrinks the size of the userspace ABI, which may be appreciated especially for struct landlock_attr_features which could grow a lot in the future. For instance, struct landlock_attr_features shrinks from 72 bytes to 32 bytes. This change also enables to remove 64-bits to 32-bits conversion checks.
* Switch syscall attribute pointer and size arguments to follow similar syscall argument order (e.g. bpf, clone3, openat2).
* Set LANDLOCK_OPT_* types to 32-bits.
* Allow enforcement of empty ruleset, which enables deny-all policies.
* Fix documentation inconsistency.

Changes since v15:
* Do not add file descriptors referring to internal filesystems (e.g. nsfs) in a ruleset.
* Replace is_user_mountable() with in-place clean checks.
* Replace EBADR with EBADFD in get_ruleset_from_fd() and get_path_from_fd().
* Remove ruleset's show_fdinfo() for now.

Changes since v14:
* Remove the security_file_open() check in get_path_from_fd(): an opened FD should not be restricted here, and even less with this hook. As a result, it is now allowed to add a path to a ruleset even if the access to this path is not allowed (without O_PATH). This doesn't change the fact that enforcing a ruleset can't grant any right, only remove some rights. The new layer levels add more consistent restrictions.
* Check minimal landlock_attr_* size/content. This fix the case when no data was provided and e.g., FD 0 was interpreted as ruleset_fd. Now this leads to a returned -EINVAL.
* Fix credential double-free error case.
* Complete struct landlock_attr_size with size_attr_enforce.
* Fix undefined reference to syscall when Landlock is not selected.
* Remove f.file->f_path.mnt check (suggested by Al Viro).
* Add build-time checks.
* Move ABI checks from fs.c .
* Constify variables.
* Fix spelling.
* Add comments.

Changes since v13:
* New implementation, replacing the dependency on seccomp(2) and bpf(2).

---
 include/linux/syscalls.h      |   7 +
 include/uapi/linux/landlock.h |  53 ++++
 kernel/sys_ni.c               |   5 +
 security/landlock/Makefile    |   2 +-
 security/landlock/syscalls.c  | 445 ++++++++++++++++++++++++++++++++++
 5 files changed, 511 insertions(+), 1 deletion(-)
 create mode 100644 security/landlock/syscalls.c
include/linux/syscalls.h +7 -0
index 2839dc9a7c01..fa3971012e1c 100644
@@ -69,6 +69,8 @@ struct io_uring_params;
 struct clone_args;
 struct open_how;
 struct mount_attr;
+struct landlock_ruleset_attr;
+enum landlock_rule_type;
 
 #include <linux/types.h>
 #include <linux/aio_abi.h>
@@ -1041,6 +1043,11 @@ asmlinkage long sys_pidfd_send_signal(int pidfd, int sig,
 				       siginfo_t __user *info,
 				       unsigned int flags);
 asmlinkage long sys_pidfd_getfd(int pidfd, int fd, unsigned int flags);
+asmlinkage long sys_landlock_create_ruleset(const struct landlock_ruleset_attr __user *attr,
+		size_t size, __u32 flags);
+asmlinkage long sys_landlock_add_rule(int ruleset_fd, enum landlock_rule_type rule_type,
+		const void __user *rule_attr, __u32 flags);
+asmlinkage long sys_landlock_restrict_self(int ruleset_fd, __u32 flags);
 
 /*
  * Architecture-specific system calls
include/uapi/linux/landlock.h +53 -0

59 lines not on this page · raw message

kernel/sys_ni.c +5 -0
index 19aa806890d5..cce430cf2ff2 100644
@@ -266,6 +266,11 @@ COND_SYSCALL(request_key);
 COND_SYSCALL(keyctl);
 COND_SYSCALL_COMPAT(keyctl);
 
+/* security/landlock/syscalls.c */
+COND_SYSCALL(landlock_create_ruleset);
+COND_SYSCALL(landlock_add_rule);
+COND_SYSCALL(landlock_restrict_self);
+
 /* arch/example/kernel/sys_example.c */
 
 /* mm/fadvise.c */
security/landlock/Makefile +1 -1
index 92e3d80ab8ed..7bbd2f413b3e 100644
@@ -1,4 +1,4 @@
 obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
 
-landlock-y := setup.o object.o ruleset.o \
+landlock-y := setup.o syscalls.o object.o ruleset.o \
 	cred.o ptrace.o fs.o
security/landlock/syscalls.c new file +445 -0

445 lines not on this page · raw message

Signature · 1 line
2.30.2
#31 lore raw

Re: [PATCH v30 08/12] landlock: Add syscall implementations

Quoted 14 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

These 3 system calls are designed to be used by unprivileged processes to sandbox themselves:
* landlock_create_ruleset(2): Creates a ruleset and returns its file descriptor.
* landlock_add_rule(2): Adds a rule (e.g. file hierarchy access) to a ruleset, identified by the dedicated file descriptor.
* landlock_restrict_self(2): Enforces a ruleset on the calling thread and its future children (similar to seccomp). This syscall has the same usage restrictions as seccomp(2): the caller must have the no_new_privs attribute set or have CAP_SYS_ADMIN in the current user namespace.

Quoted 2 lines

All these syscalls have a "flags" argument (not currently used) to enable extensibility.

For the new-style extensible syscalls, you want only a "size" argument; "flags" should be within the argument structure.

(And to this end, why 3 syscalls instead of 1, if you're going to use extensibility anyway?)

Quoted 21 lines
security/landlock/syscalls.c new file +21 -0
+/**
+ * copy_min_struct_from_user - Safe future-proof argument copying
+ *
+ * Extend copy_struct_from_user() to check for consistent user buffer.
+ *
+ * @dst: Kernel space pointer or NULL.
+ * @ksize: Actual size of the data pointed to by @dst.
+ * @ksize_min: Minimal required size to be copied.
+ * @src: User space pointer or NULL.
+ * @usize: (Alleged) size of the data pointed to by @src.
+ */
+static __always_inline int copy_min_struct_from_user(void *const dst,
+		const size_t ksize, const size_t ksize_min,
+		const void __user *const src, const size_t usize)
+{
+	/* Checks buffer inconsistencies. */
+	BUILD_BUG_ON(!dst);
+	if (!src)
+		return -EFAULT;
+
+	/* Checks size ranges. */

security/landlock/syscalls.c line 65

Quoted 10 lines
security/landlock/syscalls.c new file +10 -0
+	BUILD_BUG_ON(ksize <= 0);
+	BUILD_BUG_ON(ksize < ksize_min);
+	if (usize < ksize_min)
+		return -EINVAL;
+	if (usize > PAGE_SIZE)
+		return -E2BIG;
+
+	/* Copies user buffer and fills with zeros. */
+	return copy_struct_from_user(dst, ksize, src, usize);
+}

I still wish this was built into copy_struct_from_user(). :) But yes, this appears to be the way to protect one's self when using copy_struct_from_user().

Quoted 30 lines
security/landlock/syscalls.c new file +30 -0
+/**
+ * sys_landlock_create_ruleset - Create a new ruleset
+ *
+ * @attr: Pointer to a &struct landlock_ruleset_attr identifying the scope of
+ *        the new ruleset.
+ * @size: Size of the pointed &struct landlock_ruleset_attr (needed for
+ *        backward and forward compatibility).
+ * @flags: Must be 0.
+ *
+ * This system call enables to create a new Landlock ruleset, and returns the
+ * related file descriptor on success.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0, or unknown access, or too small @size;
+ * - E2BIG or EFAULT: @attr or @size inconsistencies;
+ * - ENOMSG: empty &landlock_ruleset_attr.handled_access_fs.
+ */
+SYSCALL_DEFINE3(landlock_create_ruleset,
+		const struct landlock_ruleset_attr __user *const, attr,
+		const size_t, size, const __u32, flags)
+{
+	struct landlock_ruleset_attr ruleset_attr;
+	struct landlock_ruleset *ruleset;
+	int err, ruleset_fd;
+
+	/* Build-time checks. */
+	build_check_abi();
+

security/landlock/syscalls.c line 170

Quoted 10 lines
security/landlock/syscalls.c new file +10 -0
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
+		return -EINVAL;
+
+	/* Copies raw user space buffer. */
+	err = copy_min_struct_from_user(&ruleset_attr, sizeof(ruleset_attr),
+			offsetofend(typeof(ruleset_attr), handled_access_fs),

The use of offsetofend() here appears to be kind of the "V1", "V2", ... sizes used in other extensible syscall implementations?

Quoted 121 lines
security/landlock/syscalls.c new file +121 -0
+			attr, size);
+	if (err)
+		return err;
+
+	/* Checks content (and 32-bits cast). */
+	if ((ruleset_attr.handled_access_fs | LANDLOCK_MASK_ACCESS_FS) !=
+			LANDLOCK_MASK_ACCESS_FS)
+		return -EINVAL;
+
+	/* Checks arguments and transforms to kernel struct. */
+	ruleset = landlock_create_ruleset(ruleset_attr.handled_access_fs);
+	if (IS_ERR(ruleset))
+		return PTR_ERR(ruleset);
+
+	/* Creates anonymous FD referring to the ruleset. */
+	ruleset_fd = anon_inode_getfd("landlock-ruleset", &ruleset_fops,
+			ruleset, O_RDWR | O_CLOEXEC);
+	if (ruleset_fd < 0)
+		landlock_put_ruleset(ruleset);
+	return ruleset_fd;
+}
+
+/*
+ * Returns an owned ruleset from a FD. It is thus needed to call
+ * landlock_put_ruleset() on the return value.
+ */
+static struct landlock_ruleset *get_ruleset_from_fd(const int fd,
+		const fmode_t mode)
+{
+	struct fd ruleset_f;
+	struct landlock_ruleset *ruleset;
+
+	ruleset_f = fdget(fd);
+	if (!ruleset_f.file)
+		return ERR_PTR(-EBADF);
+
+	/* Checks FD type and access right. */
+	if (ruleset_f.file->f_op != &ruleset_fops) {
+		ruleset = ERR_PTR(-EBADFD);
+		goto out_fdput;
+	}
+	if (!(ruleset_f.file->f_mode & mode)) {
+		ruleset = ERR_PTR(-EPERM);
+		goto out_fdput;
+	}
+	ruleset = ruleset_f.file->private_data;
+	if (WARN_ON_ONCE(ruleset->num_layers != 1)) {
+		ruleset = ERR_PTR(-EINVAL);
+		goto out_fdput;
+	}
+	landlock_get_ruleset(ruleset);
+
+out_fdput:
+	fdput(ruleset_f);
+	return ruleset;
+}
+
+/* Path handling */
+
+/*
+ * @path: Must call put_path(@path) after the call if it succeeded.
+ */
+static int get_path_from_fd(const s32 fd, struct path *const path)
+{
+	struct fd f;
+	int err = 0;
+
+	BUILD_BUG_ON(!__same_type(fd,
+		((struct landlock_path_beneath_attr *)NULL)->parent_fd));
+
+	/* Handles O_PATH. */
+	f = fdget_raw(fd);
+	if (!f.file)
+		return -EBADF;
+	/*
+	 * Only allows O_PATH file descriptor: enables to restrict ambient
+	 * filesystem access without requiring to open and risk leaking or
+	 * misusing a file descriptor.  Forbids ruleset FDs, internal
+	 * filesystems (e.g. nsfs), including pseudo filesystems that will
+	 * never be mountable (e.g. sockfs, pipefs).
+	 */
+	if (!(f.file->f_mode & FMODE_PATH) ||
+			(f.file->f_op == &ruleset_fops) ||
+			(f.file->f_path.mnt->mnt_flags & MNT_INTERNAL) ||
+			(f.file->f_path.dentry->d_sb->s_flags & SB_NOUSER) ||
+			d_is_negative(f.file->f_path.dentry) ||
+			IS_PRIVATE(d_backing_inode(f.file->f_path.dentry))) {
+		err = -EBADFD;
+		goto out_fdput;
+	}
+	*path = f.file->f_path;
+	path_get(path);
+
+out_fdput:
+	fdput(f);
+	return err;
+}
+
+/**
+ * sys_landlock_add_rule - Add a new rule to a ruleset
+ *
+ * @ruleset_fd: File descriptor tied to the ruleset that should be extended
+ *		with the new rule.
+ * @rule_type: Identify the structure type pointed to by @rule_attr (only
+ *             LANDLOCK_RULE_PATH_BENEATH for now).
+ * @rule_attr: Pointer to a rule (only of type &struct
+ *             landlock_path_beneath_attr for now).
+ * @flags: Must be 0.
+ *
+ * This system call enables to define a new rule and add it to an existing
+ * ruleset.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0, or inconsistent access in the rule (i.e.
+ *   &landlock_path_beneath_attr.allowed_access is not a subset of the rule's
+ *   accesses);
+ * - ENOMSG: Empty accesses (e.g. &landlock_path_beneath_attr.allowed_access);
+ * - EBADF: @ruleset_fd is not a file descriptor for the current thread, or a
+ *   member of @rule_attr is not a file descriptor as expected;

security/landlock/syscalls.c line 301

Quoted 10 lines
security/landlock/syscalls.c new file +10 -0
+ * - EBADFD: @ruleset_fd is not a ruleset file descriptor, or a member of
+ *   @rule_attr is not the expected file descriptor type (e.g. file open
+ *   without O_PATH);
+ * - EPERM: @ruleset_fd has no write access to the underlying ruleset;
+ * - EFAULT: @rule_attr inconsistency.
+ */
+SYSCALL_DEFINE4(landlock_add_rule,
+		const int, ruleset_fd, const enum landlock_rule_type, rule_type,
+		const void __user *const, rule_attr, const __u32, flags)
+{

If this is an extensible syscall, I'd expect a structure holding rule_type, rule_attr, and flags.

Quoted 77 lines
security/landlock/syscalls.c new file +77 -0
+	struct landlock_path_beneath_attr path_beneath_attr;
+	struct path path;
+	struct landlock_ruleset *ruleset;
+	int res, err;
+
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
+		return -EINVAL;
+
+	if (rule_type != LANDLOCK_RULE_PATH_BENEATH)
+		return -EINVAL;
+
+	/* Copies raw user space buffer, only one type for now. */
+	res = copy_from_user(&path_beneath_attr, rule_attr,
+			sizeof(path_beneath_attr));
+	if (res)
+		return -EFAULT;
+
+	/* Gets and checks the ruleset. */
+	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_WRITE);
+	if (IS_ERR(ruleset))
+		return PTR_ERR(ruleset);
+
+	/*
+	 * Informs about useless rule: empty allowed_access (i.e. deny rules)
+	 * are ignored in path walks.
+	 */
+	if (!path_beneath_attr.allowed_access) {
+		err = -ENOMSG;
+		goto out_put_ruleset;
+	}
+	/*
+	 * Checks that allowed_access matches the @ruleset constraints
+	 * (ruleset->fs_access_masks[0] is automatically upgraded to 64-bits).
+	 */
+	if ((path_beneath_attr.allowed_access | ruleset->fs_access_masks[0]) !=
+			ruleset->fs_access_masks[0]) {
+		err = -EINVAL;
+		goto out_put_ruleset;
+	}
+
+	/* Gets and checks the new rule. */
+	err = get_path_from_fd(path_beneath_attr.parent_fd, &path);
+	if (err)
+		goto out_put_ruleset;
+
+	/* Imports the new rule. */
+	err = landlock_append_fs_rule(ruleset, &path,
+			path_beneath_attr.allowed_access);
+	path_put(&path);
+
+out_put_ruleset:
+	landlock_put_ruleset(ruleset);
+	return err;
+}
+
+/* Enforcement */
+
+/**
+ * sys_landlock_restrict_self - Enforce a ruleset on the calling thread
+ *
+ * @ruleset_fd: File descriptor tied to the ruleset to merge with the target.
+ * @flags: Must be 0.
+ *
+ * This system call enables to enforce a Landlock ruleset on the current
+ * thread.  Enforcing a ruleset requires that the task has CAP_SYS_ADMIN in its
+ * namespace or is running with no_new_privs.  This avoids scenarios where
+ * unprivileged tasks can affect the behavior of privileged children.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0.
+ * - EBADF: @ruleset_fd is not a file descriptor for the current thread;

security/landlock/syscalls.c line 388

Quoted 10 lines
security/landlock/syscalls.c new file +10 -0
+ * - EBADFD: @ruleset_fd is not a ruleset file descriptor;
+ * - EPERM: @ruleset_fd has no read access to the underlying ruleset, or the
+ *   current thread is not running with no_new_privs, or it doesn't have
+ *   CAP_SYS_ADMIN in its namespace.
+ * - E2BIG: The maximum number of stacked rulesets is reached for the current
+ *   thread.
+ */
+SYSCALL_DEFINE2(landlock_restrict_self,
+		const int, ruleset_fd, const __u32, flags)
+{

Same observation about new style syscalls.

Quoted 60 lines
security/landlock/syscalls.c new file +57 -0
+	struct landlock_ruleset *new_dom, *ruleset;
+	struct cred *new_cred;
+	struct landlock_cred_security *new_llcred;
+	int err;
+
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
+		return -EINVAL;
+
+	/*
+	 * Similar checks as for seccomp(2), except that an -EPERM may be
+	 * returned.
+	 */
+	if (!task_no_new_privs(current) &&
+			!ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN))
+		return -EPERM;
+
+	/* Gets and checks the ruleset. */
+	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_READ);
+	if (IS_ERR(ruleset))
+		return PTR_ERR(ruleset);
+
+	/* Prepares new credentials. */
+	new_cred = prepare_creds();
+	if (!new_cred) {
+		err = -ENOMEM;
+		goto out_put_ruleset;
+	}
+	new_llcred = landlock_cred(new_cred);
+
+	/*
+	 * There is no possible race condition while copying and manipulating
+	 * the current credentials because they are dedicated per thread.
+	 */
+	new_dom = landlock_merge_ruleset(new_llcred->domain, ruleset);
+	if (IS_ERR(new_dom)) {
+		err = PTR_ERR(new_dom);
+		goto out_put_creds;
+	}
+
+	/* Replaces the old (prepared) domain. */
+	landlock_put_ruleset(new_llcred->domain);
+	new_llcred->domain = new_dom;
+
+	landlock_put_ruleset(ruleset);
+	return commit_creds(new_cred);
+
+out_put_creds:
+	abort_creds(new_cred);
+
+out_put_ruleset:
+	landlock_put_ruleset(ruleset);
+	return err;
+}
Signature · 1 line
2.30.2
Signature · 1 line
Kees Cook
author maintainer
#32 lore raw

Re: [PATCH v30 08/12] landlock: Add syscall implementations

Quoted 15 lines · Kees Cook
Quoted 14 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

These 3 system calls are designed to be used by unprivileged processes to sandbox themselves:
* landlock_create_ruleset(2): Creates a ruleset and returns its file descriptor.
* landlock_add_rule(2): Adds a rule (e.g. file hierarchy access) to a ruleset, identified by the dedicated file descriptor.
* landlock_restrict_self(2): Enforces a ruleset on the calling thread and its future children (similar to seccomp). This syscall has the same usage restrictions as seccomp(2): the caller must have the no_new_privs attribute set or have CAP_SYS_ADMIN in the current user namespace.

Quoted 5 lines
Quoted 2 lines

All these syscalls have a "flags" argument (not currently used) to enable extensibility.

For the new-style extensible syscalls, you want only a "size" argument; "flags" should be within the argument structure.

Not necessarily, we should avoid complexity as much as possible. A flag argument is simple, and extensible arguments should be avoided as much as possible. Here it is only used for an extensible list of properties that can't be expressed otherwise.

Quoted 3 lines

(And to this end, why 3 syscalls instead of 1, if you're going to use extensibility anyway?)

This was discussed with people such as Arnd and Jann. Multiplexer syscalls should be avoided. Here are some background:
https://lore.kernel.org/lkml/CAG48ez2V-eSH2+HL9zrYYD4QMpP4a5y8=mTQtk20PB0wUz_4Tw@mail.gmail.com/

Quoted 72 lines
Quoted 22 lines
security/landlock/syscalls.c new file +21 -0
+/**
+ * copy_min_struct_from_user - Safe future-proof argument copying
+ *
+ * Extend copy_struct_from_user() to check for consistent user buffer.
+ *
+ * @dst: Kernel space pointer or NULL.
+ * @ksize: Actual size of the data pointed to by @dst.
+ * @ksize_min: Minimal required size to be copied.
+ * @src: User space pointer or NULL.
+ * @usize: (Alleged) size of the data pointed to by @src.
+ */
+static __always_inline int copy_min_struct_from_user(void *const dst,
+		const size_t ksize, const size_t ksize_min,
+		const void __user *const src, const size_t usize)
+{
+	/* Checks buffer inconsistencies. */
+	BUILD_BUG_ON(!dst);
+	if (!src)
+		return -EFAULT;
+
+	/* Checks size ranges. */

security/landlock/syscalls.c line 65

Quoted 10 lines
security/landlock/syscalls.c new file +10 -0
+	BUILD_BUG_ON(ksize <= 0);
+	BUILD_BUG_ON(ksize < ksize_min);
+	if (usize < ksize_min)
+		return -EINVAL;
+	if (usize > PAGE_SIZE)
+		return -E2BIG;
+
+	/* Copies user buffer and fills with zeros. */
+	return copy_struct_from_user(dst, ksize, src, usize);
+}

I still wish this was built into copy_struct_from_user(). :) But yes, this appears to be the way to protect one's self when using copy_struct_from_user().

Quoted 35 lines
security/landlock/syscalls.c new file +35 -0
+/**
+ * sys_landlock_create_ruleset - Create a new ruleset
+ *
+ * @attr: Pointer to a &struct landlock_ruleset_attr identifying the scope of
+ *        the new ruleset.
+ * @size: Size of the pointed &struct landlock_ruleset_attr (needed for
+ *        backward and forward compatibility).
+ * @flags: Must be 0.
+ *
+ * This system call enables to create a new Landlock ruleset, and returns the
+ * related file descriptor on success.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0, or unknown access, or too small @size;
+ * - E2BIG or EFAULT: @attr or @size inconsistencies;
+ * - ENOMSG: empty &landlock_ruleset_attr.handled_access_fs.
+ */
+SYSCALL_DEFINE3(landlock_create_ruleset,
+		const struct landlock_ruleset_attr __user *const, attr,
+		const size_t, size, const __u32, flags)
+{
+	struct landlock_ruleset_attr ruleset_attr;
+	struct landlock_ruleset *ruleset;
+	int err, ruleset_fd;
+
+	/* Build-time checks. */
+	build_check_abi();
+
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
Quoted 8 lines

security/landlock/syscalls.c line 170

Quoted 5 lines
security/landlock/syscalls.c new file +5 -0
+		return -EINVAL;
+
+	/* Copies raw user space buffer. */
+	err = copy_min_struct_from_user(&ruleset_attr, sizeof(ruleset_attr),
+			offsetofend(typeof(ruleset_attr), handled_access_fs),

The use of offsetofend() here appears to be kind of the "V1", "V2", ... sizes used in other extensible syscall implementations?

ruleset_attr is an extensible argument.

Quoted 127 lines
Quoted 127 lines
security/landlock/syscalls.c new file +126 -0
+			attr, size);
+	if (err)
+		return err;
+
+	/* Checks content (and 32-bits cast). */
+	if ((ruleset_attr.handled_access_fs | LANDLOCK_MASK_ACCESS_FS) !=
+			LANDLOCK_MASK_ACCESS_FS)
+		return -EINVAL;
+
+	/* Checks arguments and transforms to kernel struct. */
+	ruleset = landlock_create_ruleset(ruleset_attr.handled_access_fs);
+	if (IS_ERR(ruleset))
+		return PTR_ERR(ruleset);
+
+	/* Creates anonymous FD referring to the ruleset. */
+	ruleset_fd = anon_inode_getfd("landlock-ruleset", &ruleset_fops,
+			ruleset, O_RDWR | O_CLOEXEC);
+	if (ruleset_fd < 0)
+		landlock_put_ruleset(ruleset);
+	return ruleset_fd;
+}
+
+/*
+ * Returns an owned ruleset from a FD. It is thus needed to call
+ * landlock_put_ruleset() on the return value.
+ */
+static struct landlock_ruleset *get_ruleset_from_fd(const int fd,
+		const fmode_t mode)
+{
+	struct fd ruleset_f;
+	struct landlock_ruleset *ruleset;
+
+	ruleset_f = fdget(fd);
+	if (!ruleset_f.file)
+		return ERR_PTR(-EBADF);
+
+	/* Checks FD type and access right. */
+	if (ruleset_f.file->f_op != &ruleset_fops) {
+		ruleset = ERR_PTR(-EBADFD);
+		goto out_fdput;
+	}
+	if (!(ruleset_f.file->f_mode & mode)) {
+		ruleset = ERR_PTR(-EPERM);
+		goto out_fdput;
+	}
+	ruleset = ruleset_f.file->private_data;
+	if (WARN_ON_ONCE(ruleset->num_layers != 1)) {
+		ruleset = ERR_PTR(-EINVAL);
+		goto out_fdput;
+	}
+	landlock_get_ruleset(ruleset);
+
+out_fdput:
+	fdput(ruleset_f);
+	return ruleset;
+}
+
+/* Path handling */
+
+/*
+ * @path: Must call put_path(@path) after the call if it succeeded.
+ */
+static int get_path_from_fd(const s32 fd, struct path *const path)
+{
+	struct fd f;
+	int err = 0;
+
+	BUILD_BUG_ON(!__same_type(fd,
+		((struct landlock_path_beneath_attr *)NULL)->parent_fd));
+
+	/* Handles O_PATH. */
+	f = fdget_raw(fd);
+	if (!f.file)
+		return -EBADF;
+	/*
+	 * Only allows O_PATH file descriptor: enables to restrict ambient
+	 * filesystem access without requiring to open and risk leaking or
+	 * misusing a file descriptor.  Forbids ruleset FDs, internal
+	 * filesystems (e.g. nsfs), including pseudo filesystems that will
+	 * never be mountable (e.g. sockfs, pipefs).
+	 */
+	if (!(f.file->f_mode & FMODE_PATH) ||
+			(f.file->f_op == &ruleset_fops) ||
+			(f.file->f_path.mnt->mnt_flags & MNT_INTERNAL) ||
+			(f.file->f_path.dentry->d_sb->s_flags & SB_NOUSER) ||
+			d_is_negative(f.file->f_path.dentry) ||
+			IS_PRIVATE(d_backing_inode(f.file->f_path.dentry))) {
+		err = -EBADFD;
+		goto out_fdput;
+	}
+	*path = f.file->f_path;
+	path_get(path);
+
+out_fdput:
+	fdput(f);
+	return err;
+}
+
+/**
+ * sys_landlock_add_rule - Add a new rule to a ruleset
+ *
+ * @ruleset_fd: File descriptor tied to the ruleset that should be extended
+ *		with the new rule.
+ * @rule_type: Identify the structure type pointed to by @rule_attr (only
+ *             LANDLOCK_RULE_PATH_BENEATH for now).
+ * @rule_attr: Pointer to a rule (only of type &struct
+ *             landlock_path_beneath_attr for now).
+ * @flags: Must be 0.
+ *
+ * This system call enables to define a new rule and add it to an existing
+ * ruleset.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0, or inconsistent access in the rule (i.e.
+ *   &landlock_path_beneath_attr.allowed_access is not a subset of the rule's
+ *   accesses);
+ * - ENOMSG: Empty accesses (e.g. &landlock_path_beneath_attr.allowed_access);
+ * - EBADF: @ruleset_fd is not a file descriptor for the current thread, or a
+ *   member of @rule_attr is not a file descriptor as expected;
+ * - EBADFD: @ruleset_fd is not a ruleset file descriptor, or a member of
+ *   @rule_attr is not the expected file descriptor type (e.g. file open
+ *   without O_PATH);
+ * - EPERM: @ruleset_fd has no write access to the underlying ruleset;
+ * - EFAULT: @rule_attr inconsistency.
Quoted 8 lines

security/landlock/syscalls.c line 301

Quoted 5 lines

+ */

security/landlock/syscalls.c new file +4 -0
+SYSCALL_DEFINE4(landlock_add_rule,
+		const int, ruleset_fd, const enum landlock_rule_type, rule_type,
+		const void __user *const, rule_attr, const __u32, flags)
+{

If this is an extensible syscall, I'd expect a structure holding rule_type, rule_attr, and flags.

This does not use an extensible argument. rule_type specifies a type and rule_attr specifies the content of this type. This is simpler and sufficient.

Quoted 82 lines
Quoted 82 lines
security/landlock/syscalls.c new file +81 -0
+	struct landlock_path_beneath_attr path_beneath_attr;
+	struct path path;
+	struct landlock_ruleset *ruleset;
+	int res, err;
+
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
+		return -EINVAL;
+
+	if (rule_type != LANDLOCK_RULE_PATH_BENEATH)
+		return -EINVAL;
+
+	/* Copies raw user space buffer, only one type for now. */
+	res = copy_from_user(&path_beneath_attr, rule_attr,
+			sizeof(path_beneath_attr));
+	if (res)
+		return -EFAULT;
+
+	/* Gets and checks the ruleset. */
+	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_WRITE);
+	if (IS_ERR(ruleset))
+		return PTR_ERR(ruleset);
+
+	/*
+	 * Informs about useless rule: empty allowed_access (i.e. deny rules)
+	 * are ignored in path walks.
+	 */
+	if (!path_beneath_attr.allowed_access) {
+		err = -ENOMSG;
+		goto out_put_ruleset;
+	}
+	/*
+	 * Checks that allowed_access matches the @ruleset constraints
+	 * (ruleset->fs_access_masks[0] is automatically upgraded to 64-bits).
+	 */
+	if ((path_beneath_attr.allowed_access | ruleset->fs_access_masks[0]) !=
+			ruleset->fs_access_masks[0]) {
+		err = -EINVAL;
+		goto out_put_ruleset;
+	}
+
+	/* Gets and checks the new rule. */
+	err = get_path_from_fd(path_beneath_attr.parent_fd, &path);
+	if (err)
+		goto out_put_ruleset;
+
+	/* Imports the new rule. */
+	err = landlock_append_fs_rule(ruleset, &path,
+			path_beneath_attr.allowed_access);
+	path_put(&path);
+
+out_put_ruleset:
+	landlock_put_ruleset(ruleset);
+	return err;
+}
+
+/* Enforcement */
+
+/**
+ * sys_landlock_restrict_self - Enforce a ruleset on the calling thread
+ *
+ * @ruleset_fd: File descriptor tied to the ruleset to merge with the target.
+ * @flags: Must be 0.
+ *
+ * This system call enables to enforce a Landlock ruleset on the current
+ * thread.  Enforcing a ruleset requires that the task has CAP_SYS_ADMIN in its
+ * namespace or is running with no_new_privs.  This avoids scenarios where
+ * unprivileged tasks can affect the behavior of privileged children.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0.
+ * - EBADF: @ruleset_fd is not a file descriptor for the current thread;
+ * - EBADFD: @ruleset_fd is not a ruleset file descriptor;
+ * - EPERM: @ruleset_fd has no read access to the underlying ruleset, or the
+ *   current thread is not running with no_new_privs, or it doesn't have
+ *   CAP_SYS_ADMIN in its namespace.
Quoted 8 lines

security/landlock/syscalls.c line 388

Quoted 6 lines

+ * - E2BIG: The maximum number of stacked rulesets is reached for the current
+ * thread.
+ */

security/landlock/syscalls.c new file +3 -0
+SYSCALL_DEFINE2(landlock_restrict_self,
+		const int, ruleset_fd, const __u32, flags)
+{

Same observation about new style syscalls.

This design is simpler.

Quoted 62 lines
Quoted 61 lines
security/landlock/syscalls.c new file +57 -0
+	struct landlock_ruleset *new_dom, *ruleset;
+	struct cred *new_cred;
+	struct landlock_cred_security *new_llcred;
+	int err;
+
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
+		return -EINVAL;
+
+	/*
+	 * Similar checks as for seccomp(2), except that an -EPERM may be
+	 * returned.
+	 */
+	if (!task_no_new_privs(current) &&
+			!ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN))
+		return -EPERM;
+
+	/* Gets and checks the ruleset. */
+	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_READ);
+	if (IS_ERR(ruleset))
+		return PTR_ERR(ruleset);
+
+	/* Prepares new credentials. */
+	new_cred = prepare_creds();
+	if (!new_cred) {
+		err = -ENOMEM;
+		goto out_put_ruleset;
+	}
+	new_llcred = landlock_cred(new_cred);
+
+	/*
+	 * There is no possible race condition while copying and manipulating
+	 * the current credentials because they are dedicated per thread.
+	 */
+	new_dom = landlock_merge_ruleset(new_llcred->domain, ruleset);
+	if (IS_ERR(new_dom)) {
+		err = PTR_ERR(new_dom);
+		goto out_put_creds;
+	}
+
+	/* Replaces the old (prepared) domain. */
+	landlock_put_ruleset(new_llcred->domain);
+	new_llcred->domain = new_dom;
+
+	landlock_put_ruleset(ruleset);
+	return commit_creds(new_cred);
+
+out_put_creds:
+	abort_creds(new_cred);
+
+out_put_ruleset:
+	landlock_put_ruleset(ruleset);
+	return err;
+}
Signature · 1 line
2.30.2
author maintainer
#33 lore raw

Re: [PATCH v30 08/12] landlock: Add syscall implementations

Quoted 4 lines · Mickaël Salaün
Quoted 2 lines · Kees Cook
Quoted 1 line · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

[...]

Quoted 44 lines
Quoted 35 lines
Quoted 35 lines
security/landlock/syscalls.c new file +35 -0
+/**
+ * sys_landlock_create_ruleset - Create a new ruleset
+ *
+ * @attr: Pointer to a &struct landlock_ruleset_attr identifying the scope of
+ *        the new ruleset.
+ * @size: Size of the pointed &struct landlock_ruleset_attr (needed for
+ *        backward and forward compatibility).
+ * @flags: Must be 0.
+ *
+ * This system call enables to create a new Landlock ruleset, and returns the
+ * related file descriptor on success.
+ *
+ * Possible returned errors are:
+ *
+ * - EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time;
+ * - EINVAL: @flags is not 0, or unknown access, or too small @size;
+ * - E2BIG or EFAULT: @attr or @size inconsistencies;
+ * - ENOMSG: empty &landlock_ruleset_attr.handled_access_fs.
+ */
+SYSCALL_DEFINE3(landlock_create_ruleset,
+		const struct landlock_ruleset_attr __user *const, attr,
+		const size_t, size, const __u32, flags)
+{
+	struct landlock_ruleset_attr ruleset_attr;
+	struct landlock_ruleset *ruleset;
+	int err, ruleset_fd;
+
+	/* Build-time checks. */
+	build_check_abi();
+
+	if (!landlock_initialized)
+		return -EOPNOTSUPP;
+
+	/* No flag for now. */
+	if (flags)
Quoted 8 lines

security/landlock/syscalls.c line 170

Quoted 5 lines
security/landlock/syscalls.c new file +5 -0
+		return -EINVAL;
+
+	/* Copies raw user space buffer. */
+	err = copy_min_struct_from_user(&ruleset_attr, sizeof(ruleset_attr),
+			offsetofend(typeof(ruleset_attr), handled_access_fs),

The use of offsetofend() here appears to be kind of the "V1", "V2", ... sizes used in other extensible syscall implementations?

Quoted 1 line

ruleset_attr is an extensible argument.

offsetofen() is used to set the minimum size of a valid argument. This code will then not change with future extended ruleset_attr.

author maintainer
#34 lore raw

PATCH v30 9/12 arch: Wire up Landlock syscalls

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Wire up the following system calls for all architectures:
* landlock_create_ruleset(2)
* landlock_add_rule(2)
* landlock_restrict_self(2)

---

Changes since v29:
* Rebase on v5.12-rc3 and fix trivial conflict with mount_setattr(2).
* Synchronize syscall numbers with -next, which are the same as for v5.12-rc3.

Changes since v27:
* Rename landlock_enforce_ruleset_self(2) to landlock_restrict_self(2).
* Cosmetic fix: align TBL enries.

Changes since v26:
* Rename landlock_enforce_ruleset_current(2) to landlock_enforce_ruleset_self(2).

Changes since v25:
* Rebase and leave space for the new epoll_pwait2(2) and memfd_secret(2) from -next.

Changes since v21:
* Rebase and leave space for watch_mount(2) from -next.

Changes since v20:
* Remove landlock_get_features(2).
* Decrease syscall numbers to stick to process_madvise(2) in -next.
* Rename landlock_enforce_ruleset(2) to landlock_enforce_ruleset_current(2).

Changes since v19:
* Increase syscall numbers by 4 to leave space for new ones (in linux-next): watch_mount(2), watch_sb(2), fsinfo(2) and process_madvise(2) (requested by Arnd Bergmann).
* Replace the previous multiplexor landlock(2) with 4 syscalls:
landlock_get_features(2), landlock_create_ruleset(2), landlock_add_rule(2) and landlock_enforce_ruleset(2).

Changes since v18:
* Increase the syscall number because of the new faccessat2(2).

Changes since v14:
* Add all architectures.

Changes since v13:
* New implementation.

---
 arch/alpha/kernel/syscalls/syscall.tbl      | 3 +++
 arch/arm/tools/syscall.tbl                  | 3 +++
 arch/arm64/include/asm/unistd.h             | 2 +-
 arch/arm64/include/asm/unistd32.h           | 6 ++++++
 arch/ia64/kernel/syscalls/syscall.tbl       | 3 +++
 arch/m68k/kernel/syscalls/syscall.tbl       | 3 +++
 arch/microblaze/kernel/syscalls/syscall.tbl | 3 +++
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 3 +++
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 3 +++
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 3 +++
 arch/parisc/kernel/syscalls/syscall.tbl     | 3 +++
 arch/powerpc/kernel/syscalls/syscall.tbl    | 3 +++
 arch/s390/kernel/syscalls/syscall.tbl       | 3 +++
 arch/sh/kernel/syscalls/syscall.tbl         | 3 +++
 arch/sparc/kernel/syscalls/syscall.tbl      | 3 +++
 arch/x86/entry/syscalls/syscall_32.tbl      | 3 +++
 arch/x86/entry/syscalls/syscall_64.tbl      | 3 +++
 arch/xtensa/kernel/syscalls/syscall.tbl     | 3 +++
 include/uapi/asm-generic/unistd.h           | 8 +++++++-
 19 files changed, 62 insertions(+), 2 deletions(-)
arch/alpha/kernel/syscalls/syscall.tbl +3 -0
index 02f0244e005c..0924a3ac7bd9 100644
@@ -482,3 +482,6 @@
 550	common	process_madvise			sys_process_madvise
 551	common	epoll_pwait2			sys_epoll_pwait2
 552	common	mount_setattr			sys_mount_setattr
+553	common	landlock_create_ruleset		sys_landlock_create_ruleset
+554	common	landlock_add_rule		sys_landlock_add_rule
+555	common	landlock_restrict_self		sys_landlock_restrict_self
arch/arm/tools/syscall.tbl +3 -0
index dcc1191291a2..dc1134b34cea 100644
@@ -456,3 +456,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/arm64/include/asm/unistd.h +1 -1
index 949788f5ba40..d1cc2849dc00 100644
@@ -38,7 +38,7 @@
 #define __ARM_NR_compat_set_tls		(__ARM_NR_COMPAT_BASE + 5)
 #define __ARM_NR_COMPAT_END		(__ARM_NR_COMPAT_BASE + 0x800)
 
-#define __NR_compat_syscalls		443
+#define __NR_compat_syscalls		446
 #endif
 
 #define __ARCH_WANT_SYS_CLONE
arch/arm64/include/asm/unistd32.h +6 -0
index 3d874f624056..54e11bce7677 100644
@@ -893,6 +893,12 @@ __SYSCALL(__NR_process_madvise, sys_process_madvise)
 __SYSCALL(__NR_epoll_pwait2, compat_sys_epoll_pwait2)
 #define __NR_mount_setattr 442
 __SYSCALL(__NR_mount_setattr, sys_mount_setattr)
+#define __NR_landlock_create_ruleset 443
+__SYSCALL(__NR_landlock_create_ruleset, sys_landlock_create_ruleset)
+#define __NR_landlock_add_rule 444
+__SYSCALL(__NR_landlock_add_rule, sys_landlock_add_rule)
+#define __NR_landlock_restrict_self 445
+__SYSCALL(__NR_landlock_restrict_self, sys_landlock_restrict_self)
 
 /*
  * Please add new compat syscalls above this comment and update
arch/ia64/kernel/syscalls/syscall.tbl +3 -0
index d89231166e19..1bb35159561a 100644
@@ -363,3 +363,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/m68k/kernel/syscalls/syscall.tbl +3 -0
index 72bde6707dd3..e06e224523bb 100644
@@ -442,3 +442,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/microblaze/kernel/syscalls/syscall.tbl +3 -0
index d603a5ec9338..9994a43eafb2 100644
@@ -448,3 +448,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/mips/kernel/syscalls/syscall_n32.tbl +3 -0
index 8fd8c1790941..834333d84d3e 100644
@@ -381,3 +381,6 @@
 440	n32	process_madvise			sys_process_madvise
 441	n32	epoll_pwait2			compat_sys_epoll_pwait2
 442	n32	mount_setattr			sys_mount_setattr
+443	n32	landlock_create_ruleset		sys_landlock_create_ruleset
+444	n32	landlock_add_rule		sys_landlock_add_rule
+445	n32	landlock_restrict_self		sys_landlock_restrict_self
arch/mips/kernel/syscalls/syscall_n64.tbl +3 -0
index 169f21438065..935024e0f49b 100644
@@ -357,3 +357,6 @@
 440	n64	process_madvise			sys_process_madvise
 441	n64	epoll_pwait2			sys_epoll_pwait2
 442	n64	mount_setattr			sys_mount_setattr
+443	n64	landlock_create_ruleset		sys_landlock_create_ruleset
+444	n64	landlock_add_rule		sys_landlock_add_rule
+445	n64	landlock_restrict_self		sys_landlock_restrict_self
arch/mips/kernel/syscalls/syscall_o32.tbl +3 -0
index 090d29ca80ff..f3f8bea8ce99 100644
@@ -430,3 +430,6 @@
 440	o32	process_madvise			sys_process_madvise
 441	o32	epoll_pwait2			sys_epoll_pwait2		compat_sys_epoll_pwait2
 442	o32	mount_setattr			sys_mount_setattr
+443	o32	landlock_create_ruleset		sys_landlock_create_ruleset
+444	o32	landlock_add_rule		sys_landlock_add_rule
+445	o32	landlock_restrict_self		sys_landlock_restrict_self
arch/parisc/kernel/syscalls/syscall.tbl +3 -0
index 271a92519683..1bddfeffdebd 100644
@@ -440,3 +440,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2		compat_sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/powerpc/kernel/syscalls/syscall.tbl +3 -0
index 0b2480cf3e47..98548b8da879 100644
@@ -522,3 +522,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2		compat_sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/s390/kernel/syscalls/syscall.tbl +3 -0
index 3abef2144dac..ecb697fee2f3 100644
@@ -445,3 +445,6 @@
 440  common	process_madvise		sys_process_madvise		sys_process_madvise
 441  common	epoll_pwait2		sys_epoll_pwait2		compat_sys_epoll_pwait2
 442  common	mount_setattr		sys_mount_setattr		sys_mount_setattr
+443  common	landlock_create_ruleset	sys_landlock_create_ruleset	sys_landlock_create_ruleset
+444  common	landlock_add_rule	sys_landlock_add_rule		sys_landlock_add_rule
+445  common	landlock_restrict_self	sys_landlock_restrict_self	sys_landlock_restrict_self
arch/sh/kernel/syscalls/syscall.tbl +3 -0
index d08eebad6b7f..440c053eada5 100644
@@ -445,3 +445,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/sparc/kernel/syscalls/syscall.tbl +3 -0
index 84403a99039c..f5f5d165c8c1 100644
@@ -488,3 +488,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2		compat_sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
arch/x86/entry/syscalls/syscall_32.tbl +3 -0
index a1c9f496fca6..995dc5b46dfc 100644
@@ -447,3 +447,6 @@
 440	i386	process_madvise		sys_process_madvise
 441	i386	epoll_pwait2		sys_epoll_pwait2		compat_sys_epoll_pwait2
 442	i386	mount_setattr		sys_mount_setattr
+443	i386	landlock_create_ruleset	sys_landlock_create_ruleset
+444	i386	landlock_add_rule	sys_landlock_add_rule
+445	i386	landlock_restrict_self	sys_landlock_restrict_self
arch/x86/entry/syscalls/syscall_64.tbl +3 -0
index 7bf01cbe582f..a5207ee2b67b 100644
@@ -364,6 +364,9 @@
 440	common	process_madvise		sys_process_madvise
 441	common	epoll_pwait2		sys_epoll_pwait2
 442	common	mount_setattr		sys_mount_setattr
+443	common	landlock_create_ruleset	sys_landlock_create_ruleset
+444	common	landlock_add_rule	sys_landlock_add_rule
+445	common	landlock_restrict_self	sys_landlock_restrict_self
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/xtensa/kernel/syscalls/syscall.tbl +3 -0
index 365a9b849224..b43b96a862cd 100644
@@ -413,3 +413,6 @@
 440	common	process_madvise			sys_process_madvise
 441	common	epoll_pwait2			sys_epoll_pwait2
 442	common	mount_setattr			sys_mount_setattr
+443	common	landlock_create_ruleset		sys_landlock_create_ruleset
+444	common	landlock_add_rule		sys_landlock_add_rule
+445	common	landlock_restrict_self		sys_landlock_restrict_self
include/uapi/asm-generic/unistd.h +7 -1
index ce58cff99b66..02d8d7804a29 100644
@@ -863,9 +863,15 @@ __SYSCALL(__NR_process_madvise, sys_process_madvise)
 __SC_COMP(__NR_epoll_pwait2, sys_epoll_pwait2, compat_sys_epoll_pwait2)
 #define __NR_mount_setattr 442
 __SYSCALL(__NR_mount_setattr, sys_mount_setattr)
+#define __NR_landlock_create_ruleset 443
+__SYSCALL(__NR_landlock_create_ruleset, sys_landlock_create_ruleset)
+#define __NR_landlock_add_rule 444
+__SYSCALL(__NR_landlock_add_rule, sys_landlock_add_rule)
+#define __NR_landlock_restrict_self 445
+__SYSCALL(__NR_landlock_restrict_self, sys_landlock_restrict_self)
 
 #undef __NR_syscalls
-#define __NR_syscalls 443
+#define __NR_syscalls 446
 
 /*
  * 32 bit systems traditionally used different
Signature · 1 line
2.30.2
author maintainer
#35 lore raw

PATCH v30 10/12 selftests/landlock: Add user space tests

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Test all Landlock system calls, ptrace hooks semantic and filesystem access-control with multiple layouts.

Test coverage for security/landlock/ is 93.6% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions.

---

Changes since v29:
* Add new tests with chroot (parent directory).
* Extend test_make_file() and make_sym() to test link(2) and rename(2), which helps cover get_mode_access().

Changes since v28:
* Creates a standalone filesystem test environement: do not update the root mount point options, and creates a private mount hierarchy with a deterministic filesystem (tmpfs). This is now possible thanks to TEST_F_FORK().
* Factor out layout management with prepare_layout() and cleanup_layout() for layout1, layout1_bind and layout2_overlay.
* Add and use a drop_caps() helper as much as possible (complementary to the disable_caps() helper). This is possible for fs_test.c thanks to TEST_F_FORK().
* Improve layout1.execute to make sure LANDLOCK_ACCESS_FS_EXECUTE only restricts execve(2).
* Improve ptrace_test.c with /proc/<pid>/environ checks to also test PTRACE_MODE_READ.
* Extend layout1.rename_file and layout1.rename_dir tests with renameat2/RENAME_EXCHANGE and more comments.
* Tests unlinkat/AT_REMOVEDIR in complement to rmdir().
* Add a test to layout1.inval to check a rule with a ruleset as a path_beneath.parent_fd .
* Add CONFIG_TMPFS_XATTR to avoid overlayfs warnings ("upper fs does not support xattr, falling back to index=off and metacopy=off").
* Reduce capabilities use.
* Remove useless TH_LOG().

Changes since v27:
* Add layout1.non_overlapping_accesses to check rules without overlapping access rights (fixed in this patchset).
* Extend layout1.interleaved_masked_accesses with a non-overlapping execute-only rule.
* Update tests for empty path_beneath.allowed_access, and replace useless (i.e. deny-only rules) code in layout1.interleaved_masked_accesses with equivalent meaningful rules.
* Fix the returned step when a test failed with TEST_F_FORK().
* Update MAINTAINERS.
* Cosmetic fix to please checkpatch.
* Fix typo in comment.
* Update landlock_restrict_self(2).

Changes since v26:
* Add layout1_bind tests to check inherited bind mount accesses.
* Add layout2_overlay tests to check non-inherited overlayfs accesses.
* Fix final cleanup which was reordered because of kselftest_harness changes.
* Update layout1.inherit_subset test according to the check_access_path_layer() change.
* Implement TEST_F_FORK() to be able to use FIXTURE_TEARDOWN() to clean up layouts even if the test (child) lost access rights or failed. Remove now useless layout*.cleanup .
* Update syscall names.
* Clean up FIXTURE_SETUP(layout1).
* Clean up file layout management:
- Replace specific create_dir_and_file() with generic create_directory() and create_file().
- Replace specific delete_dir_and_file() with generic remove_path().
- Rename and move cleanup_*() to remove_*() to improve readability.
- Use EXPECT_*() for all FIXTURE_TEARDOWN() code.

Changes since v25:
* Add a new test to check that Landlock ruleset file descriptors received through UNIX sockets are usable. Contributed by Vincent Dagonneau.
* Improve hierarchy.trace tests to not hang when testing on a kernel that don't support Landlock.
* Replace EXPECT_EQ(0, close(*)) with ASSERT_EQ(0, close(*)).
* Guard WEXITSTATUS() use with WIFEXITED() in ptrace tests.
* Use pipe2(2) with O_CLOEXEC.
* Remove useless errno set for syscall wrappers, and related useless checks.
* Rename test.
* Add Microsoft copyright for layout1.interleaved_masked_accesses .

Changes since v24:
* Revert the ruleset_overlap test from v24: check that access righs are ORed together when building a ruleset. Keep the extra checks added with v24.
* Revert inherit_subset test from v24: use the automatic ORing of access rights for the same file.
* Update interleaved_masked_accesses test (added with v24) to stop when all layers allowed at least one time an inode in the path walk.
* Extend interleaved_masked_accesses test with new tricky interleaved layers which would not work as intended with (allow or deny) bitmask layer implementations.
* Simplify and rename test_path*() to test_open*() to make easier the diagnostic in case of unattended errors.
* Replace most call to open(2) with a call to test_open(), which reduces the number of lines and make tests more readable.
* Fix erroneous check in inherit_superset.

Changes since v23:
* Add an interleaved_masked_accesses test to check corner cases for interleaved layered ruleset combinations.
* Update ruleset_overlap and inherit_subset tests to follow the new intersect access rights behavior.
* Extend the inherit_superset test to check that layers are handled as expected in the superset use case, which complete the inherit_subset checks.
* Fix comment (spotted by Vincent Dagonneau).

Changes since v22:
* Extend and add a new test to better check rules applied to the root
directory: rule_over_root_allow_then_deny, rule_over_root_deny.
* Change the signature of test_path*() to make the calls clearer.

Changes since v21:
* Remove layout1.chroot test and update layout1.unhandled_access to not rely on LANDLOCK_ACCESS_FS_CHROOT.
* Clean up comments.

Changes since v20:
* Update with new syscalls and type names.
* Use the full syscall interfaces: explicitely set the "flags" field to zero.
* Update the empty_path_beneath_attr test to check for EFAULT.
* Update and merge tests for the simplified copy_min_struct_from_user().
* Clean up makefile.
* Rename some types and variables in a more consistent way.

Changes since v19:
* Update with the new Landlock syscalls.
* Fix device creation.
* Check the new landlock_attr_features members: last_rule_type and last_target_type .
* Constify variables.

Changes since v18:
* Replace ruleset_rw.inval with layout1.inval to avoid inexistent test layout.
* Use the new FIXTURE_VARIANT for ptrace_test: makes the tests more readable and usable.
* Add ARRAY_SIZE() macro to please checkpatch.

Changes since v17:
* Add new test for mknod with a zero mode.
* Use memset(3) to initialize attr_features in base_test.

Changes since v16:
* Add new unpriv_enforce_without_no_new_privs test: check that ruleset enforcing is forbiden without no_new_privs and CAP_SYS_ADMIN.
* Drop capabilities when useful.
* Check the new size_attr_features field from struct landlock_attr_features.
* Update the empty_or_same_ruleset test to check complementary empty ruleset.
* Update base_test according to the new attribute structures and fix the inconsistent_attr test accordingly.
* Switch syscall attribute pointer and size arguments.
* Rename test files with a "_test" suffix.

Changes since v14:
* Add new tests:
- superset: check new layer bitmask.
- max_layers: check maximum number of layers.
- release_inodes: check that umount work well.
- empty_or_same_ruleset.
- inconsistent_attr: checks copy_to_user limits.
- in ruleset_rw.inval to check ruleset FD.
- proc_unlinked_file: check file access through /proc/self/fd .
- file_access_rights: check that a file can only get consistent access rights.
- unpriv: check that NO_NEW_PRIVS or CAP_SYS_ADMIN is required.
- check pipe access through /proc/self/fd .
- check move_mount(2).
- check ruleset file descriptor properties.
- proc_nsfs: extend to check that internal filesystems (e.g. nsfs) are allowed.
* Double-check read and write effective actions.
* Fix potential desynchronization between the kernel sources and installed headers by overriding the build step in the Makefile. This also enable to build with Clang.
* Add two files in the test directories (for link test and rename test).
* Remove test for ruleset's show_fdinfo().
* Replace EBADR with EBADFD.
* Update tests accordingly to the changes of rename and link rights.
* Fix (now) illegal access rights tied to files.
* Update rename and link tests.
* Remove superfluous '\n' in TH_LOG() calls.
* Make assert calls consistent and readable.
* Fix the execute test.
* Make tests future-proof.
* Cosmetic fixes.

Changes since v14:
* Add new tests:
- Compatibility: empty_attr_{ruleset,path_beneath,enforce} to check minimal attr size.
- Access types: link_to, rename_from, rename_to, rmdir, unlink, make_char, make_block, make_reg, make_sock, make_fifo, make_sym, make_dir, chroot, execute.
- Test privilege escalation prevention by enforcing a nested rule, on a parent directory, with less restrictions than one on a child directory.
- Test for empty and more than 32-bits allowed_access
* Merge the two test mount hierarchies.
* Complete relative path tests by combining chdir and chroot.
* Adjust tests:
- Remove the layout1/extend_ruleset_with_denied_path test.
- Extend layout1/whitelist test with checks on file.
- Add and use create_dir_and_file().
* Only use read/write checks but not stat(2) for tests.
* Rename test.h to common.h and improve it.
* Rename path name to make them more consistent, easy to understand and make them in a common directory.
* Make create_ruleset() more generic.
* Constify variables.
* Re-add static global variables.
* Remove useless openat(2).
* Fix and complete kernel config.
* Set umask and clean up file modes.
* Clean up open flags.
* Improve Makefile.
* Fix spelling.
* Improve comments and error messages.

Changes since v13:
* Add back the filesystem tests (from v10) and extend them.
* Add tests for the new syscall.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 MAINTAINERS                                   |    1 +
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/landlock/.gitignore   |    2 +
 tools/testing/selftests/landlock/Makefile     |   24 +
 tools/testing/selftests/landlock/base_test.c  |  219 ++
 tools/testing/selftests/landlock/common.h     |  183 ++
 tools/testing/selftests/landlock/config       |    7 +
 tools/testing/selftests/landlock/fs_test.c    | 2792 +++++++++++++++++
 .../testing/selftests/landlock/ptrace_test.c  |  337 ++
 tools/testing/selftests/landlock/true.c       |    5 +
 10 files changed, 3571 insertions(+)
 create mode 100644 tools/testing/selftests/landlock/.gitignore
 create mode 100644 tools/testing/selftests/landlock/Makefile
 create mode 100644 tools/testing/selftests/landlock/base_test.c
 create mode 100644 tools/testing/selftests/landlock/common.h
 create mode 100644 tools/testing/selftests/landlock/config
 create mode 100644 tools/testing/selftests/landlock/fs_test.c
 create mode 100644 tools/testing/selftests/landlock/ptrace_test.c
 create mode 100644 tools/testing/selftests/landlock/true.c
MAINTAINERS +1 -0
index 70ec117efa8a..8cab5854844e 100644
@@ -10005,6 +10005,7 @@ W:	https://landlock.io
 T:	git https://github.com/landlock-lsm/linux.git
 F:	include/uapi/linux/landlock.h
 F:	security/landlock/
+F:	tools/testing/selftests/landlock/
 K:	landlock
 K:	LANDLOCK
 
tools/testing/selftests/Makefile +1 -0
index 6c575cf34a71..bc3299a20338 100644
@@ -25,6 +25,7 @@ TARGETS += ir
 TARGETS += kcmp
 TARGETS += kexec
 TARGETS += kvm
+TARGETS += landlock
 TARGETS += lib
 TARGETS += livepatch
 TARGETS += lkdtm
tools/testing/selftests/landlock/.gitignore new file +2 -0
new file mode 100644
index 000000000000..470203a7cd73
@@ -0,0 +1,2 @@
+/*_test
+/true
tools/testing/selftests/landlock/Makefile new file +24 -0
new file mode 100644
index 000000000000..a99596ca9882
@@ -0,0 +1,24 @@
+# SPDX-License-Identifier: GPL-2.0
+
+CFLAGS += -Wall -O2
+
+src_test := $(wildcard *_test.c)
+
+TEST_GEN_PROGS := $(src_test:.c=)
+
+TEST_GEN_PROGS_EXTENDED := true
+
+KSFT_KHDR_INSTALL := 1
+OVERRIDE_TARGETS := 1
+include ../lib.mk
+
+khdr_dir = $(top_srcdir)/usr/include
+
+$(khdr_dir)/linux/landlock.h: khdr
+	@:
+
+$(OUTPUT)/true: true.c
+	$(LINK.c) $< $(LDLIBS) -o $@ -static
+
+$(OUTPUT)/%_test: %_test.c $(khdr_dir)/linux/landlock.h ../kselftest_harness.h common.h
+	$(LINK.c) $< $(LDLIBS) -o $@ -lcap -I$(khdr_dir)
tools/testing/selftests/landlock/base_test.c new file +219 -0

219 lines not on this page · raw message

tools/testing/selftests/landlock/common.h new file +183 -0

183 lines not on this page · raw message

tools/testing/selftests/landlock/config new file +7 -0
new file mode 100644
index 000000000000..0f0a65287bac
@@ -0,0 +1,7 @@
+CONFIG_OVERLAY_FS=y
+CONFIG_SECURITY_LANDLOCK=y
+CONFIG_SECURITY_PATH=y
+CONFIG_SECURITY=y
+CONFIG_SHMEM=y
+CONFIG_TMPFS_XATTR=y
+CONFIG_TMPFS=y
tools/testing/selftests/landlock/fs_test.c new file +2792 -0

2,551 lines not on this page · raw message

tools/testing/selftests/landlock/ptrace_test.c new file +337 -0

337 lines not on this page · raw message

tools/testing/selftests/landlock/true.c new file +5 -0
new file mode 100644
index 000000000000..3f9ccbf52783

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.30.2

Part of the diff is not shown here. View the raw message.

#36 lore raw

Re: [PATCH v30 10/12] selftests/landlock: Add user space tests

Quoted 9 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Test all Landlock system calls, ptrace hooks semantic and filesystem access-control with multiple layouts.

Test coverage for security/landlock/ is 93.6% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions.

Quoted 8 lines

This is terrific. I love the coverage. How did you measure this, BTW? To increase it into memory allocation failures, have you tried allocation fault injection:
https://www.kernel.org/doc/html/latest/fault-injection/fault-injection.html

Quoted 4 lines

[...]

tools/testing/selftests/landlock/base_test.c new file +3 -0
+TEST(inconsistent_attr) {
+	const long page_size = sysconf(_SC_PAGESIZE);
+	char *const buf = malloc(page_size + 1);

tools/testing/selftests/landlock/base_test.c line 36

Quoted 10 lines
tools/testing/selftests/landlock/base_test.c new file +10 -0
+	struct landlock_ruleset_attr *const ruleset_attr = (void *)buf;
+
+	ASSERT_NE(NULL, buf);
+
+	/* Checks copy_from_user(). */
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 0, 0));
+	/* The size if less than sizeof(struct landlock_attr_enforce). */
+	ASSERT_EQ(EINVAL, errno);
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 1, 0));
+	ASSERT_EQ(EINVAL, errno);

Almost everywhere you're using ASSERT instead of EXPECT. Is this correct (in the sense than as soon as an ASSERT fails the rest of the test is skipped)? I do see you using EXPECT is some places, but I figured I'd ask about the intention here.

Quoted 8 lines

+/*
+ * TEST_F_FORK() is useful when a test drop privileges but the corresponding
+ * FIXTURE_TEARDOWN() requires them (e.g. to remove files from a directory
+ * where write actions are denied). For convenience, FIXTURE_TEARDOWN() is
+ * also called when the test failed, but not when FIXTURE_SETUP() failed. For
+ * this to be possible, we must not call abort() but instead exit smoothly
+ * (hence the step print).
+ */

Hm, interesting. I think this should be extracted into a separate patch and added to the test harness proper.

Could this be solved with TEARDOWN being called on SETUP failure?

Quoted 31 lines
tools/testing/selftests/landlock/common.h new file +31 -0
+#define TEST_F_FORK(fixture_name, test_name) \
+	static void fixture_name##_##test_name##_child( \
+		struct __test_metadata *_metadata, \
+		FIXTURE_DATA(fixture_name) *self, \
+		const FIXTURE_VARIANT(fixture_name) *variant); \
+	TEST_F(fixture_name, test_name) \
+	{ \
+		int status; \
+		const pid_t child = fork(); \
+		if (child < 0) \
+			abort(); \
+		if (child == 0) { \
+			_metadata->no_print = 1; \
+			fixture_name##_##test_name##_child(_metadata, self, variant); \
+			if (_metadata->skip) \
+				_exit(255); \
+			if (_metadata->passed) \
+				_exit(0); \
+			_exit(_metadata->step); \
+		} \
+		if (child != waitpid(child, &status, 0)) \
+			abort(); \
+		if (WIFSIGNALED(status) || !WIFEXITED(status)) { \
+			_metadata->passed = 0; \
+			_metadata->step = 1; \
+			return; \
+		} \
+		switch (WEXITSTATUS(status)) { \
+		case 0: \
+			_metadata->passed = 1; \
+			break; \

tools/testing/selftests/landlock/common.h line 72

Quoted 10 lines
tools/testing/selftests/landlock/common.h new file +10 -0
+		case 255: \
+			_metadata->passed = 1; \
+			_metadata->skip = 1; \
+			break; \
+		default: \
+			_metadata->passed = 0; \
+			_metadata->step = WEXITSTATUS(status); \
+			break; \
+		} \
+	} \

This looks like a subset of __wait_for_test()? Could __TEST_F_IMPL() be updated instead to do this? (Though the fork overhead might not be great for everyone.)

Signature · 1 line
Kees Cook
author maintainer
#37 lore raw

Re: [PATCH v30 10/12] selftests/landlock: Add user space tests

Quoted 19 lines · Kees Cook
Quoted 9 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Test all Landlock system calls, ptrace hooks semantic and filesystem access-control with multiple layouts.

Test coverage for security/landlock/ is 93.6% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions.

Quoted 8 lines
Quoted 1 line

This is terrific. I love the coverage. How did you measure this, BTW?

I used gcov: https://www.kernel.org/doc/html/latest/dev-tools/gcov.html

Quoted 3 lines

To increase it into memory allocation failures, have you tried allocation fault injection:
https://www.kernel.org/doc/html/latest/fault-injection/fault-injection.html

Yes, it is used by syzkaller, but I don't know how to extract this specific coverage.

Quoted 12 lines
Quoted 12 lines

[...]

tools/testing/selftests/landlock/base_test.c new file +10 -0
+TEST(inconsistent_attr) {
+	const long page_size = sysconf(_SC_PAGESIZE);
+	char *const buf = malloc(page_size + 1);
+	struct landlock_ruleset_attr *const ruleset_attr = (void *)buf;
+
+	ASSERT_NE(NULL, buf);
+
+	/* Checks copy_from_user(). */
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 0, 0));
+	/* The size if less than sizeof(struct landlock_attr_enforce). */
Quoted 8 lines

tools/testing/selftests/landlock/base_test.c line 36

Quoted 3 lines
tools/testing/selftests/landlock/base_test.c new file +3 -0
+	ASSERT_EQ(EINVAL, errno);
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 1, 0));
+	ASSERT_EQ(EINVAL, errno);

Almost everywhere you're using ASSERT instead of EXPECT. Is this correct (in the sense than as soon as an ASSERT fails the rest of the test is skipped)? I do see you using EXPECT is some places, but I figured I'd ask about the intention here.

I intentionally use ASSERT as much as possible, but I use EXPECT when an error could block a test or when it could stop a cleanup (i.e. teardown).

Quoted 10 lines
Quoted 9 lines

+/*
+ * TEST_F_FORK() is useful when a test drop privileges but the corresponding
+ * FIXTURE_TEARDOWN() requires them (e.g. to remove files from a directory
+ * where write actions are denied). For convenience, FIXTURE_TEARDOWN() is
+ * also called when the test failed, but not when FIXTURE_SETUP() failed. For
+ * this to be possible, we must not call abort() but instead exit smoothly
+ * (hence the step print).
+ */

Quoted 2 lines

Hm, interesting. I think this should be extracted into a separate patch and added to the test harness proper.

I agree, but it may require some modifications to fit nicely in kselftest_harness.h . For now, it works well for my use case. I'll send patches once Landlock is merged. In fact, I already made kselftest_harness.h available for other users than seccomp. ;)

Quoted 2 lines

Could this be solved with TEARDOWN being called on SETUP failure?

The goal of this helper is to still be able to call TEARDOWN when TEST failed, not SETUP.

Quoted 38 lines
Quoted 38 lines
tools/testing/selftests/landlock/common.h new file +37 -0
+#define TEST_F_FORK(fixture_name, test_name) \
+	static void fixture_name##_##test_name##_child( \
+		struct __test_metadata *_metadata, \
+		FIXTURE_DATA(fixture_name) *self, \
+		const FIXTURE_VARIANT(fixture_name) *variant); \
+	TEST_F(fixture_name, test_name) \
+	{ \
+		int status; \
+		const pid_t child = fork(); \
+		if (child < 0) \
+			abort(); \
+		if (child == 0) { \
+			_metadata->no_print = 1; \
+			fixture_name##_##test_name##_child(_metadata, self, variant); \
+			if (_metadata->skip) \
+				_exit(255); \
+			if (_metadata->passed) \
+				_exit(0); \
+			_exit(_metadata->step); \
+		} \
+		if (child != waitpid(child, &status, 0)) \
+			abort(); \
+		if (WIFSIGNALED(status) || !WIFEXITED(status)) { \
+			_metadata->passed = 0; \
+			_metadata->step = 1; \
+			return; \
+		} \
+		switch (WEXITSTATUS(status)) { \
+		case 0: \
+			_metadata->passed = 1; \
+			break; \
+		case 255: \
+			_metadata->passed = 1; \
+			_metadata->skip = 1; \
+			break; \
+		default: \
+			_metadata->passed = 0; \
Quoted 8 lines

tools/testing/selftests/landlock/common.h line 72

Quoted 4 lines
tools/testing/selftests/landlock/common.h new file +4 -0
+			_metadata->step = WEXITSTATUS(status); \
+			break; \
+		} \
+	} \

This looks like a subset of __wait_for_test()? Could __TEST_F_IMPL() be updated instead to do this? (Though the fork overhead might not be great for everyone.)

Yes, it will probably be my approach to update kselftest_harness.h .

#38 lore raw

Re: [PATCH v30 10/12] selftests/landlock: Add user space tests

Quoted 53 lines · Mickaël Salaün
Quoted 19 lines · Kees Cook
Quoted 9 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Test all Landlock system calls, ptrace hooks semantic and filesystem access-control with multiple layouts.

Test coverage for security/landlock/ is 93.6% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions.

Quoted 8 lines
Quoted 1 line

This is terrific. I love the coverage. How did you measure this, BTW?

I used gcov: https://www.kernel.org/doc/html/latest/dev-tools/gcov.html

Quoted 3 lines

To increase it into memory allocation failures, have you tried allocation fault injection:
https://www.kernel.org/doc/html/latest/fault-injection/fault-injection.html

Yes, it is used by syzkaller, but I don't know how to extract this specific coverage.

Quoted 12 lines
Quoted 12 lines

[...]

tools/testing/selftests/landlock/base_test.c new file +10 -0
+TEST(inconsistent_attr) {
+	const long page_size = sysconf(_SC_PAGESIZE);
+	char *const buf = malloc(page_size + 1);
+	struct landlock_ruleset_attr *const ruleset_attr = (void *)buf;
+
+	ASSERT_NE(NULL, buf);
+
+	/* Checks copy_from_user(). */
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 0, 0));
+	/* The size if less than sizeof(struct landlock_attr_enforce). */
Quoted 8 lines

tools/testing/selftests/landlock/base_test.c line 36

Quoted 3 lines
tools/testing/selftests/landlock/base_test.c new file +3 -0
+	ASSERT_EQ(EINVAL, errno);
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 1, 0));
+	ASSERT_EQ(EINVAL, errno);

Almost everywhere you're using ASSERT instead of EXPECT. Is this correct (in the sense than as soon as an ASSERT fails the rest of the test is skipped)? I do see you using EXPECT is some places, but I figured I'd ask about the intention here.

Quoted 2 lines

I intentionally use ASSERT as much as possible, but I use EXPECT when an error could block a test or when it could stop a cleanup (i.e. teardown).

Okay. Does the test suite run sanely when landlock is missing from the kernel?

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines

+/*
+ * TEST_F_FORK() is useful when a test drop privileges but the corresponding
+ * FIXTURE_TEARDOWN() requires them (e.g. to remove files from a directory
+ * where write actions are denied). For convenience, FIXTURE_TEARDOWN() is
+ * also called when the test failed, but not when FIXTURE_SETUP() failed. For
+ * this to be possible, we must not call abort() but instead exit smoothly
+ * (hence the step print).
+ */

Quoted 7 lines
Quoted 2 lines

Hm, interesting. I think this should be extracted into a separate patch and added to the test harness proper.

I agree, but it may require some modifications to fit nicely in kselftest_harness.h . For now, it works well for my use case. I'll send patches once Landlock is merged. In fact, I already made kselftest_harness.h available for other users than seccomp. ;)

Fair points.

Quoted 53 lines
Quoted 2 lines

Could this be solved with TEARDOWN being called on SETUP failure?

The goal of this helper is to still be able to call TEARDOWN when TEST failed, not SETUP.

Quoted 38 lines
Quoted 38 lines
tools/testing/selftests/landlock/common.h new file +37 -0
+#define TEST_F_FORK(fixture_name, test_name) \
+	static void fixture_name##_##test_name##_child( \
+		struct __test_metadata *_metadata, \
+		FIXTURE_DATA(fixture_name) *self, \
+		const FIXTURE_VARIANT(fixture_name) *variant); \
+	TEST_F(fixture_name, test_name) \
+	{ \
+		int status; \
+		const pid_t child = fork(); \
+		if (child < 0) \
+			abort(); \
+		if (child == 0) { \
+			_metadata->no_print = 1; \
+			fixture_name##_##test_name##_child(_metadata, self, variant); \
+			if (_metadata->skip) \
+				_exit(255); \
+			if (_metadata->passed) \
+				_exit(0); \
+			_exit(_metadata->step); \
+		} \
+		if (child != waitpid(child, &status, 0)) \
+			abort(); \
+		if (WIFSIGNALED(status) || !WIFEXITED(status)) { \
+			_metadata->passed = 0; \
+			_metadata->step = 1; \
+			return; \
+		} \
+		switch (WEXITSTATUS(status)) { \
+		case 0: \
+			_metadata->passed = 1; \
+			break; \
+		case 255: \
+			_metadata->passed = 1; \
+			_metadata->skip = 1; \
+			break; \
+		default: \
+			_metadata->passed = 0; \
Quoted 8 lines

tools/testing/selftests/landlock/common.h line 72

Quoted 4 lines
tools/testing/selftests/landlock/common.h new file +4 -0
+			_metadata->step = WEXITSTATUS(status); \
+			break; \
+		} \
+	} \

This looks like a subset of __wait_for_test()? Could __TEST_F_IMPL() be updated instead to do this? (Though the fork overhead might not be great for everyone.)

Quoted 1 line

Yes, it will probably be my approach to update kselftest_harness.h .

It seems like this would be named better as TEST_DROPS_PRIVS or something, which describes the reason for the fork.

Signature · 1 line
Kees Cook
author maintainer
#39 lore raw

Re: [PATCH v30 10/12] selftests/landlock: Add user space tests

Quoted 54 lines · Kees Cook
Quoted 53 lines · Mickaël Salaün
Quoted 19 lines · Kees Cook
Quoted 9 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Test all Landlock system calls, ptrace hooks semantic and filesystem access-control with multiple layouts.

Test coverage for security/landlock/ is 93.6% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions.

Quoted 8 lines
Quoted 1 line

This is terrific. I love the coverage. How did you measure this, BTW?

I used gcov: https://www.kernel.org/doc/html/latest/dev-tools/gcov.html

Quoted 3 lines

To increase it into memory allocation failures, have you tried allocation fault injection:
https://www.kernel.org/doc/html/latest/fault-injection/fault-injection.html

Yes, it is used by syzkaller, but I don't know how to extract this specific coverage.

Quoted 20 lines
Quoted 5 lines

[...]

tools/testing/selftests/landlock/base_test.c new file +3 -0
+TEST(inconsistent_attr) {
+	const long page_size = sysconf(_SC_PAGESIZE);
+	char *const buf = malloc(page_size + 1);

tools/testing/selftests/landlock/base_test.c line 36

Quoted 10 lines
tools/testing/selftests/landlock/base_test.c new file +10 -0
+	struct landlock_ruleset_attr *const ruleset_attr = (void *)buf;
+
+	ASSERT_NE(NULL, buf);
+
+	/* Checks copy_from_user(). */
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 0, 0));
+	/* The size if less than sizeof(struct landlock_attr_enforce). */
+	ASSERT_EQ(EINVAL, errno);
+	ASSERT_EQ(-1, landlock_create_ruleset(ruleset_attr, 1, 0));
+	ASSERT_EQ(EINVAL, errno);

Almost everywhere you're using ASSERT instead of EXPECT. Is this correct (in the sense than as soon as an ASSERT fails the rest of the test is skipped)? I do see you using EXPECT is some places, but I figured I'd ask about the intention here.

Quoted 5 lines
Quoted 2 lines

I intentionally use ASSERT as much as possible, but I use EXPECT when an error could block a test or when it could stop a cleanup (i.e. teardown).

Okay. Does the test suite run sanely when landlock is missing from the kernel?

When Landlock is disabled, the tests fail but do not hang.

Quoted 74 lines
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

+/*
+ * TEST_F_FORK() is useful when a test drop privileges but the corresponding
+ * FIXTURE_TEARDOWN() requires them (e.g. to remove files from a directory
+ * where write actions are denied). For convenience, FIXTURE_TEARDOWN() is
+ * also called when the test failed, but not when FIXTURE_SETUP() failed. For
+ * this to be possible, we must not call abort() but instead exit smoothly
+ * (hence the step print).
+ */

Quoted 7 lines
Quoted 2 lines

Hm, interesting. I think this should be extracted into a separate patch and added to the test harness proper.

I agree, but it may require some modifications to fit nicely in kselftest_harness.h . For now, it works well for my use case. I'll send patches once Landlock is merged. In fact, I already made kselftest_harness.h available for other users than seccomp. ;)

Fair points.

Quoted 53 lines
Quoted 2 lines

Could this be solved with TEARDOWN being called on SETUP failure?

The goal of this helper is to still be able to call TEARDOWN when TEST failed, not SETUP.

Quoted 46 lines
Quoted 32 lines
tools/testing/selftests/landlock/common.h new file +31 -0
+#define TEST_F_FORK(fixture_name, test_name) \
+	static void fixture_name##_##test_name##_child( \
+		struct __test_metadata *_metadata, \
+		FIXTURE_DATA(fixture_name) *self, \
+		const FIXTURE_VARIANT(fixture_name) *variant); \
+	TEST_F(fixture_name, test_name) \
+	{ \
+		int status; \
+		const pid_t child = fork(); \
+		if (child < 0) \
+			abort(); \
+		if (child == 0) { \
+			_metadata->no_print = 1; \
+			fixture_name##_##test_name##_child(_metadata, self, variant); \
+			if (_metadata->skip) \
+				_exit(255); \
+			if (_metadata->passed) \
+				_exit(0); \
+			_exit(_metadata->step); \
+		} \
+		if (child != waitpid(child, &status, 0)) \
+			abort(); \
+		if (WIFSIGNALED(status) || !WIFEXITED(status)) { \
+			_metadata->passed = 0; \
+			_metadata->step = 1; \
+			return; \
+		} \
+		switch (WEXITSTATUS(status)) { \
+		case 0: \
+			_metadata->passed = 1; \
+			break; \

tools/testing/selftests/landlock/common.h line 72

Quoted 10 lines
tools/testing/selftests/landlock/common.h new file +10 -0
+		case 255: \
+			_metadata->passed = 1; \
+			_metadata->skip = 1; \
+			break; \
+		default: \
+			_metadata->passed = 0; \
+			_metadata->step = WEXITSTATUS(status); \
+			break; \
+		} \
+	} \

This looks like a subset of __wait_for_test()? Could __TEST_F_IMPL() be updated instead to do this? (Though the fork overhead might not be great for everyone.)

Quoted 4 lines
Quoted 1 line

Yes, it will probably be my approach to update kselftest_harness.h .

It seems like this would be named better as TEST_DROPS_PRIVS or something, which describes the reason for the fork.

Yeah, maybe, we could discuss about that in a dedicated patch series. :)

author maintainer
#40 lore raw

PATCH v30 11/12 samples/landlock: Add a sandbox manager example

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Add a basic sandbox tool to launch a command which can only access a list of file hierarchies in a read-only or read-write way.

---

Changes since v28:
* Simplify Kconfig option title.

Changes since v27:
* Add samples/landlock/ to MAINTAINERS.
* Update landlock_restrict_self(2).
* Tweak Kconfig title and description.

Changes since v25:
* Improve comments and fix help (suggested by Jann Horn).
* Add a safeguard for errno check (suggested by Jann Horn).
* Allows users to not use all possible restrictions (e.g. use LL_FS_RO without LL_FS_RW).
* Update syscall names.
* Improve Makefile:
- Replace hostprogs/always-y with userprogs-always-y, available since commit faabed295ccc ("kbuild: introduce hostprogs-always-y and userprogs-always-y").
- Depends on CC_CAN_LINK.
* Add Reviewed-by Jann Horn.

Changes since v25:
* Remove useless errno set in the syscall wrappers.
* Cosmetic variable renames.

Changes since v23:
* Re-add hints to help users understand the required kernel configuration. This was removed with the removal of landlock_get_features(2).

Changes since v21:
* Remove LANDLOCK_ACCESS_FS_CHROOT.
* Clean up help.

Changes since v20:
* Update with new syscalls and type names.
* Update errno check for EOPNOTSUPP.
* Use the full syscall interfaces: explicitely set the "flags" field to zero.

Changes since v19:
* Update with the new Landlock syscalls.
* Comply with commit 5f2fb52fac15 ("kbuild: rename hostprogs-y/always to hostprogs/always-y").

Changes since v16:
* Switch syscall attribute pointer and size arguments.

Changes since v15:
* Update access right names.
* Properly assign access right to files according to the new related syscall restriction.
* Replace "select" with "depends on" HEADERS_INSTALL (suggested by Randy Dunlap).

Changes since v14:
* Fix Kconfig dependency.
* Remove access rights that may be required for FD-only requests:
mmap, truncate, getattr, lock, chmod, chown, chgrp, ioctl.
* Fix useless hardcoded syscall number.
* Use execvpe().
* Follow symlinks.
* Extend help with common file paths.
* Constify variables.
* Clean up comments.
* Improve error message.

Changes since v11:
* Add back the filesystem sandbox manager and update it to work with the new Landlock syscall.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 MAINTAINERS                  |   1 +
 samples/Kconfig              |   7 ++
 samples/Makefile             |   1 +
 samples/landlock/.gitignore  |   1 +
 samples/landlock/Makefile    |  13 ++
 samples/landlock/sandboxer.c | 238 +++++++++++++++++++++++++++++++++++
 6 files changed, 261 insertions(+)
 create mode 100644 samples/landlock/.gitignore
 create mode 100644 samples/landlock/Makefile
 create mode 100644 samples/landlock/sandboxer.c
MAINTAINERS +1 -0
index 8cab5854844e..88175ed1f315 100644
@@ -10004,6 +10004,7 @@ S:	Supported
 W:	https://landlock.io
 T:	git https://github.com/landlock-lsm/linux.git
 F:	include/uapi/linux/landlock.h
+F:	samples/landlock/
 F:	security/landlock/
 F:	tools/testing/selftests/landlock/
 K:	landlock
samples/Kconfig +7 -0
index e76cdfc50e25..b5a1a7aa7e23 100644
@@ -124,6 +124,13 @@ config SAMPLE_HIDRAW
 	bool "hidraw sample"
 	depends on CC_CAN_LINK && HEADERS_INSTALL
 
+config SAMPLE_LANDLOCK
+	bool "Landlock example"
+	depends on CC_CAN_LINK && HEADERS_INSTALL
+	help
+	  Build a simple Landlock sandbox manager able to start a process
+	  restricted by a user-defined filesystem access control policy.
+
 config SAMPLE_PIDFD
 	bool "pidfd sample"
 	depends on CC_CAN_LINK && HEADERS_INSTALL
samples/Makefile +1 -0
index c3392a595e4b..087e0988ccc5 100644
@@ -11,6 +11,7 @@ obj-$(CONFIG_SAMPLE_KDB)		+= kdb/
 obj-$(CONFIG_SAMPLE_KFIFO)		+= kfifo/
 obj-$(CONFIG_SAMPLE_KOBJECT)		+= kobject/
 obj-$(CONFIG_SAMPLE_KPROBES)		+= kprobes/
+subdir-$(CONFIG_SAMPLE_LANDLOCK)	+= landlock
 obj-$(CONFIG_SAMPLE_LIVEPATCH)		+= livepatch/
 subdir-$(CONFIG_SAMPLE_PIDFD)		+= pidfd
 obj-$(CONFIG_SAMPLE_QMI_CLIENT)		+= qmi/
samples/landlock/.gitignore new file +1 -0
new file mode 100644
index 000000000000..f43668b2d318
@@ -0,0 +1 @@
+/sandboxer
samples/landlock/Makefile new file +13 -0
new file mode 100644
index 000000000000..5d601e51c2eb
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: BSD-3-Clause
+
+userprogs-always-y := sandboxer
+
+userccflags += -I usr/include
+
+.PHONY: all clean
+
+all:
+	$(MAKE) -C ../.. samples/landlock/
+
+clean:
+	$(MAKE) -C ../.. M=samples/landlock/ clean
samples/landlock/sandboxer.c new file +238 -0

238 lines not on this page · raw message

Signature · 1 line
2.30.2
Reviewed-by on v30 11/12
#41 lore raw

Re: [PATCH v30 11/12] samples/landlock: Add a sandbox manager example

Quoted 9 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

Add a basic sandbox tool to launch a command which can only access a list of file hierarchies in a read-only or read-write way.

Cc James Morris <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

I'm very happy to see any example!

Signature · 1 line
Kees Cook
author maintainer
#42 lore raw

PATCH v30 12/12 landlock: Add user and kernel documentation

In reply to Mickaël Salaün

From: Mickaël Salaün <[email protected]>

This documentation can be built with the Sphinx framework.

---

Changes since v28:
* Reorder subsections by importance in the "Current limitations" section.

Changes since v27:
* Update landlock_restrict_self(2).
* Update date and copyright.

Changes since v25:
* Explain the behavior of layered access rights.
* Explain how bind mounts and overayfs mounts are handled by Landlock:
merged overlayfs mount points have their own inodes, which makes these hierarchies independent from its upper and lower layers, unlike bind mounts which share the same inodes between the source hierarchy and the mount point hierarchy.
New overlayfs mount and bind mount tests check these behaviors.
* Synchronize with the new syscalls.c file and update syscall names.
* Fix spelling.
* Remove Reviewed-by Jann Horn because of the above changes.

Changes since v24:
* Add Reviewed-by Jann Horn.
* Add a paragraph to explain how the ruleset layers work.
* Bump date.

Changes since v23:
* Explain limitations for the maximum number of stacked ruleset, and the memory usage restrictions.

Changes since v22:
* Fix spelling and remove obsolete sentence (spotted by Jann Horn).
* Bump date.

Changes since v21:
* Move the user space documentation to userspace-api/landlock.rst and the kernel documentation to security/landlock.rst .
* Add license headers.
* Add last update dates.
* Update MAINTAINERS file.
* Add (back) links to git.kernel.org .
* Fix spelling.

Changes since v20:
* Update examples and documentation with the new syscalls.

Changes since v19:
* Update examples and documentation with the new syscalls.

Changes since v15:
* Add current limitations.

Changes since v14:
* Fix spelling (contributed by Randy Dunlap).
* Extend documentation about inheritance and explain layer levels.
* Remove the use of now-removed access rights.
* Use GitHub links.
* Improve kernel documentation.
* Add section for tests.
* Update example.

Changes since v13:
* Rewrote the documentation according to the major revamp.

Previous changes:
https://lore.kernel.org/lkml/[email protected]/

---
 Documentation/security/index.rst         |   1 +
 Documentation/security/landlock.rst      |  79 ++++++
 Documentation/userspace-api/index.rst    |   1 +
 Documentation/userspace-api/landlock.rst | 307 +++++++++++++++++++++++
 MAINTAINERS                              |   2 +
 5 files changed, 390 insertions(+)
 create mode 100644 Documentation/security/landlock.rst
 create mode 100644 Documentation/userspace-api/landlock.rst
Documentation/security/index.rst +1 -0
index 8129405eb2cc..16335de04e8c 100644
@@ -16,3 +16,4 @@ Security Documentation
    siphash
    tpm/index
    digsig
+   landlock
Documentation/security/landlock.rst new file +79 -0

79 lines not on this page · raw message

Documentation/userspace-api/index.rst +1 -0
index d29b020e5622..744c6491610c 100644
@@ -18,6 +18,7 @@ place where this information is gathered.
 
    no_new_privs
    seccomp_filter
+   landlock
    unshare
    spec_ctrl
    accelerators/ocxl
Documentation/userspace-api/landlock.rst new file +307 -0

307 lines not on this page · raw message

MAINTAINERS +2 -0
index 88175ed1f315..7b0c6de5946a 100644
@@ -10003,6 +10003,8 @@ L:	[email protected]
 S:	Supported
 W:	https://landlock.io
 T:	git https://github.com/landlock-lsm/linux.git
+F:	Documentation/security/landlock.rst
+F:	Documentation/userspace-api/landlock.rst
 F:	include/uapi/linux/landlock.h
 F:	samples/landlock/
 F:	security/landlock/
Signature · 1 line
2.30.2
#43 lore raw

Re: [PATCH v30 12/12] landlock: Add user and kernel documentation

Quoted 3 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

This documentation can be built with the Sphinx framework.

Well, yes. :) Maybe describe what the documentation covers instead here.
Regardless: yay docs! This is great.

Quoted 13 lines

[...]

Documentation/userspace-api/landlock.rst new file +12 -0
+Bind mounts and OverlayFS
+-------------------------
+
+Landlock enables to restrict access to file hierarchies, which means that these
+access rights can be propagated with bind mounts (cf.
+:doc:`/filesystems/sharedsubtree`) but not with :doc:`/filesystems/overlayfs`.
+
+A bind mount mirrors a source file hierarchy to a destination.  The destination
+hierarchy is then composed of the exact same files, on which Landlock rules can
+be tied, either via the source or the destination path.  These rules restrict
+access when they are encountered on a path, which means that they can restrict
+access to multiple file hierarchies at the same time, whether these hierarchies

Documentation/userspace-api/landlock.rst line 164

Quoted 10 lines
Documentation/userspace-api/landlock.rst new file +10 -0
+are the result of bind mounts or not.
+
+An OverlayFS mount point consists of upper and lower layers.  These layers are
+combined in a merge directory, result of the mount point.  This merge hierarchy
+may include files from the upper and lower layers, but modifications performed
+on the merge hierarchy only reflects on the upper layer.  From a Landlock
+policy point of view, each OverlayFS layers and merge hierarchies are
+standalone and contains their own set of files and directories, which is
+different from bind mounts.  A policy restricting an OverlayFS layer will not
+restrict the resulted merged hierarchy, and vice versa.

Can you include some examples about what a user of landlock should do? i.e. what are some examples of unexpected results when trying to write policy that runs on top of overlayfs, etc?

Documentation/userspace-api/landlock.rst line 238

Quoted 12 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+File renaming and linking
+-------------------------
+
+Because Landlock targets unprivileged access controls, it is needed to properly
+handle composition of rules.  Such property also implies rules nesting.
+Properly handling multiple layers of ruleset, each one of them able to restrict
+access to files, also implies to inherit the ruleset restrictions from a parent
+to its hierarchy.  Because files are identified and restricted by their
+hierarchy, moving or linking a file from one directory to another implies to
+propagate the hierarchy constraints.  To protect against privilege escalations
+through renaming or linking, and for the sack of simplicity, Landlock currently

typo: sack -> sake

Documentation/userspace-api/landlock.rst line 260

Quoted 12 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+Special filesystems
+-------------------
+
+Access to regular files and directories can be restricted by Landlock,
+according to the handled accesses of a ruleset.  However, files that do not
+come from a user-visible filesystem (e.g. pipe, socket), but can still be
+accessed through /proc/self/fd/, cannot currently be restricted.  Likewise,
+some special kernel filesystems such as nsfs, which can be accessed through
+/proc/self/ns/, cannot currently be restricted.  For now, these kind of special
+paths are then always allowed.  Future Landlock evolutions will enable to
+restrict such paths with dedicated ruleset flags.

With this series, can /proc (at the top level) be blocked? (i.e. can a landlock user avoid the weirdness by making /proc/$pid/ unavailable?)

Documentation/userspace-api/landlock.rst line 271

Quoted 10 lines
Documentation/userspace-api/landlock.rst new file +10 -0
+Ruleset layers
+--------------
+
+There is a limit of 64 layers of stacked rulesets.  This can be an issue for a
+task willing to enforce a new ruleset in complement to its 64 inherited
+rulesets.  Once this limit is reached, sys_landlock_restrict_self() returns
+E2BIG.  It is then strongly suggested to carefully build rulesets once in the
+life of a thread, especially for applications able to launch other applications
+that may also want to sandbox themselves (e.g. shells, container managers,
+etc.).

How was this value (64) chosen?

Signature · 1 line
Kees Cook
author maintainer
#44 lore raw

Re: [PATCH v30 12/12] landlock: Add user and kernel documentation

Quoted 7 lines · Kees Cook
Quoted 3 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

This documentation can be built with the Sphinx framework.

Well, yes. :) Maybe describe what the documentation covers instead here.
Regardless: yay docs! This is great.

Well, I don't know what to describe other than the subject, the rest is in the patch. :)

Quoted 20 lines
Quoted 20 lines

[...]

Documentation/userspace-api/landlock.rst new file +18 -0
+Bind mounts and OverlayFS
+-------------------------
+
+Landlock enables to restrict access to file hierarchies, which means that these
+access rights can be propagated with bind mounts (cf.
+:doc:`/filesystems/sharedsubtree`) but not with :doc:`/filesystems/overlayfs`.
+
+A bind mount mirrors a source file hierarchy to a destination.  The destination
+hierarchy is then composed of the exact same files, on which Landlock rules can
+be tied, either via the source or the destination path.  These rules restrict
+access when they are encountered on a path, which means that they can restrict
+access to multiple file hierarchies at the same time, whether these hierarchies
+are the result of bind mounts or not.
+
+An OverlayFS mount point consists of upper and lower layers.  These layers are
+combined in a merge directory, result of the mount point.  This merge hierarchy
+may include files from the upper and lower layers, but modifications performed
+on the merge hierarchy only reflects on the upper layer.  From a Landlock
Quoted 8 lines

Documentation/userspace-api/landlock.rst line 164

Quoted 4 lines
Documentation/userspace-api/landlock.rst new file +4 -0
+policy point of view, each OverlayFS layers and merge hierarchies are
+standalone and contains their own set of files and directories, which is
+different from bind mounts.  A policy restricting an OverlayFS layer will not
+restrict the resulted merged hierarchy, and vice versa.

Can you include some examples about what a user of landlock should do? i.e. what are some examples of unexpected results when trying to write policy that runs on top of overlayfs, etc?

Landlock works well with overlayfs, at least from my point of view. It may be a bit disturbing with bind mount though, but it is the same with other access-controls (e.g. DAC). Landlock users should just think about file hierarchies and create their policies accordingly. A user should not try to adapt a policy according to his/her understanding of overlayfs, but just think about file hierarchies.

Quoted 15 lines

Documentation/userspace-api/landlock.rst line 238

Quoted 13 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+File renaming and linking
+-------------------------
+
+Because Landlock targets unprivileged access controls, it is needed to properly
+handle composition of rules.  Such property also implies rules nesting.
+Properly handling multiple layers of ruleset, each one of them able to restrict
+access to files, also implies to inherit the ruleset restrictions from a parent
+to its hierarchy.  Because files are identified and restricted by their
+hierarchy, moving or linking a file from one directory to another implies to
+propagate the hierarchy constraints.  To protect against privilege escalations
+through renaming or linking, and for the sack of simplicity, Landlock currently

typo: sack -> sake

Indeed

Quoted 16 lines

Documentation/userspace-api/landlock.rst line 260

Quoted 13 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+Special filesystems
+-------------------
+
+Access to regular files and directories can be restricted by Landlock,
+according to the handled accesses of a ruleset.  However, files that do not
+come from a user-visible filesystem (e.g. pipe, socket), but can still be
+accessed through /proc/self/fd/, cannot currently be restricted.  Likewise,
+some special kernel filesystems such as nsfs, which can be accessed through
+/proc/self/ns/, cannot currently be restricted.  For now, these kind of special
+paths are then always allowed.  Future Landlock evolutions will enable to
+restrict such paths with dedicated ruleset flags.

With this series, can /proc (at the top level) be blocked? (i.e. can a landlock user avoid the weirdness by making /proc/$pid/ unavailable?)

/proc can be blocked, but not /proc/*/ns/* because of disconnected roots. I plan to address this.

Quoted 14 lines

Documentation/userspace-api/landlock.rst line 271

Quoted 11 lines
Documentation/userspace-api/landlock.rst new file +10 -0
+Ruleset layers
+--------------
+
+There is a limit of 64 layers of stacked rulesets.  This can be an issue for a
+task willing to enforce a new ruleset in complement to its 64 inherited
+rulesets.  Once this limit is reached, sys_landlock_restrict_self() returns
+E2BIG.  It is then strongly suggested to carefully build rulesets once in the
+life of a thread, especially for applications able to launch other applications
+that may also want to sandbox themselves (e.g. shells, container managers,
+etc.).

How was this value (64) chosen?

It was first an implementation constraint to limit the memory allocated for each rule, but it could now be increased if needed. The implementation still uses u64 for the sake of simplicity, but we could switch to a bitmap type.

author maintainer
#45 lore raw

Re: [PATCH v30 12/12] landlock: Add user and kernel documentation

Quoted 9 lines · Mickaël Salaün
Quoted 7 lines · Kees Cook
Quoted 3 lines · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

This documentation can be built with the Sphinx framework.

Well, yes. :) Maybe describe what the documentation covers instead here.
Regardless: yay docs! This is great.

What about that?

Add a first document describing userspace API: how to define and enforce a Landlock security policy. This is explained with a simple example. The Landlock system calls are described with their expected behavior and current limitations.

Another document is dedicated to kernel developers, describing guiding principles and some important kernel structures.

This documentation can be built with the Sphinx framework.

Quoted 94 lines
Quoted 20 lines
Quoted 20 lines

[...]

Documentation/userspace-api/landlock.rst new file +18 -0
+Bind mounts and OverlayFS
+-------------------------
+
+Landlock enables to restrict access to file hierarchies, which means that these
+access rights can be propagated with bind mounts (cf.
+:doc:`/filesystems/sharedsubtree`) but not with :doc:`/filesystems/overlayfs`.
+
+A bind mount mirrors a source file hierarchy to a destination.  The destination
+hierarchy is then composed of the exact same files, on which Landlock rules can
+be tied, either via the source or the destination path.  These rules restrict
+access when they are encountered on a path, which means that they can restrict
+access to multiple file hierarchies at the same time, whether these hierarchies
+are the result of bind mounts or not.
+
+An OverlayFS mount point consists of upper and lower layers.  These layers are
+combined in a merge directory, result of the mount point.  This merge hierarchy
+may include files from the upper and lower layers, but modifications performed
+on the merge hierarchy only reflects on the upper layer.  From a Landlock
Quoted 8 lines

Documentation/userspace-api/landlock.rst line 164

Quoted 4 lines
Documentation/userspace-api/landlock.rst new file +4 -0
+policy point of view, each OverlayFS layers and merge hierarchies are
+standalone and contains their own set of files and directories, which is
+different from bind mounts.  A policy restricting an OverlayFS layer will not
+restrict the resulted merged hierarchy, and vice versa.

Can you include some examples about what a user of landlock should do? i.e. what are some examples of unexpected results when trying to write policy that runs on top of overlayfs, etc?

Landlock works well with overlayfs, at least from my point of view. It may be a bit disturbing with bind mount though, but it is the same with other access-controls (e.g. DAC). Landlock users should just think about file hierarchies and create their policies accordingly. A user should not try to adapt a policy according to his/her understanding of overlayfs, but just think about file hierarchies.

Quoted 15 lines

Documentation/userspace-api/landlock.rst line 238

Quoted 13 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+File renaming and linking
+-------------------------
+
+Because Landlock targets unprivileged access controls, it is needed to properly
+handle composition of rules.  Such property also implies rules nesting.
+Properly handling multiple layers of ruleset, each one of them able to restrict
+access to files, also implies to inherit the ruleset restrictions from a parent
+to its hierarchy.  Because files are identified and restricted by their
+hierarchy, moving or linking a file from one directory to another implies to
+propagate the hierarchy constraints.  To protect against privilege escalations
+through renaming or linking, and for the sack of simplicity, Landlock currently

typo: sack -> sake

Indeed

Quoted 16 lines

Documentation/userspace-api/landlock.rst line 260

Quoted 13 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+Special filesystems
+-------------------
+
+Access to regular files and directories can be restricted by Landlock,
+according to the handled accesses of a ruleset.  However, files that do not
+come from a user-visible filesystem (e.g. pipe, socket), but can still be
+accessed through /proc/self/fd/, cannot currently be restricted.  Likewise,
+some special kernel filesystems such as nsfs, which can be accessed through
+/proc/self/ns/, cannot currently be restricted.  For now, these kind of special
+paths are then always allowed.  Future Landlock evolutions will enable to
+restrict such paths with dedicated ruleset flags.

With this series, can /proc (at the top level) be blocked? (i.e. can a landlock user avoid the weirdness by making /proc/$pid/ unavailable?)

/proc can be blocked, but not /proc/*/ns/* because of disconnected roots. I plan to address this.

Quoted 14 lines

Documentation/userspace-api/landlock.rst line 271

Quoted 11 lines
Documentation/userspace-api/landlock.rst new file +10 -0
+Ruleset layers
+--------------
+
+There is a limit of 64 layers of stacked rulesets.  This can be an issue for a
+task willing to enforce a new ruleset in complement to its 64 inherited
+rulesets.  Once this limit is reached, sys_landlock_restrict_self() returns
+E2BIG.  It is then strongly suggested to carefully build rulesets once in the
+life of a thread, especially for applications able to launch other applications
+that may also want to sandbox themselves (e.g. shells, container managers,
+etc.).

How was this value (64) chosen?

It was first an implementation constraint to limit the memory allocated for each rule, but it could now be increased if needed. The implementation still uses u64 for the sake of simplicity, but we could switch to a bitmap type.

author maintainer
#46 lore raw

Re: [PATCH v30 12/12] landlock: Add user and kernel documentation

In reply to Mickaël Salaün
Quoted 4 lines · Mickaël Salaün
Quoted 2 lines · Kees Cook
Quoted 1 line · Mickaël Salaün

From: Mickaël Salaün <[email protected]>

[...]

Quoted 17 lines
Quoted 16 lines

Documentation/userspace-api/landlock.rst line 260

Quoted 13 lines

[...]

Documentation/userspace-api/landlock.rst new file +11 -0
+Special filesystems
+-------------------
+
+Access to regular files and directories can be restricted by Landlock,
+according to the handled accesses of a ruleset.  However, files that do not
+come from a user-visible filesystem (e.g. pipe, socket), but can still be
+accessed through /proc/self/fd/, cannot currently be restricted.  Likewise,
+some special kernel filesystems such as nsfs, which can be accessed through
+/proc/self/ns/, cannot currently be restricted.  For now, these kind of special
+paths are then always allowed.  Future Landlock evolutions will enable to
+restrict such paths with dedicated ruleset flags.

With this series, can /proc (at the top level) be blocked? (i.e. can a landlock user avoid the weirdness by making /proc/$pid/ unavailable?)

Quoted 2 lines

/proc can be blocked, but not /proc/*/ns/* because of disconnected roots. I plan to address this.

It is important to note that access to sensitive /proc files such as ns/* and fd/* are automatically restricted according to domain hierarchies. I'll add this detail to the documentation. :)

maintainer
#47 lore raw
In reply to Mickaël Salaün

I've queued this patchset here:

git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/linux-security.git landlock_lsm

and pulled it into next-testing, which will get it coverage in linux-next.

All going well, I'll aim to push this to Linus in the next merge window. More review and testing during that time will be helpful.

Signature · 2 lines
James Morris
<[email protected]>
author maintainer
#48 lore raw
Quoted 8 lines · James Morris

I've queued this patchset here:

git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/linux-security.git landlock_lsm

and pulled it into next-testing, which will get it coverage in linux-next.

All going well, I'll aim to push this to Linus in the next merge window. More review and testing during that time will be helpful.

Good, thanks! The syzkaller changes are now merged and up-to-date with linux-next:
https://github.com/google/syzkaller/commits/3d01c4de549b4e4bddba6102715c212bbcff2fbb