Skip to contentSkip to conversation

Landlock LSM

PATCH Superseded Mickaël Salaün 4 participants 37 messages Oct 27, 2020 – Nov 16, 2020

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

v22 of 34 Superseded Latest is v34 →

lore
Share & tools
lore

Mickaël Salaün

author maintainer
#0 lore raw

v22 cover Landlock LSM

Hi,

Can you please consider to merge this into the tree?

This new patch series improves documentation, cleans up comments, renames ARCH_EPHEMERAL_STATES to ARCH_EPHEMERAL_INODES and removes LANDLOCK_ACCESS_FS_CHROOT.

The SLOC count is 1183 for security/landlock/ and 1657 for tools/testing/selftest/landlock/ . Test coverage for security/landlock/ is 95.2% of lines. The code not covered only deals with internal kernel errors (e.g. memory allocation) and race conditions.

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

This series can be applied on top of v5.10-rc1 . This can be tested with CONFIG_SECURITY_LANDLOCK and CONFIG_SAMPLE_LANDLOCK. This patch series can be found in a Git repository here:
https://github.com/landlock-lsm/linux/commits/landlock-v22
I would really appreciate constructive comments on this patch series.

# 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].

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

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[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      |  259 +++
 MAINTAINERS                                   |   13 +
 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                     |    3 +
 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                     |   15 +
 samples/landlock/sandboxer.c                  |  219 +++
 security/Kconfig                              |   11 +-
 security/Makefile                             |    2 +
 security/landlock/Kconfig                     |   19 +
 security/landlock/Makefile                    |    4 +
 security/landlock/common.h                    |   20 +
 security/landlock/cred.c                      |   46 +
 security/landlock/cred.h                      |   58 +
 security/landlock/fs.c                        |  604 ++++++
 security/landlock/fs.h                        |   60 +
 security/landlock/object.c                    |   66 +
 security/landlock/object.h                    |   91 +
 security/landlock/ptrace.c                    |  120 ++
 security/landlock/ptrace.h                    |   14 +
 security/landlock/ruleset.c                   |  350 ++++
 security/landlock/ruleset.h                   |  157 ++
 security/landlock/setup.c                     |   40 +
 security/landlock/setup.h                     |   18 +
 security/landlock/syscall.c                   |  427 +++++
 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  |  117 ++
 tools/testing/selftests/landlock/common.h     |  113 ++
 tools/testing/selftests/landlock/config       |    5 +
 tools/testing/selftests/landlock/fs_test.c    | 1675 +++++++++++++++++
 .../testing/selftests/landlock/ptrace_test.c  |  307 +++
 tools/testing/selftests/landlock/true.c       |    5 +
 71 files changed, 5255 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/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/syscall.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: 3650b228f83adda7e5ee532e2b90429c03f7b9ec

Signature · 1 line
2.28.0
author maintainer
#1 lore raw

PATCH v22 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.

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

---

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  | 19 ++++++++
 security/landlock/Makefile |  3 ++
 security/landlock/object.c | 66 +++++++++++++++++++++++++++
 security/landlock/object.h | 91 ++++++++++++++++++++++++++++++++++++++
 7 files changed, 192 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 e73636b75f29..06c77076214a 100644
@@ -9846,6 +9846,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..c688f4907a1b 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 +19 -0
new file mode 100644
index 000000000000..48dd213ca5eb
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+config SECURITY_LANDLOCK
+	bool "Landlock support"
+	depends on SECURITY
+	select SECURITY_PATH
+	help
+	  Landlock is a safe sandboxing mechanism which enables processes to
+	  restrict themselves (and their future children) by gradually
+	  enforcing tailored access control policies.  A 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 thanks to dedicated system
+	  calls: landlock_create_ruleset(), landlock_add_rule(), and
+	  landlock_enforce_ruleset_current().
+
+	  See Documentation/userspace-api/landlock.rst for further information.
+
+	  If you are unsure how to answer this question, answer N.
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 +66 -0

66 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.28.0
Reviewed-by on v22 1/12
#2 lore raw

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

Quoted 19 lines · Mickaël Salaün

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.

Quoted 7 lines

A following commit uses this generic object management for inodes.

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

except for some minor nits:

[...]

Quoted 1 line
security/landlock/object.c +0 -0

[...]

security/landlock/object.c line 44

Quoted 4 lines
security/landlock/object.c +4 -0
+void landlock_put_object(struct landlock_object *const object)
+{
+       /*
+        * The call to @object->underops->release(object) might sleep e.g.,

s/ e.g.,/, e.g./

Quoted 5 lines
security/landlock/object.c +5 -0
+        * because of iput().
+        */
+       might_sleep();
+       if (!object)
+               return;

[...]

Quoted 2 lines
security/landlock/object.c +1 -0
+}
security/landlock/object.h +0 -0

[...]

security/landlock/object.h line 50

Quoted 12 lines
security/landlock/object.h +12 -0
+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: Guards against concurrent modifications.  This lock must be

s/must be/must be held/ ?

Quoted 6 lines
security/landlock/object.h +6 -0
+        * 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;

[...]

security/landlock/object.h line 81

Quoted 5 lines
security/landlock/object.h +5 -0
+};
+
+struct landlock_object *landlock_create_object(
+               const struct landlock_object_underops *const underops,
+               void *const underojb);

nit: "underobj"

author maintainer
#3 lore raw

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

Quoted 22 lines · Jann Horn
Quoted 21 lines · Mickaël Salaün

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.

Quoted 7 lines
Quoted 5 lines
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

Thanks for the review.

Quoted 4 lines

except for some minor nits:

[...]

Quoted 8 lines
Quoted 1 line
security/landlock/object.c +0 -0

[...]

security/landlock/object.c line 44

Quoted 4 lines
security/landlock/object.c +4 -0
+void landlock_put_object(struct landlock_object *const object)
+{
+       /*
+        * The call to @object->underops->release(object) might sleep e.g.,

s/ e.g.,/, e.g./

I indeed prefer the comma preceding the "e.g.", but it seems that there is a difference between UK english and US english:
https://english.stackexchange.com/questions/16172/should-i-always-use-a-comma-after-e-g-or-i-e
Looking at the kernel documentation makes it clear:

$ git grep -F 'e.g. ' | wc -l
1179
$ git grep -F 'e.g., ' | wc -l
160

I'll apply your fix in the whole patch series.

Quoted 23 lines
Quoted 6 lines
security/landlock/object.c +5 -0
+        * because of iput().
+        */
+       might_sleep();
+       if (!object)
+               return;

[...]

Quoted 2 lines
security/landlock/object.c +1 -0
+}
security/landlock/object.h +0 -0

[...]

security/landlock/object.h line 50

Quoted 12 lines
security/landlock/object.h +12 -0
+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: Guards against concurrent modifications.  This lock must be
Quoted 1 line

s/must be/must be held/ ?

Right.

Quoted 7 lines

security/landlock/object.h line 56

Quoted 7 lines
security/landlock/object.h +6 -0
+        * 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;
Quoted 9 lines

[...]

security/landlock/object.h line 81

Quoted 5 lines
security/landlock/object.h +5 -0
+};
+
+struct landlock_object *landlock_create_object(
+               const struct landlock_object_underops *const underops,
+               void *const underojb);

nit: "underobj"

Good catch!

#4 lore raw

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

Quoted 6 lines · Mickaël Salaün
Quoted 5 lines · Jann Horn
Quoted 4 lines · Mickaël Salaün

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).

[...]

Quoted 13 lines
Quoted 8 lines
Quoted 1 line
security/landlock/object.c +0 -0

[...]

security/landlock/object.c line 44

Quoted 4 lines
security/landlock/object.c +4 -0
+void landlock_put_object(struct landlock_object *const object)
+{
+       /*
+        * The call to @object->underops->release(object) might sleep e.g.,

s/ e.g.,/, e.g./

I indeed prefer the comma preceding the "e.g.", but it seems that there is a difference between UK english and US english:
https://english.stackexchange.com/questions/16172/should-i-always-use-a-comma-after-e-g-or-i-e
Looking at the kernel documentation makes it clear:

Quoted 6 lines
$ git grep -F 'e.g. ' | wc -l
1179
$ git grep -F 'e.g., ' | wc -l
160

I'll apply your fix in the whole patch series.

Ooh, sorry. I didn't realize that that's valid in UK English...

#5 lore raw

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

In reply to Mickaël Salaün

Hi!

Quoted 13 lines

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.

security/landlock/Kconfig new file +3 -0
+config SECURITY_LANDLOCK
+	bool "Landlock support"
+	depends on SECURITY

security/landlock/Kconfig line 15

Quoted 10 lines
security/landlock/Kconfig new file +10 -0
+	select SECURITY_PATH
+	help
+	  Landlock is a safe sandboxing mechanism which enables processes to
+	  restrict themselves (and their future children) by gradually
+	  enforcing tailored access control policies.  A 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 thanks to dedicated system
+	  calls: landlock_create_ruleset(), landlock_add_rule(), and
+	  landlock_enforce_ruleset_current().

How does it interact with setuid binaries? Being able to exec passwd in a sandbox sounds like ... fun way to get root? :-).

Best regards,
Pavel

Signature · 1 line
http://www.livejournal.com/~pavelmachek
author maintainer
#6 lore raw

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

Quoted 12 lines · Pavel Machek

Hi!

Quoted 8 lines

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.

Quoted 16 lines

security/landlock/Kconfig line 15

Quoted 13 lines
security/landlock/Kconfig new file +13 -0
+config SECURITY_LANDLOCK
+	bool "Landlock support"
+	depends on SECURITY
+	select SECURITY_PATH
+	help
+	  Landlock is a safe sandboxing mechanism which enables processes to
+	  restrict themselves (and their future children) by gradually
+	  enforcing tailored access control policies.  A 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 thanks to dedicated system
+	  calls: landlock_create_ruleset(), landlock_add_rule(), and
+	  landlock_enforce_ruleset_current().

How does it interact with setuid binaries? Being able to exec passwd in a sandbox sounds like ... fun way to get root? :-).

It works like seccomp: if you run with CAP_SYS_ADMIN in the current namespace, then SUID binaries may be allowed, otherwise if you use PR_SET_NO_NEW_PRIVS, then executing a SUID binary is denied.

The 24th version is here:
https://lore.kernel.org/lkml/[email protected]/

Quoted 5 lines

Best regards,
Pavel

author maintainer
#7 lore raw

PATCH v22 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.

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

---

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/ruleset.c | 350 ++++++++++++++++++++++++++++++++++++
 security/landlock/ruleset.h | 157 ++++++++++++++++
 3 files changed, 508 insertions(+), 1 deletion(-)
 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/ruleset.c new file +350 -0

350 lines not on this page · raw message

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

157 lines not on this page · raw message

Signature · 1 line
2.28.0
Reviewed-by on v22 2/12
#8 lore raw

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

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 5 lines
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

with some nits:

[...]

security/landlock/ruleset.c line 35

Quoted 11 lines
security/landlock/ruleset.c new file +11 -0
+static struct landlock_ruleset *create_ruleset(void)
+{
+       struct landlock_ruleset *new_ruleset;
+
+       new_ruleset = kzalloc(sizeof(*new_ruleset), GFP_KERNEL_ACCOUNT);
+       if (!new_ruleset)
+               return ERR_PTR(-ENOMEM);
+       refcount_set(&new_ruleset->usage, 1);
+       mutex_init(&new_ruleset->lock);
+       /*
+        * root = RB_ROOT

This should probably be done explicitly, even though it's currently a no-op, in case the implementation of RB_ROOT changes in the future.

Quoted 7 lines
security/landlock/ruleset.c new file +7 -0
+        * hierarchy = NULL
+        * nb_rules = 0
+        * nb_layers = 0
+        * fs_access_mask = 0
+        */
+       return new_ruleset;
+}

[...]

Quoted 5 lines

+/**
+ * landlock_insert_rule - Insert a rule in a ruleset
+ *
+ * @ruleset: The ruleset to be updated.
+ * @rule: Read-only payload to be inserted (not own by this function).

s/own/owned/

Quoted 11 lines

+ * @is_merge: If true, intersects access rights and updates the rule's layers
+ * (e.g. merge two rulesets), else do a union of access rights and
+ * keep the rule's layers (e.g. extend a ruleset)
+ *
+ * Assumptions:
+ *
+ * - An inserted rule cannot be removed.
+ * - The underlying kernel object must be held by the caller.
+ */

security/landlock/ruleset.c new file +2 -0
+int landlock_insert_rule(struct landlock_ruleset *const ruleset,
+               struct landlock_rule *const rule, const bool is_merge)

[...]

Quoted 5 lines
security/landlock/ruleset.c new file +5 -0
+static int merge_ruleset(struct landlock_ruleset *const dst,
+               struct landlock_ruleset *const src)
+{
+       struct landlock_rule *walker_rule, *next_rule;
+       int err = 0;

security/landlock/ruleset.c line 177

Quoted 10 lines
security/landlock/ruleset.c new file +10 -0
+
+       might_sleep();
+       if (!src)
+               return 0;
+       /* Only merge into a domain. */
+       if (WARN_ON_ONCE(!dst || !dst->hierarchy))
+               return -EFAULT;
+
+       mutex_lock(&dst->lock);
+       mutex_lock_nested(&src->lock, 1);

Maybe add a comment like this above these two lines? "Ruleset locks are ordered by time of ruleset creation; dst is newer than src."

Also, maybe s/1/SINGLE_DEPTH_NESTING/.

Quoted 24 lines
security/landlock/ruleset.c new file +24 -0
+       /*
+        * Makes a new layer, but only increments the number of layers after
+        * the rules are inserted.
+        */
+       if (dst->nb_layers == sizeof(walker_rule->layers) * BITS_PER_BYTE) {
+               err = -E2BIG;
+               goto out_unlock;
+       }
+       dst->fs_access_mask |= src->fs_access_mask;
+
+       /* Merges the @src tree. */
+       rbtree_postorder_for_each_entry_safe(walker_rule, next_rule,
+                       &src->root, node) {
+               err = landlock_insert_rule(dst, walker_rule, true);
+               if (err)
+                       goto out_unlock;
+       }
+       dst->nb_layers++;
+
+out_unlock:
+       mutex_unlock(&src->lock);
+       mutex_unlock(&dst->lock);
+       return err;
+}

[...]

Quoted 1 line
security/landlock/ruleset.h +0 -0

[...]

security/landlock/ruleset.h line 33

Quoted 3 lines
security/landlock/ruleset.h +3 -0
+struct landlock_rule {
+       /**
+        * @node: Node in the red-black tree.

s/the red-black tree/the ruleset's red-black tree/

security/landlock/ruleset.h line 39

Quoted 6 lines
security/landlock/ruleset.h +6 -0
+        */
+       struct rb_node node;
+       /**
+        * @object: Pointer to identify a kernel object (e.g. an inode).  This
+        * is used as a key for this ruleset element.  This pointer is set once
+        * and never modified.  It always point to an allocated object because

s/point/points/

Quoted 1 line

+ * each rule increment the refcount of there object.

s/increment/increments/
s/there/its/

Quoted 12 lines
security/landlock/ruleset.h +12 -0
+        */
+       struct landlock_object *object;
+       /**
+        * @layers: Bitfield to identify the layers which resulted to @access
+        * from different consecutive intersections.
+        */
+       u64 layers;
+       /**
+        * @access: Bitfield of allowed actions on the kernel object.  They are
+        * relative to the object type (e.g. %LANDLOCK_ACTION_FS_READ).  This
+        * may be the result of the merged access rights (boolean AND) from
+        * multiple layers referring to the same object.

security/landlock/ruleset.h line 62

Quoted 10 lines
security/landlock/ruleset.h +10 -0
+        */
+       u32 access;
+};
+
+/**
+ * struct landlock_hierarchy - Node in a ruleset hierarchy
+ */
+struct landlock_hierarchy {
+       /**
+        * @parent: Pointer to the parent node, or NULL if it is a root Lanlock

nit: Landlock

Quoted 4 lines
security/landlock/ruleset.h +4 -0
+        * domain.
+        */
+       struct landlock_hierarchy *parent;
+       /**

security/landlock/ruleset.h line 76

Quoted 10 lines
security/landlock/ruleset.h +10 -0
+        * @usage: Number of potential children domains plus their parent
+        * domain.
+        */
+       refcount_t usage;
+};
+
+/**
+ * struct landlock_ruleset - Landlock ruleset
+ *
+ * This data structure must contains unique entries, be updatable, and quick to

s/contains/contain/

security/landlock/ruleset.h line 82

Quoted 6 lines

+ * match an object.
+ */

security/landlock/ruleset.h +4 -0
+struct landlock_ruleset {
+       /**
+        * @root: Root of a red-black tree containing &struct landlock_rule
+        * nodes.

Maybe add: "Once the ruleset is installed on a process, this tree is immutable until @usage reaches zero."

Quoted 26 lines
security/landlock/ruleset.h +26 -0
+        */
+       struct rb_root root;
+       /**
+        * @hierarchy: Enables hierarchy identification even when a parent
+        * domain vanishes.  This is needed for the ptrace protection.
+        */
+       struct landlock_hierarchy *hierarchy;
+       union {
+               /**
+                * @work_free: Enables to free a ruleset within a lockless
+                * section.  This is only used by
+                * landlock_put_ruleset_deferred() when @usage reaches zero.
+                * The fields @lock, @usage, @nb_layers, @nb_rules and
+                * @fs_access_mask are then unused.
+                */
+               struct work_struct work_free;
+               struct {
+                       /**
+                        * @lock: Guards against concurrent modifications of
+                        * @root, if @usage is greater than zero.
+                        */
+                       struct mutex lock;
+                       /**
+                        * @usage: Number of processes (i.e. domains) or file
+                        * descriptors referencing this ruleset.
+                        */

security/landlock/ruleset.h line 118

Quoted 10 lines
security/landlock/ruleset.h +10 -0
+                       refcount_t usage;
+                       /**
+                        * @nb_rules: Number of non-overlapping (i.e. not for
+                        * the same object) rules in this ruleset.
+                        */
+                       u32 nb_rules;
+                       /**
+                        * @nb_layers: Number of layers which are used in this
+                        * ruleset.  This enables to check that all the layers
+                        * allow an access request.  A value of 0 identify a

s/identify/identifies/

Quoted 15 lines
security/landlock/ruleset.h +15 -0
+                        * non-merged ruleset (i.e. not a domain).
+                        */
+                       u32 nb_layers;
+                       /**
+                        * @fs_access_mask: Contains the subset of filesystem
+                        * actions which are restricted by a ruleset.  This is
+                        * used when merging rulesets and for user space
+                        * backward compatibility (i.e. future-proof).  Set
+                        * once and never changed for the lifetime of the
+                        * ruleset.
+                        */
+                       u32 fs_access_mask;
+               };
+       };
+};
author maintainer
#9 lore raw

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

Quoted 15 lines · Jann Horn
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 7 lines
Quoted 5 lines
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

Thanks.

Quoted 4 lines

with some nits:

[...]

Quoted 14 lines

security/landlock/ruleset.c line 35

Quoted 11 lines
security/landlock/ruleset.c new file +11 -0
+static struct landlock_ruleset *create_ruleset(void)
+{
+       struct landlock_ruleset *new_ruleset;
+
+       new_ruleset = kzalloc(sizeof(*new_ruleset), GFP_KERNEL_ACCOUNT);
+       if (!new_ruleset)
+               return ERR_PTR(-ENOMEM);
+       refcount_set(&new_ruleset->usage, 1);
+       mutex_init(&new_ruleset->lock);
+       /*
+        * root = RB_ROOT

This should probably be done explicitly, even though it's currently a no-op, in case the implementation of RB_ROOT changes in the future.

OK, I'll do it for RB_ROOT.

Quoted 8 lines

security/landlock/ruleset.c line 42

Quoted 8 lines
security/landlock/ruleset.c new file +7 -0
+        * hierarchy = NULL
+        * nb_rules = 0
+        * nb_layers = 0
+        * fs_access_mask = 0
+        */
+       return new_ruleset;
+}
Quoted 8 lines

[...]

Quoted 5 lines

+/**
+ * landlock_insert_rule - Insert a rule in a ruleset
+ *
+ * @ruleset: The ruleset to be updated.
+ * @rule: Read-only payload to be inserted (not own by this function).

s/own/owned/

OK

Quoted 23 lines
Quoted 12 lines

+ * @is_merge: If true, intersects access rights and updates the rule's layers
+ * (e.g. merge two rulesets), else do a union of access rights and
+ * keep the rule's layers (e.g. extend a ruleset)
+ *
+ * Assumptions:
+ *
+ * - An inserted rule cannot be removed.
+ * - The underlying kernel object must be held by the caller.
+ */

security/landlock/ruleset.c new file +2 -0
+int landlock_insert_rule(struct landlock_ruleset *const ruleset,
+               struct landlock_rule *const rule, const bool is_merge)

[...]

Quoted 10 lines
security/landlock/ruleset.c new file +10 -0
+static int merge_ruleset(struct landlock_ruleset *const dst,
+               struct landlock_ruleset *const src)
+{
+       struct landlock_rule *walker_rule, *next_rule;
+       int err = 0;
+
+       might_sleep();
+       if (!src)
+               return 0;
+       /* Only merge into a domain. */
Quoted 8 lines

security/landlock/ruleset.c line 177

Quoted 5 lines
security/landlock/ruleset.c new file +5 -0
+       if (WARN_ON_ONCE(!dst || !dst->hierarchy))
+               return -EFAULT;
+
+       mutex_lock(&dst->lock);
+       mutex_lock_nested(&src->lock, 1);

Maybe add a comment like this above these two lines? "Ruleset locks are ordered by time of ruleset creation; dst is newer than src."

OK

Quoted 2 lines

Also, maybe s/1/SINGLE_DEPTH_NESTING/.

OK

Quoted 27 lines
Quoted 26 lines
security/landlock/ruleset.c new file +24 -0
+       /*
+        * Makes a new layer, but only increments the number of layers after
+        * the rules are inserted.
+        */
+       if (dst->nb_layers == sizeof(walker_rule->layers) * BITS_PER_BYTE) {
+               err = -E2BIG;
+               goto out_unlock;
+       }
+       dst->fs_access_mask |= src->fs_access_mask;
+
+       /* Merges the @src tree. */
+       rbtree_postorder_for_each_entry_safe(walker_rule, next_rule,
+                       &src->root, node) {
+               err = landlock_insert_rule(dst, walker_rule, true);
+               if (err)
+                       goto out_unlock;
+       }
+       dst->nb_layers++;
+
+out_unlock:
+       mutex_unlock(&src->lock);
+       mutex_unlock(&dst->lock);
+       return err;
+}

[...]

Quoted 7 lines
Quoted 1 line
security/landlock/ruleset.h +0 -0

[...]

security/landlock/ruleset.h line 33

Quoted 3 lines
security/landlock/ruleset.h +3 -0
+struct landlock_rule {
+       /**
+        * @node: Node in the red-black tree.

s/the red-black tree/the ruleset's red-black tree/

OK

Quoted 9 lines

security/landlock/ruleset.h line 39

Quoted 7 lines
security/landlock/ruleset.h +6 -0
+        */
+       struct rb_node node;
+       /**
+        * @object: Pointer to identify a kernel object (e.g. an inode).  This
+        * is used as a key for this ruleset element.  This pointer is set once
+        * and never modified.  It always point to an allocated object because

s/point/points/

OK

Quoted 5 lines
Quoted 2 lines

+ * each rule increment the refcount of there object.

s/increment/increments/
s/there/its/

OK

Quoted 17 lines
Quoted 17 lines
security/landlock/ruleset.h +16 -0
+        */
+       struct landlock_object *object;
+       /**
+        * @layers: Bitfield to identify the layers which resulted to @access
+        * from different consecutive intersections.
+        */
+       u64 layers;
+       /**
+        * @access: Bitfield of allowed actions on the kernel object.  They are
+        * relative to the object type (e.g. %LANDLOCK_ACTION_FS_READ).  This
+        * may be the result of the merged access rights (boolean AND) from
+        * multiple layers referring to the same object.
+        */
+       u32 access;
+};
+
Quoted 8 lines

security/landlock/ruleset.h line 62

Quoted 6 lines
security/landlock/ruleset.h +6 -0
+/**
+ * struct landlock_hierarchy - Node in a ruleset hierarchy
+ */
+struct landlock_hierarchy {
+       /**
+        * @parent: Pointer to the parent node, or NULL if it is a root Lanlock

nit: Landlock

Thanks :)

Quoted 17 lines
Quoted 5 lines
security/landlock/ruleset.h +4 -0
+        * domain.
+        */
+       struct landlock_hierarchy *parent;
+       /**

security/landlock/ruleset.h line 76

Quoted 10 lines
security/landlock/ruleset.h +10 -0
+        * @usage: Number of potential children domains plus their parent
+        * domain.
+        */
+       refcount_t usage;
+};
+
+/**
+ * struct landlock_ruleset - Landlock ruleset
+ *
+ * This data structure must contains unique entries, be updatable, and quick to

s/contains/contain/

OK

Quoted 10 lines

security/landlock/ruleset.h line 82

Quoted 7 lines

+ * match an object.
+ */

security/landlock/ruleset.h +4 -0
+struct landlock_ruleset {
+       /**
+        * @root: Root of a red-black tree containing &struct landlock_rule
+        * nodes.

Maybe add: "Once the ruleset is installed on a process, this tree is immutable until @usage reaches zero."

Right.

Quoted 38 lines
Quoted 27 lines
security/landlock/ruleset.h +26 -0
+        */
+       struct rb_root root;
+       /**
+        * @hierarchy: Enables hierarchy identification even when a parent
+        * domain vanishes.  This is needed for the ptrace protection.
+        */
+       struct landlock_hierarchy *hierarchy;
+       union {
+               /**
+                * @work_free: Enables to free a ruleset within a lockless
+                * section.  This is only used by
+                * landlock_put_ruleset_deferred() when @usage reaches zero.
+                * The fields @lock, @usage, @nb_layers, @nb_rules and
+                * @fs_access_mask are then unused.
+                */
+               struct work_struct work_free;
+               struct {
+                       /**
+                        * @lock: Guards against concurrent modifications of
+                        * @root, if @usage is greater than zero.
+                        */
+                       struct mutex lock;
+                       /**
+                        * @usage: Number of processes (i.e. domains) or file
+                        * descriptors referencing this ruleset.
+                        */

security/landlock/ruleset.h line 118

Quoted 10 lines
security/landlock/ruleset.h +10 -0
+                       refcount_t usage;
+                       /**
+                        * @nb_rules: Number of non-overlapping (i.e. not for
+                        * the same object) rules in this ruleset.
+                        */
+                       u32 nb_rules;
+                       /**
+                        * @nb_layers: Number of layers which are used in this
+                        * ruleset.  This enables to check that all the layers
+                        * allow an access request.  A value of 0 identify a
Quoted 1 line

s/identify/identifies/

OK

Quoted 18 lines
Quoted 18 lines
security/landlock/ruleset.h +15 -0
+                        * non-merged ruleset (i.e. not a domain).
+                        */
+                       u32 nb_layers;
+                       /**
+                        * @fs_access_mask: Contains the subset of filesystem
+                        * actions which are restricted by a ruleset.  This is
+                        * used when merging rulesets and for user space
+                        * backward compatibility (i.e. future-proof).  Set
+                        * once and never changed for the lifetime of the
+                        * ruleset.
+                        */
+                       u32 fs_access_mask;
+               };
+       };
+};
author maintainer
#10 lore raw

PATCH v22 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.

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

---

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..39ee1766f175
@@ -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_hooks_cred();
+	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.28.0
Reviewed-by on v22 3/12
#11 lore raw

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

Quoted 11 lines · Mickaël Salaün

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.

Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>
author maintainer
#12 lore raw

PATCH v22 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).

Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[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..6740c6a723de
@@ -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_hooks_ptrace(void);
+
+#endif /* _SECURITY_LANDLOCK_PTRACE_H */
security/landlock/setup.c +2 -0
index 39ee1766f175..5e7540fdeefa 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_hooks_cred();
+	landlock_add_hooks_ptrace();
 	pr_info("Up and running.\n");
 	return 0;
 }
Signature · 1 line
2.28.0
Reviewed-by on v22 4/12
#13 lore raw

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

Quoted 12 lines · Mickaël Salaün

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 5 lines
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>
author maintainer
#14 lore raw

PATCH v22 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 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 c503f7ab8afb..ff0f03a45c56 100644
@@ -1563,6 +1563,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 330b7b6d44e0..dcebd2b95ca7 100644
@@ -189,4 +189,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 9704c8a32303..1b2dae7c0773 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 5c90b9fa4d40..e9d264a9df91 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;
@@ -1398,7 +1381,7 @@ static int smack_inode_removexattr(struct dentry *dentry, const char *name)
 	 */
 	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)
@@ -1668,7 +1651,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;
@@ -3283,7 +3266,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.
@@ -4697,6 +4680,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 = {
@@ -4708,7 +4692,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.28.0
maintainer
#15 lore raw

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

Quoted 8 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.

Quoted 5 lines

It would be good to see review from JJ here.

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

PATCH v22 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.

Cc Al Viro <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[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     | 2 ++
 include/linux/security.h      | 4 ++++
 security/security.c           | 5 +++++
 5 files changed, 13 insertions(+)
fs/super.c +1 -0
index a51c2083cd6b..fea9475189f7 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 32a940117e7a..1ba9b4dfecb3 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 +2 -0
index ff0f03a45c56..dbfcec05a176 100644
@@ -108,6 +108,8 @@
  *	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_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 bc2725491560..a4603b62d444 100644
@@ -287,6 +287,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);
@@ -619,6 +620,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 4ffd6c3af9d7..4563e7a79216 100644
@@ -899,6 +899,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.28.0
maintainer
#17 lore raw

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

Quoted 10 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).

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.

Quoted 6 lines
Cc Al Viro <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

Al, Kees, JJ et al, any objections?

Signature · 2 lines
James Morris
<[email protected]>
Reviewed-by on v22 6/12
#18 lore raw

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

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

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.

Quoted 6 lines
Cc Al Viro <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>
author maintainer
#19 lore raw

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

In reply to Mickaël Salaün

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

Thanks to the Landlock objects and ruleset, it is possible to identify 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 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        | 604 ++++++++++++++++++++++++++++++++++
 security/landlock/fs.h        |  60 ++++
 security/landlock/setup.c     |   7 +
 security/landlock/setup.h     |   2 +
 10 files changed, 759 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 06c77076214a..43021f8c95bb 100644
@@ -9852,6 +9852,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 56b6ccc0e32d..7da605bd966d 100644
@@ -884,6 +884,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 4b799fad8b48..082d0207a7be 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 48dd213ca5eb..cbf88bb7fd97 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 safe sandboxing mechanism which enables processes to
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 +604 -0

604 lines not on this page · raw message

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

60 lines not on this page · raw message

security/landlock/setup.c +7 -0
index 5e7540fdeefa..722cbea82324 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_hooks_cred();
 	landlock_add_hooks_ptrace();
+	landlock_add_hooks_fs();
+	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.28.0
#20 lore raw

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

Quoted 24 lines · Mickaël Salaün

Thanks to the Landlock objects and ruleset, it is possible to identify 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.

[...]

Quoted 1 line
include/uapi/linux/landlock.h +0 -0

[...]

Quoted 10 lines

+/**
+ * DOC: fs_access
+ *
+ * A set of actions on kernel objects may be defined by an attribute (e.g.
+ * &struct landlock_path_beneath_attr) including a bitmask of access.
+ *
+ * Filesystem flags
+ * ~~~~~~~~~~~~~~~~
+ *
+ * These flags enable to restrict a sandbox process to a set of actions on

s/sandbox/sandboxed/

[...]

Quoted 1 line
security/landlock/fs.c +0 -0

[...]

Quoted 3 lines
security/landlock/fs.c +3 -0
+static const struct landlock_object_underops landlock_fs_underops = {
+       .release = release_inode
+};

[...]

security/landlock/fs.c line 171

Quoted 12 lines
security/landlock/fs.c +12 -0
+/* Access-control management */
+
+static bool check_access_path_continue(
+               const struct landlock_ruleset *const domain,
+               const struct path *const path, const u32 access_request,
+               bool *const allow, u64 *const layer_mask)
+{
+       const struct landlock_rule *rule;
+       const struct inode *inode;
+       bool next = true;
+
+       prefetch(path->dentry->d_parent);

IIRC software prefetch() turned out to only rarely actually have a performance benefit, and they often actually make things worse; see e.g. <https://lwn.net/Articles/444336/>. Unless you have strong evidence that this actually brings a performance benefit, I'd probably get rid of this.

Quoted 50 lines
security/landlock/fs.c +50 -0
+       if (d_is_negative(path->dentry))
+               /* Continues to walk while there is no mapped inode. */
+               return true;
+       inode = d_backing_inode(path->dentry);
+       rcu_read_lock();
+       rule = landlock_find_rule(domain,
+                       rcu_dereference(landlock_inode(inode)->object));
+       rcu_read_unlock();
+
+       /* Checks for matching layers. */
+       if (rule && (rule->layers | *layer_mask)) {
+               *allow = (rule->access & access_request) == access_request;
+               if (*allow) {
+                       *layer_mask &= ~rule->layers;
+                       /* Stops when a rule from each layer granted access. */
+                       next = !!*layer_mask;
+               } else {
+                       next = false;
+               }
+       }
+       return next;
+}
+
+static int check_access_path(const struct landlock_ruleset *const domain,
+               const struct path *const path, u32 access_request)
+{
+       bool allow = false;
+       struct path walker_path;
+       u64 layer_mask;
+
+       if (WARN_ON_ONCE(!domain || !path))
+               return 0;
+       /*
+        * Allows access to pseudo filesystems that will never be mountable
+        * (e.g. sockfs, pipefs), but can still be reachable through
+        * /proc/self/fd .
+        */
+       if ((path->dentry->d_sb->s_flags & SB_NOUSER) ||
+                       (d_is_positive(path->dentry) &&
+                        unlikely(IS_PRIVATE(d_backing_inode(path->dentry)))))
+               return 0;
+       if (WARN_ON_ONCE(domain->nb_layers < 1))
+               return -EACCES;
+
+       layer_mask = GENMASK_ULL(domain->nb_layers - 1, 0);
+       /*
+        * An access request which is not handled by the domain should be
+        * allowed.
+        */
+       access_request &= domain->fs_access_mask;

security/landlock/fs.c line 231

Quoted 10 lines
security/landlock/fs.c +10 -0
+       if (access_request == 0)
+               return 0;
+       walker_path = *path;
+       path_get(&walker_path);
+       /*
+        * We need to walk through all the hierarchy to not miss any relevant
+        * restriction.
+        */
+       while (check_access_path_continue(domain, &walker_path, access_request,
+                               &allow, &layer_mask)) {

The logic in this code might be clearer if check_access_path_continue() just returns whether the rule permitted the access. Then it'd look like:

bool allow = false;
[...]
while (check_access_path_continue(domain, &walker_path, access_request, &layer_mask)) {

  if (layer_mask == 0) {
    allow = true;
    break;

}
[...]
}

I think that would make it clearer under which conditions we can end up returning "true" from check_access_path().

(The current code also looks correct to me, I just think it'd be clearer this way. If you disagree, you can keep it as-is.)

Quoted 36 lines
security/landlock/fs.c +36 -0
+               struct dentry *parent_dentry;
+
+jump_up:
+               /*
+                * Does not work with orphaned/private mounts like overlayfs
+                * layers for now (cf. ovl_path_real() and ovl_path_open()).
+                */
+               if (walker_path.dentry == walker_path.mnt->mnt_root) {
+                       if (follow_up(&walker_path)) {
+                               /* Ignores hidden mount points. */
+                               goto jump_up;
+                       } else {
+                               /*
+                                * Stops at the real root.  Denies access
+                                * because not all layers have granted access.
+                                */
+                               allow = false;
+                               break;
+                       }
+               }
+               if (unlikely(IS_ROOT(walker_path.dentry))) {
+                       /*
+                        * Stops at disconnected root directories.  Only allows
+                        * access to internal filesystems (e.g. nsfs which is
+                        * reachable through /proc/self/ns).
+                        */
+                       allow = !!(walker_path.mnt->mnt_flags & MNT_INTERNAL);
+                       break;
+               }
+               parent_dentry = dget_parent(walker_path.dentry);
+               dput(walker_path.dentry);
+               walker_path.dentry = parent_dentry;
+       }
+       path_put(&walker_path);
+       return allow ? 0 : -EACCES;
+}

[...]

Quoted 4 lines
security/landlock/fs.c +4 -0
+static inline u32 get_file_access(const struct file *const file)
+{
+       u32 access = 0;
+

security/landlock/fs.c line 557

Quoted 10 lines
security/landlock/fs.c +10 -0
+       if (file->f_mode & FMODE_READ) {
+               /* A directory can only be opened in read mode. */
+               if (S_ISDIR(file_inode(file)->i_mode))
+                       return LANDLOCK_ACCESS_FS_READ_DIR;
+               access = LANDLOCK_ACCESS_FS_READ_FILE;
+       }
+       /*
+        * A LANDLOCK_ACCESS_FS_APPEND could be added but we also need to check
+        * fcntl(2).
+        */

Once https://lore.kernel.org/linux-api/[email protected]/
lands, pwritev2() with RWF_NOAPPEND will also be problematic for classifying "write" vs "append"; you may want to include that in the comment. (Or delete the comment.)

Quoted 7 lines
security/landlock/fs.c +7 -0
+       if (file->f_mode & FMODE_WRITE)
+               access |= LANDLOCK_ACCESS_FS_WRITE_FILE;
+       /* __FMODE_EXEC is indeed part of f_flags, not f_mode. */
+       if (file->f_flags & __FMODE_EXEC)
+               access |= LANDLOCK_ACCESS_FS_EXECUTE;
+       return access;
+}

[...]

author maintainer
#21 lore raw

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

Quoted 39 lines · Jann Horn
Quoted 24 lines · Mickaël Salaün

Thanks to the Landlock objects and ruleset, it is possible to identify 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.

[...]

Quoted 1 line
include/uapi/linux/landlock.h +0 -0

[...]

Quoted 10 lines

+/**
+ * DOC: fs_access
+ *
+ * A set of actions on kernel objects may be defined by an attribute (e.g.
+ * &struct landlock_path_beneath_attr) including a bitmask of access.
+ *
+ * Filesystem flags
+ * ~~~~~~~~~~~~~~~~
+ *
+ * These flags enable to restrict a sandbox process to a set of actions on

Quoted 1 line

s/sandbox/sandboxed/

OK

Quoted 18 lines

[...]

Quoted 1 line
security/landlock/fs.c +0 -0

[...]

Quoted 3 lines
security/landlock/fs.c +3 -0
+static const struct landlock_object_underops landlock_fs_underops = {
+       .release = release_inode
+};

[...]

Quoted 10 lines
security/landlock/fs.c +10 -0
+/* Access-control management */
+
+static bool check_access_path_continue(
+               const struct landlock_ruleset *const domain,
+               const struct path *const path, const u32 access_request,
+               bool *const allow, u64 *const layer_mask)
+{
+       const struct landlock_rule *rule;
+       const struct inode *inode;
+       bool next = true;
Quoted 8 lines

security/landlock/fs.c

Quoted 2 lines
security/landlock/fs.c +2 -0
+
+       prefetch(path->dentry->d_parent);

IIRC software prefetch() turned out to only rarely actually have a performance benefit, and they often actually make things worse; see e.g. <https://lwn.net/Articles/444336/>. Unless you have strong evidence that this actually brings a performance benefit, I'd probably get rid of this.

I took inspiration from the fs/d_path.c:prepend_path() but I agree. I'll remove prefetch() calls in the next series. I'll add them later if a benchmark shows an interesting performance impact.

Quoted 77 lines
Quoted 51 lines
security/landlock/fs.c +50 -0
+       if (d_is_negative(path->dentry))
+               /* Continues to walk while there is no mapped inode. */
+               return true;
+       inode = d_backing_inode(path->dentry);
+       rcu_read_lock();
+       rule = landlock_find_rule(domain,
+                       rcu_dereference(landlock_inode(inode)->object));
+       rcu_read_unlock();
+
+       /* Checks for matching layers. */
+       if (rule && (rule->layers | *layer_mask)) {
+               *allow = (rule->access & access_request) == access_request;
+               if (*allow) {
+                       *layer_mask &= ~rule->layers;
+                       /* Stops when a rule from each layer granted access. */
+                       next = !!*layer_mask;
+               } else {
+                       next = false;
+               }
+       }
+       return next;
+}
+
+static int check_access_path(const struct landlock_ruleset *const domain,
+               const struct path *const path, u32 access_request)
+{
+       bool allow = false;
+       struct path walker_path;
+       u64 layer_mask;
+
+       if (WARN_ON_ONCE(!domain || !path))
+               return 0;
+       /*
+        * Allows access to pseudo filesystems that will never be mountable
+        * (e.g. sockfs, pipefs), but can still be reachable through
+        * /proc/self/fd .
+        */
+       if ((path->dentry->d_sb->s_flags & SB_NOUSER) ||
+                       (d_is_positive(path->dentry) &&
+                        unlikely(IS_PRIVATE(d_backing_inode(path->dentry)))))
+               return 0;
+       if (WARN_ON_ONCE(domain->nb_layers < 1))
+               return -EACCES;
+
+       layer_mask = GENMASK_ULL(domain->nb_layers - 1, 0);
+       /*
+        * An access request which is not handled by the domain should be
+        * allowed.
+        */
+       access_request &= domain->fs_access_mask;

security/landlock/fs.c line 231

Quoted 10 lines
security/landlock/fs.c +10 -0
+       if (access_request == 0)
+               return 0;
+       walker_path = *path;
+       path_get(&walker_path);
+       /*
+        * We need to walk through all the hierarchy to not miss any relevant
+        * restriction.
+        */
+       while (check_access_path_continue(domain, &walker_path, access_request,
+                               &allow, &layer_mask)) {

The logic in this code might be clearer if check_access_path_continue() just returns whether the rule permitted the access. Then it'd look like:

bool allow = false;
[...]
while (check_access_path_continue(domain, &walker_path, access_request, &layer_mask)) {

  if (layer_mask == 0) {
    allow = true;
    break;

}
[...]
}

Quoted 5 lines

I think that would make it clearer under which conditions we can end up returning "true" from check_access_path().

(The current code also looks correct to me, I just think it'd be clearer this way. If you disagree, you can keep it as-is.)

I agree, applied and tested.

Quoted 50 lines
Quoted 38 lines
security/landlock/fs.c +36 -0
+               struct dentry *parent_dentry;
+
+jump_up:
+               /*
+                * Does not work with orphaned/private mounts like overlayfs
+                * layers for now (cf. ovl_path_real() and ovl_path_open()).
+                */
+               if (walker_path.dentry == walker_path.mnt->mnt_root) {
+                       if (follow_up(&walker_path)) {
+                               /* Ignores hidden mount points. */
+                               goto jump_up;
+                       } else {
+                               /*
+                                * Stops at the real root.  Denies access
+                                * because not all layers have granted access.
+                                */
+                               allow = false;
+                               break;
+                       }
+               }
+               if (unlikely(IS_ROOT(walker_path.dentry))) {
+                       /*
+                        * Stops at disconnected root directories.  Only allows
+                        * access to internal filesystems (e.g. nsfs which is
+                        * reachable through /proc/self/ns).
+                        */
+                       allow = !!(walker_path.mnt->mnt_flags & MNT_INTERNAL);
+                       break;
+               }
+               parent_dentry = dget_parent(walker_path.dentry);
+               dput(walker_path.dentry);
+               walker_path.dentry = parent_dentry;
+       }
+       path_put(&walker_path);
+       return allow ? 0 : -EACCES;
+}

[...]

Quoted 11 lines
security/landlock/fs.c +11 -0
+static inline u32 get_file_access(const struct file *const file)
+{
+       u32 access = 0;
+
+       if (file->f_mode & FMODE_READ) {
+               /* A directory can only be opened in read mode. */
+               if (S_ISDIR(file_inode(file)->i_mode))
+                       return LANDLOCK_ACCESS_FS_READ_DIR;
+               access = LANDLOCK_ACCESS_FS_READ_FILE;
+       }
+       /*
Quoted 8 lines

security/landlock/fs.c line 557

Quoted 3 lines
security/landlock/fs.c +3 -0
+        * A LANDLOCK_ACCESS_FS_APPEND could be added but we also need to check
+        * fcntl(2).
+        */

Once https://lore.kernel.org/linux-api/[email protected]/
lands, pwritev2() with RWF_NOAPPEND will also be problematic for classifying "write" vs "append"; you may want to include that in the comment. (Or delete the comment.)

Right, I'll include it in the comment.

Quoted 10 lines
Quoted 8 lines
security/landlock/fs.c +7 -0
+       if (file->f_mode & FMODE_WRITE)
+               access |= LANDLOCK_ACCESS_FS_WRITE_FILE;
+       /* __FMODE_EXEC is indeed part of f_flags, not f_mode. */
+       if (file->f_flags & __FMODE_EXEC)
+               access |= LANDLOCK_ACCESS_FS_EXECUTE;
+       return access;
+}

[...]

author maintainer
#22 lore raw

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

In reply to Jann Horn
Quoted 15 lines · Jann Horn
Quoted 1 line · Mickaël Salaün
security/landlock/fs.c +0 -0

[...]

Quoted 11 lines
security/landlock/fs.c +11 -0
+static inline u32 get_file_access(const struct file *const file)
+{
+       u32 access = 0;
+
+       if (file->f_mode & FMODE_READ) {
+               /* A directory can only be opened in read mode. */
+               if (S_ISDIR(file_inode(file)->i_mode))
+                       return LANDLOCK_ACCESS_FS_READ_DIR;
+               access = LANDLOCK_ACCESS_FS_READ_FILE;
+       }
+       /*
Quoted 8 lines

security/landlock/fs.c line 557

Quoted 3 lines
security/landlock/fs.c +3 -0
+        * A LANDLOCK_ACCESS_FS_APPEND could be added but we also need to check
+        * fcntl(2).
+        */

Once https://lore.kernel.org/linux-api/[email protected]/
lands, pwritev2() with RWF_NOAPPEND will also be problematic for classifying "write" vs "append"; you may want to include that in the comment. (Or delete the comment.)

Contrary to fcntl(2), pwritev2(2) doesn't seems to modify the file description. Otherwise, other LSMs would need to be patched. I'll remove this comment anyway.

Quoted 10 lines
Quoted 8 lines
security/landlock/fs.c +7 -0
+       if (file->f_mode & FMODE_WRITE)
+               access |= LANDLOCK_ACCESS_FS_WRITE_FILE;
+       /* __FMODE_EXEC is indeed part of f_flags, not f_mode. */
+       if (file->f_flags & __FMODE_EXEC)
+               access |= LANDLOCK_ACCESS_FS_EXECUTE;
+       return access;
+}

[...]

author maintainer
#23 lore raw

PATCH v22 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_enforce_ruleset_current(2): Enforces a ruleset on the current 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

Cc Arnd Bergmann <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

---

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/syscall.c   | 427 ++++++++++++++++++++++++++++++++++
 5 files changed, 493 insertions(+), 1 deletion(-)
 create mode 100644 security/landlock/syscall.c
include/linux/syscalls.h +7 -0
index 37bea07c12f2..ee3e24095c5f 100644
@@ -68,6 +68,8 @@ union bpf_attr;
 struct io_uring_params;
 struct clone_args;
 struct open_how;
+struct landlock_ruleset_attr;
+enum landlock_rule_type;
 
 #include <linux/types.h>
 #include <linux/aio_abi.h>
@@ -1008,6 +1010,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_enforce_ruleset_current(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 f27ac94d5fa7..0906cb79e801 100644
@@ -264,6 +264,11 @@ COND_SYSCALL(request_key);
 COND_SYSCALL(keyctl);
 COND_SYSCALL_COMPAT(keyctl);
 
+/* security/landlock/syscall.c */
+COND_SYSCALL(landlock_create_ruleset);
+COND_SYSCALL(landlock_add_rule);
+COND_SYSCALL(landlock_enforce_ruleset_current);
+
 /* arch/example/kernel/sys_example.c */
 
 /* mm/fadvise.c */
security/landlock/Makefile +1 -1
index 92e3d80ab8ed..4388494779ec 100644
@@ -1,4 +1,4 @@
 obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o
 
-landlock-y := setup.o object.o ruleset.o \
+landlock-y := setup.o syscall.o object.o ruleset.o \
 	cred.o ptrace.o fs.o
security/landlock/syscall.c new file +427 -0

427 lines not on this page · raw message

Signature · 1 line
2.28.0
#24 lore raw

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

Quoted 11 lines · Mickaël Salaün

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_enforce_ruleset_current(2): Enforces a ruleset on the current 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 6 lines
Cc Arnd Bergmann <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

[...]

Quoted 1 line
include/uapi/linux/landlock.h +0 -0

[...]

include/uapi/linux/landlock.h line 55

Quoted 13 lines
include/uapi/linux/landlock.h +13 -0
+/**
+ * struct landlock_path_beneath_attr - Path hierarchy definition
+ *
+ * Argument of sys_landlock_add_rule().
+ */
+struct landlock_path_beneath_attr {
+       /**
+        * @allowed_access: Bitmask of allowed actions for this file hierarchy
+        * (cf. `Filesystem flags`_).
+        */
+       __u64 allowed_access;
+       /**
+        * @parent_fd: File descriptor, open with ``O_PATH``, which identify

nit: "identifies"

Quoted 8 lines
include/uapi/linux/landlock.h +8 -0
+        * the parent directory of a file hierarchy, or just a file.
+        */
+       __s32 parent_fd;
+       /*
+        * This struct is packed to avoid trailing reserved members.
+        * Cf. security/landlock/syscall.c:build_check_abi()
+        */
+} __attribute__((packed));

[...]

Quoted 1 line
security/landlock/syscall.c +0 -0

[...]

security/landlock/syscall.c line 56

Quoted 12 lines
security/landlock/syscall.c +12 -0
+static 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. */
+       BUILD_BUG_ON(ksize <= 0);
+       BUILD_BUG_ON(ksize < ksize_min);

To make these checks work reliably, you should add __always_inline to the function.

Quoted 8 lines
security/landlock/syscall.c +8 -0
+       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);
+}

[...]

Quoted 19 lines
security/landlock/syscall.c +19 -0
+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.  Forbid internal filesystems (e.g.
+        * nsfs), including pseudo filesystems that will never be mountable
+        * (e.g. sockfs, pipefs).
+        */

security/landlock/syscall.c line 252

Quoted 10 lines
security/landlock/syscall.c +10 -0
+       if (!(f.file->f_mode & FMODE_PATH) ||
+                       (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->mnt = f.file->f_path.mnt;
+       path->dentry = f.file->f_path.dentry;

those two lines can be replaced with "*path = f.file->f_path"

Quoted 6 lines
security/landlock/syscall.c +6 -0
+       path_get(path);
+
+out_fdput:
+       fdput(f);
+       return err;
+}

[...]

Quoted 9 lines

+/**
+ * sys_landlock_enforce_ruleset_current - Enforce a ruleset on the current task
+ *
+ * @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 be running with no_new_privs. This avoids scenarios where

s/be/is/

Quoted 24 lines

+ * 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 doesn't have
+ * CAP_SYS_ADMIN in its namespace).
+ */

security/landlock/syscall.c +12 -0
+SYSCALL_DEFINE2(landlock_enforce_ruleset_current,
+               const int, ruleset_fd, const __u32, flags)
+{
+       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. */

security/landlock/syscall.c line 385

Quoted 10 lines
security/landlock/syscall.c +10 -0
+       if (flags)
+               return -EINVAL;
+
+       /*
+        * Similar checks as for seccomp(2), except that an -EPERM may be
+        * returned.
+        */
+       if (!task_no_new_privs(current)) {
+               err = security_capable(current_cred(), current_user_ns(),
+                               CAP_SYS_ADMIN, CAP_OPT_NOAUDIT);

I think this should be ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN)?

Quoted 27 lines
security/landlock/syscall.c +27 -0
+               if (err)
+                       return err;
+       }
+
+       /* 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;
+       }
+

security/landlock/syscall.c line 422

Quoted 10 lines
security/landlock/syscall.c +10 -0
+       /* 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);
+       return err;

I think this "return err" is wrong - don't we still have to put "ruleset" here?

Quoted 7 lines
security/landlock/syscall.c +4 -1
+out_put_ruleset:
+       landlock_put_ruleset(ruleset);
+       return err;
+}
--

2.28.0

author maintainer
#25 lore raw

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

Quoted 22 lines · Jann Horn
Quoted 11 lines · Mickaël Salaün

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_enforce_ruleset_current(2): Enforces a ruleset on the current 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 6 lines
Cc Arnd Bergmann <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

[...]

Quoted 1 line
include/uapi/linux/landlock.h +0 -0

[...]

Quoted 15 lines

include/uapi/linux/landlock.h line 55

Quoted 13 lines
include/uapi/linux/landlock.h +13 -0
+/**
+ * struct landlock_path_beneath_attr - Path hierarchy definition
+ *
+ * Argument of sys_landlock_add_rule().
+ */
+struct landlock_path_beneath_attr {
+       /**
+        * @allowed_access: Bitmask of allowed actions for this file hierarchy
+        * (cf. `Filesystem flags`_).
+        */
+       __u64 allowed_access;
+       /**
+        * @parent_fd: File descriptor, open with ``O_PATH``, which identify

nit: "identifies"

OK

Quoted 12 lines
Quoted 9 lines
include/uapi/linux/landlock.h +8 -0
+        * the parent directory of a file hierarchy, or just a file.
+        */
+       __s32 parent_fd;
+       /*
+        * This struct is packed to avoid trailing reserved members.
+        * Cf. security/landlock/syscall.c:build_check_abi()
+        */
+} __attribute__((packed));

[...]

Quoted 1 line
security/landlock/syscall.c +0 -0

[...]

Quoted 15 lines

security/landlock/syscall.c line 56

Quoted 12 lines
security/landlock/syscall.c +12 -0
+static 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. */
+       BUILD_BUG_ON(ksize <= 0);
+       BUILD_BUG_ON(ksize < ksize_min);

To make these checks work reliably, you should add __always_inline to the function.

Done.

Quoted 33 lines
Quoted 9 lines
security/landlock/syscall.c +8 -0
+       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);
+}

[...]

Quoted 23 lines
security/landlock/syscall.c +23 -0
+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.  Forbid 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_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) ||
Quoted 8 lines

security/landlock/syscall.c line 252

Quoted 6 lines
security/landlock/syscall.c +6 -0
+                       IS_PRIVATE(d_backing_inode(f.file->f_path.dentry))) {
+               err = -EBADFD;
+               goto out_fdput;
+       }
+       path->mnt = f.file->f_path.mnt;
+       path->dentry = f.file->f_path.dentry;

those two lines can be replaced with "*path = f.file->f_path"

Done.

Quoted 18 lines
Quoted 7 lines
security/landlock/syscall.c +6 -0
+       path_get(path);
+
+out_fdput:
+       fdput(f);
+       return err;
+}

[...]

Quoted 9 lines

+/**
+ * sys_landlock_enforce_ruleset_current - Enforce a ruleset on the current task
+ *
+ * @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 be running with no_new_privs. This avoids scenarios where

Quoted 1 line

s/be/is/

OK.

Quoted 29 lines
Quoted 29 lines

+ * 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 doesn't have
+ * CAP_SYS_ADMIN in its namespace).
+ */

security/landlock/syscall.c +16 -0
+SYSCALL_DEFINE2(landlock_enforce_ruleset_current,
+               const int, ruleset_fd, const __u32, flags)
+{
+       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;
+
+       /*
Quoted 8 lines

security/landlock/syscall.c line 385

Quoted 6 lines
security/landlock/syscall.c +6 -0
+        * Similar checks as for seccomp(2), except that an -EPERM may be
+        * returned.
+        */
+       if (!task_no_new_privs(current)) {
+               err = security_capable(current_cred(), current_user_ns(),
+                               CAP_SYS_ADMIN, CAP_OPT_NOAUDIT);

I think this should be ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN)?

Right. The main difference is that ns_capable*() set PF_SUPERPRIV in current->flags. I guess seccomp should use ns_capable_noaudit() as well?

Quoted 32 lines
Quoted 32 lines
security/landlock/syscall.c +31 -0
+               if (err)
+                       return err;
+       }
+
+       /* 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;
+
Quoted 8 lines

security/landlock/syscall.c line 422

Quoted 6 lines
security/landlock/syscall.c +6 -0
+       landlock_put_ruleset(ruleset);
+       return commit_creds(new_cred);
+
+out_put_creds:
+       abort_creds(new_cred);
+       return err;

I think this "return err" is wrong - don't we still have to put "ruleset" here?

Oh yes, good catch!

Quoted 9 lines
Quoted 9 lines
security/landlock/syscall.c +4 -1
+out_put_ruleset:
+       landlock_put_ruleset(ruleset);
+       return err;
+}
--

2.28.0

#26 lore raw

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

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

These 3 system calls are designed to be used by unprivileged processes to sandbox themselves:

[...]

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
security/landlock/syscall.c new file +7 -0
+       /*
+        * Similar checks as for seccomp(2), except that an -EPERM may be
+        * returned.
+        */
+       if (!task_no_new_privs(current)) {
+               err = security_capable(current_cred(), current_user_ns(),
+                               CAP_SYS_ADMIN, CAP_OPT_NOAUDIT);
Quoted 4 lines
Quoted 1 line

I think this should be ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN)?

Right. The main difference is that ns_capable*() set PF_SUPERPRIV in current->flags. I guess seccomp should use ns_capable_noaudit() as well?

Yeah. That seccomp code is from commit e2cfabdfd0756, with commit date in April 2012, while ns_capable_noaudit() was introduced in commit 98f368e9e263, with commit date in June 2016; the seccomp code predates the availability of that API.

Do you want to send a patch to Kees for that, or should I?

author maintainer
#27 lore raw

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

Quoted 19 lines · Jann Horn
Quoted 4 lines · Mickaël Salaün
Quoted 3 lines · Jann Horn
Quoted 2 lines · Mickaël Salaün

These 3 system calls are designed to be used by unprivileged processes to sandbox themselves:

[...]

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
security/landlock/syscall.c new file +7 -0
+       /*
+        * Similar checks as for seccomp(2), except that an -EPERM may be
+        * returned.
+        */
+       if (!task_no_new_privs(current)) {
+               err = security_capable(current_cred(), current_user_ns(),
+                               CAP_SYS_ADMIN, CAP_OPT_NOAUDIT);
Quoted 4 lines
Quoted 1 line

I think this should be ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN)?

Right. The main difference is that ns_capable*() set PF_SUPERPRIV in current->flags. I guess seccomp should use ns_capable_noaudit() as well?

Quoted 7 lines

Yeah. That seccomp code is from commit e2cfabdfd0756, with commit date in April 2012, while ns_capable_noaudit() was introduced in commit 98f368e9e263, with commit date in June 2016; the seccomp code predates the availability of that API.

Do you want to send a patch to Kees for that, or should I?

I found another case of this inconsistency in ptrace. I sent patches:
https://lore.kernel.org/lkml/[email protected]/

author maintainer
#28 lore raw

PATCH v22 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_enforce_ruleset_current(2)

Cc Arnd Bergmann <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

---

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 ee7b01bb7346..7ef9966fc654 100644
@@ -480,3 +480,6 @@
 548	common	pidfd_getfd			sys_pidfd_getfd
 549	common	faccessat2			sys_faccessat2
 550	common	process_madvise			sys_process_madvise
+552	common	landlock_create_ruleset				sys_landlock_create_ruleset
+553	common	landlock_add_rule					sys_landlock_add_rule
+554	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/arm/tools/syscall.tbl +3 -0
index d056a548358e..5bde774cef96 100644
@@ -454,3 +454,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/arm64/include/asm/unistd.h +1 -1
index b3b2019f8d16..64ebdc1ec581 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		441
+#define __NR_compat_syscalls		445
 #endif
 
 #define __ARCH_WANT_SYS_CLONE
arch/arm64/include/asm/unistd32.h +6 -0
index 107f08e03b9f..253521adb064 100644
@@ -889,6 +889,12 @@ __SYSCALL(__NR_pidfd_getfd, sys_pidfd_getfd)
 __SYSCALL(__NR_faccessat2, sys_faccessat2)
 #define __NR_process_madvise 440
 __SYSCALL(__NR_process_madvise, sys_process_madvise)
+#define __NR_landlock_create_ruleset 442
+__SYSCALL(__NR_landlock_create_ruleset, sys_landlock_create_ruleset)
+#define __NR_landlock_add_rule 443
+__SYSCALL(__NR_landlock_add_rule, sys_landlock_add_rule)
+#define __NR_landlock_enforce_ruleset_current 444
+__SYSCALL(__NR_landlock_enforce_ruleset_current, sys_landlock_enforce_ruleset_current)
 
 /*
  * Please add new compat syscalls above this comment and update
arch/ia64/kernel/syscalls/syscall.tbl +3 -0
index b96ed8b8a508..b3790ee36efa 100644
@@ -361,3 +361,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/m68k/kernel/syscalls/syscall.tbl +3 -0
index 625fb6d32842..1958c994511b 100644
@@ -440,3 +440,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/microblaze/kernel/syscalls/syscall.tbl +3 -0
index aae729c95cf9..213f731f719f 100644
@@ -446,3 +446,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/mips/kernel/syscalls/syscall_n32.tbl +3 -0
index 32817c954435..d9df5ab558d9 100644
@@ -379,3 +379,6 @@
 438	n32	pidfd_getfd			sys_pidfd_getfd
 439	n32	faccessat2			sys_faccessat2
 440	n32	process_madvise			sys_process_madvise
+442	n32	landlock_create_ruleset				sys_landlock_create_ruleset
+443	n32	landlock_add_rule					sys_landlock_add_rule
+444	n32	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/mips/kernel/syscalls/syscall_n64.tbl +3 -0
index 9e4ea3c31b1c..d7f7f1b8586a 100644
@@ -355,3 +355,6 @@
 438	n64	pidfd_getfd			sys_pidfd_getfd
 439	n64	faccessat2			sys_faccessat2
 440	n64	process_madvise			sys_process_madvise
+442	n64	landlock_create_ruleset				sys_landlock_create_ruleset
+443	n64	landlock_add_rule					sys_landlock_add_rule
+444	n64	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/mips/kernel/syscalls/syscall_o32.tbl +3 -0
index 29f5f28cf5ce..940572554130 100644
@@ -428,3 +428,6 @@
 438	o32	pidfd_getfd			sys_pidfd_getfd
 439	o32	faccessat2			sys_faccessat2
 440	o32	process_madvise			sys_process_madvise
+442	o32	landlock_create_ruleset				sys_landlock_create_ruleset
+443	o32	landlock_add_rule					sys_landlock_add_rule
+444	o32	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/parisc/kernel/syscalls/syscall.tbl +3 -0
index f375ea528e59..344bd5011555 100644
@@ -438,3 +438,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/powerpc/kernel/syscalls/syscall.tbl +3 -0
index 1275daec7fec..a00381d714ed 100644
@@ -530,3 +530,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/s390/kernel/syscalls/syscall.tbl +3 -0
index 28c168000483..2b58ee29e071 100644
@@ -443,3 +443,6 @@
 438  common	pidfd_getfd		sys_pidfd_getfd			sys_pidfd_getfd
 439  common	faccessat2		sys_faccessat2			sys_faccessat2
 440  common	process_madvise		sys_process_madvise		sys_process_madvise
+442  common	landlock_create_ruleset				sys_landlock_create_ruleset				sys_landlock_create_ruleset
+443  common	landlock_add_rule					sys_landlock_add_rule					sys_landlock_add_rule
+444  common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/sh/kernel/syscalls/syscall.tbl +3 -0
index 783738448ff5..adf7c7de5e2b 100644
@@ -443,3 +443,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/sparc/kernel/syscalls/syscall.tbl +3 -0
index 78160260991b..c9b58cdd8830 100644
@@ -486,3 +486,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/x86/entry/syscalls/syscall_32.tbl +3 -0
index 0d0667a9fbd7..2a3d87873d76 100644
@@ -445,3 +445,6 @@
 438	i386	pidfd_getfd		sys_pidfd_getfd
 439	i386	faccessat2		sys_faccessat2
 440	i386	process_madvise		sys_process_madvise
+442	i386	landlock_create_ruleset				sys_landlock_create_ruleset
+443	i386	landlock_add_rule					sys_landlock_add_rule
+444	i386	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
arch/x86/entry/syscalls/syscall_64.tbl +3 -0
index 1f47e24fb65c..9da85292cb79 100644
@@ -362,6 +362,9 @@
 438	common	pidfd_getfd		sys_pidfd_getfd
 439	common	faccessat2		sys_faccessat2
 440	common	process_madvise		sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
arch/xtensa/kernel/syscalls/syscall.tbl +3 -0
index b070f272995d..09c587a75625 100644
@@ -411,3 +411,6 @@
 438	common	pidfd_getfd			sys_pidfd_getfd
 439	common	faccessat2			sys_faccessat2
 440	common	process_madvise			sys_process_madvise
+442	common	landlock_create_ruleset				sys_landlock_create_ruleset
+443	common	landlock_add_rule					sys_landlock_add_rule
+444	common	landlock_enforce_ruleset_current	sys_landlock_enforce_ruleset_current
include/uapi/asm-generic/unistd.h +7 -1
index 2056318988f7..6892c0de6fbd 100644
@@ -859,9 +859,15 @@ __SYSCALL(__NR_pidfd_getfd, sys_pidfd_getfd)
 __SYSCALL(__NR_faccessat2, sys_faccessat2)
 #define __NR_process_madvise 440
 __SYSCALL(__NR_process_madvise, sys_process_madvise)
+#define __NR_landlock_create_ruleset 442
+__SYSCALL(__NR_landlock_create_ruleset, sys_landlock_create_ruleset)
+#define __NR_landlock_add_rule 443
+__SYSCALL(__NR_landlock_add_rule, sys_landlock_add_rule)
+#define __NR_landlock_enforce_ruleset_current 444
+__SYSCALL(__NR_landlock_enforce_ruleset_current, sys_landlock_enforce_ruleset_current)
 
 #undef __NR_syscalls
-#define __NR_syscalls 441
+#define __NR_syscalls 445
 
 /*
  * 32 bit systems traditionally used different
Signature · 1 line
2.28.0
maintainer
#29 lore raw

Re: [PATCH v22 09/12] arch: Wire up Landlock syscalls

Quoted 7 lines · 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_enforce_ruleset_current(2)

Quoted 6 lines
Cc Arnd Bergmann <[email protected]>
Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>

Acks from arch maintainers here would be appreciated.

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

PATCH v22 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.

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

Cc James Morris <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kees Cook <[email protected]>
Cc Serge E. Hallyn <[email protected]>
Cc Shuah Khan <[email protected]>

---

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]/

---
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/landlock/.gitignore   |    2 +
 tools/testing/selftests/landlock/Makefile     |   24 +
 tools/testing/selftests/landlock/base_test.c  |  117 ++
 tools/testing/selftests/landlock/common.h     |  113 ++
 tools/testing/selftests/landlock/config       |    5 +
 tools/testing/selftests/landlock/fs_test.c    | 1675 +++++++++++++++++
 .../testing/selftests/landlock/ptrace_test.c  |  307 +++
 tools/testing/selftests/landlock/true.c       |    5 +
 9 files changed, 2249 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
tools/testing/selftests/Makefile +1 -0
index d9c283503159..f40a34430652 100644
@@ -26,6 +26,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 +117 -0

117 lines not on this page · raw message

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

113 lines not on this page · raw message

tools/testing/selftests/landlock/config new file +5 -0
new file mode 100644
index 000000000000..042298105821
@@ -0,0 +1,5 @@
+CONFIG_SECURITY_LANDLOCK=y
+CONFIG_SECURITY_PATH=y
+CONFIG_SECURITY=y
+CONFIG_SHMEM=y
+CONFIG_TMPFS=y
tools/testing/selftests/landlock/fs_test.c new file +1675 -0

1,675 lines not on this page · raw message

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

307 lines not on this page · raw message

tools/testing/selftests/landlock/true.c new file +5 -0
new file mode 100644
index 000000000000..3f9ccbf52783
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: GPL-2.0
+int main(void)
+{
+	return 0;
+}
Signature · 1 line
2.28.0
author maintainer
#31 lore raw

PATCH v22 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 whitelist of file hierarchies in a read-only or read-write way.

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

---

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]/

---
 samples/Kconfig              |   7 ++
 samples/Makefile             |   1 +
 samples/landlock/.gitignore  |   1 +
 samples/landlock/Makefile    |  15 +++
 samples/landlock/sandboxer.c | 219 +++++++++++++++++++++++++++++++++++
 5 files changed, 243 insertions(+)
 create mode 100644 samples/landlock/.gitignore
 create mode 100644 samples/landlock/Makefile
 create mode 100644 samples/landlock/sandboxer.c
samples/Kconfig +7 -0
index 0ed6e4d71d87..e6129496ced5 100644
@@ -124,6 +124,13 @@ config SAMPLE_HIDRAW
 	bool "hidraw sample"
 	depends on CC_CAN_LINK && HEADERS_INSTALL
 
+config SAMPLE_LANDLOCK
+	bool "Build Landlock sample code"
+	depends on HEADERS_INSTALL
+	help
+	  Build a simple Landlock sandbox manager able to launch a process
+	  restricted by a user-defined filesystem access control.
+
 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 +15 -0
new file mode 100644
index 000000000000..21eda5774948
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: BSD-3-Clause
+
+hostprogs := sandboxer
+
+always-y := $(hostprogs)
+
+KBUILD_HOSTCFLAGS += -I$(objtree)/usr/include
+
+.PHONY: all clean
+
+all:
+	$(MAKE) -C ../.. samples/landlock/
+
+clean:
+	$(MAKE) -C ../.. M=samples/landlock/ clean
samples/landlock/sandboxer.c new file +219 -0

219 lines not on this page · raw message

Signature · 1 line
2.28.0
author maintainer
#32 lore raw

PATCH v22 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 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 | 259 +++++++++++++++++++++++
 MAINTAINERS                              |   2 +
 5 files changed, 342 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 69fc5167e648..4918fbed5be0 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 +259 -0

259 lines not on this page · raw message

MAINTAINERS +2 -0
index 43021f8c95bb..ac31dfd7663c 100644
@@ -9852,6 +9852,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:	security/landlock/
 K:	landlock
Signature · 1 line
2.28.0
#33 lore raw

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

Quoted 8 lines · Mickaël Salaün

This documentation can be built with the Sphinx framework.

[...]

Quoted 1 line
Documentation/userspace-api/landlock.rst +0 -0

[...]

Documentation/userspace-api/landlock.rst line 23

Quoted 4 lines
Documentation/userspace-api/landlock.rst +4 -0
+Landlock rules
+==============
+
+A Landlock rule enables to describe an action on an object.  An object is

s/enables to describe/describes/

Documentation/userspace-api/landlock.rst line 35

Quoted 12 lines
Documentation/userspace-api/landlock.rst +12 -0
+currently a file hierarchy, and the related filesystem actions are defined in
+`Access rights`_.  A set of rules is aggregated in a ruleset, which can then
+restrict the thread enforcing it, and its future children.
+
+Defining and enforcing a security policy
+----------------------------------------
+
+We first need to create the ruleset that will contain our rules.  For this
+example, the ruleset will contain rules which only allow read actions, but
+write actions will be denied.  The ruleset then needs to handle both of these
+kind of actions.  To have a backward compatibility, these actions should be
+ANDed with the supported ones.

This sounds as if there is a way for userspace to discover which actions are supported by the running kernel; but we don't have anything like that, right?

If we want to make that possible, we could maybe change sys_landlock_create_ruleset() so that if ruleset_attr.handled_access_fs contains bits we don't know, we clear those bits and then copy the struct back to userspace? And then userspace can retry the syscall with the cleared bits? Or something along those lines?

[...]

Documentation/userspace-api/landlock.rst line 64

Quoted 2 lines
Documentation/userspace-api/landlock.rst +2 -0
+We can now add a new rule to this ruleset thanks to the returned file
+descriptor referring to this ruleset.  The rule will only enable to read the

s/enable to read/allow reading/

Quoted 4 lines
Documentation/userspace-api/landlock.rst +4 -0
+file hierarchy ``/usr``.  Without another rule, write actions would then be
+denied by the ruleset.  To add ``/usr`` to the ruleset, we open it with the
+``O_PATH`` flag and fill the &struct landlock_path_beneath_attr with this file
+descriptor.

[...]

Documentation/userspace-api/landlock.rst line 139

Quoted 12 lines
Documentation/userspace-api/landlock.rst +12 -0
+Inheritance
+-----------
+
+Every new thread resulting from a :manpage:`clone(2)` inherits Landlock domain
+restrictions from its parent.  This is similar to the seccomp inheritance (cf.
+:doc:`/userspace-api/seccomp_filter`) or any other LSM dealing with task's
+:manpage:`credentials(7)`.  For instance, one process's thread may apply
+Landlock rules to itself, but they will not be automatically applied to other
+sibling threads (unlike POSIX thread credential changes, cf.
+:manpage:`nptl(7)`).
+
+When a thread sandbox itself, we have the grantee that the related security

s/sandbox/sandboxes/
s/grantee/guarantee/

Documentation/userspace-api/landlock.rst line 141

Quoted 2 lines
Documentation/userspace-api/landlock.rst +2 -0
+policy will stay enforced on all this thread's descendants.  This enables to
+create standalone and modular security policies per application, which will

s/enables to create/allows creating/

Quoted 2 lines
Documentation/userspace-api/landlock.rst +2 -0
+automatically be composed between themselves according to their runtime parent
+policies.
author maintainer
#34 lore raw

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

Quoted 10 lines · Jann Horn
Quoted 8 lines · Mickaël Salaün

This documentation can be built with the Sphinx framework.

[...]

Quoted 8 lines
Quoted 1 line
Documentation/userspace-api/landlock.rst +0 -0

[...]

Documentation/userspace-api/landlock.rst line 23

Quoted 4 lines
Documentation/userspace-api/landlock.rst +4 -0
+Landlock rules
+==============
+
+A Landlock rule enables to describe an action on an object.  An object is

s/enables to describe/describes/

OK.

Quoted 17 lines

Documentation/userspace-api/landlock.rst line 35

Quoted 13 lines
Documentation/userspace-api/landlock.rst +12 -0
+currently a file hierarchy, and the related filesystem actions are defined in
+`Access rights`_.  A set of rules is aggregated in a ruleset, which can then
+restrict the thread enforcing it, and its future children.
+
+Defining and enforcing a security policy
+----------------------------------------
+
+We first need to create the ruleset that will contain our rules.  For this
+example, the ruleset will contain rules which only allow read actions, but
+write actions will be denied.  The ruleset then needs to handle both of these
+kind of actions.  To have a backward compatibility, these actions should be
+ANDed with the supported ones.

This sounds as if there is a way for userspace to discover which actions are supported by the running kernel; but we don't have anything like that, right?

Right, it dates from the landlock_get_features(2), which is now gone but may be replaced by something else in the future. I'll remove that.

Quoted 7 lines

If we want to make that possible, we could maybe change sys_landlock_create_ruleset() so that if ruleset_attr.handled_access_fs contains bits we don't know, we clear those bits and then copy the struct back to userspace? And then userspace can retry the syscall with the cleared bits? Or something along those lines?

Yes, but I would prefer clear syscall which don't read and write from/to the same argument. I'm working on a more generic solution. It should not be an issue for now.

Quoted 6 lines

[...]

Documentation/userspace-api/landlock.rst line 64

Quoted 2 lines
Documentation/userspace-api/landlock.rst +2 -0
+We can now add a new rule to this ruleset thanks to the returned file
+descriptor referring to this ruleset.  The rule will only enable to read the

s/enable to read/allow reading/

OK.

Quoted 6 lines
Quoted 5 lines
Documentation/userspace-api/landlock.rst +4 -0
+file hierarchy ``/usr``.  Without another rule, write actions would then be
+denied by the ruleset.  To add ``/usr`` to the ruleset, we open it with the
+``O_PATH`` flag and fill the &struct landlock_path_beneath_attr with this file
+descriptor.

[...]

Quoted 15 lines

Documentation/userspace-api/landlock.rst line 139

Quoted 12 lines
Documentation/userspace-api/landlock.rst +12 -0
+Inheritance
+-----------
+
+Every new thread resulting from a :manpage:`clone(2)` inherits Landlock domain
+restrictions from its parent.  This is similar to the seccomp inheritance (cf.
+:doc:`/userspace-api/seccomp_filter`) or any other LSM dealing with task's
+:manpage:`credentials(7)`.  For instance, one process's thread may apply
+Landlock rules to itself, but they will not be automatically applied to other
+sibling threads (unlike POSIX thread credential changes, cf.
+:manpage:`nptl(7)`).
+
+When a thread sandbox itself, we have the grantee that the related security

s/sandbox/sandboxes/
s/grantee/guarantee/

OK.

Quoted 5 lines

Documentation/userspace-api/landlock.rst line 141

Quoted 3 lines
Documentation/userspace-api/landlock.rst +2 -0
+policy will stay enforced on all this thread's descendants.  This enables to
+create standalone and modular security policies per application, which will

s/enables to create/allows creating/

OK.

Quoted 4 lines
Quoted 4 lines
Documentation/userspace-api/landlock.rst +2 -0
+automatically be composed between themselves according to their runtime parent
+policies.
#35 lore raw
In reply to Mickaël Salaün
Quoted 3 lines · Mickaël Salaün

This new patch series improves documentation, cleans up comments, renames ARCH_EPHEMERAL_STATES to ARCH_EPHEMERAL_INODES and removes LANDLOCK_ACCESS_FS_CHROOT.

Thanks for continuing to work on this! This is going to be really valuable for sandboxing.

I hadn't looked at this series for a while; but I've now read through it, and I don't see any major problems left. :) That said, there still are a couple small things...

author maintainer
#36 lore raw
Quoted 5 lines · Jann Horn
Quoted 3 lines · Mickaël Salaün

This new patch series improves documentation, cleans up comments, renames ARCH_EPHEMERAL_STATES to ARCH_EPHEMERAL_INODES and removes LANDLOCK_ACCESS_FS_CHROOT.

Quoted 7 lines

Thanks for continuing to work on this! This is going to be really valuable for sandboxing.

I hadn't looked at this series for a while; but I've now read through it, and I don't see any major problems left. :) That said, there still are a couple small things...

Thanks Jann, I really appreciate your reviews!