Skip to contentSkip to conversation

Fix Landlock mediation of commoncap's capability checks

PATCH Superseded Mickaël Salaün 3 participants 23 messages Nov 17 – Nov 18

Subsystems (4)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Mickaël Salaün

author maintainer
#0 lore raw

v2 cover Fix Landlock mediation of commoncap's capability checks

Hi,

This is series 1 of 3:

* 1. fix Landlock mediation of commoncap's capability checks;
2. fix PR_SET_SECUREBITS mediation and add focused Landlock tests;
3. fix Landlock mediation of capabilities guarding LSM policies.

LANDLOCK_PERMISSION_CAPABILITY_USE, merged for v7.4, denies capabilities through the LSM capable hook, but commoncap's mmap_addr, capset and vm_enough_memory hooks call cap_capable() directly. A domain that denies a capability can therefore still:

- map memory below vm.mmap_min_addr (CAP_SYS_RAWIO), which defeats a mitigation for kernel NULL pointer dereferences;
- add inheritable capabilities outside of its permitted set (CAP_SETPCAP), which lets a privileged sandbox without no_new_privs gain capabilities through execve(), although the domain still restricts their use;
- use the admin memory reserve with vm.overcommit_memory=2 (CAP_SYS_ADMIN).

As SELinux does, patches 2 to 4 add Landlock's own check to these hooks, with commoncap's conditions, so they only deny what commoncap granted because of the capability. Patch 1 factors out the shared check. Patch 5 adds tests, including audit tests, that fail without the mmap_addr and capset fixes; testing the admin reserve would require changing system-wide overcommit settings. Patch 6 fixes the documentation, which overstated what the permission restricts and how its denials show.

Two other direct capability-set checks are fixed separately:

- PSI triggers (CAP_SYS_RESOURCE):
https://patch.msgid.link/[email protected]
- user namespace uid 0 mapping (CAP_SETFCAP):
https://patch.msgid.link/[email protected]

Changes since v1:
https://patch.msgid.link/[email protected]
- Replace the admin reserve test, which changed system-wide overcommit settings and was racy, with a comment, and fix the mmap_addr tests on 32-bit ARM (reported by Sashiko).
- Add Serge Hallyn's Acked-by.

Regards,

Mickaël Salaün (6):
landlock: Factor out capability denial checks
landlock: Mediate CAP_SYS_RAWIO for mappings below mmap_min_addr
landlock: Mediate CAP_SETPCAP for inheritable capabilities
landlock: Mediate CAP_SYS_ADMIN for the admin memory reserve selftests/landlock: Test capability checks outside the capable hook
landlock: Fix capability restriction documentation

 Documentation/security/landlock.rst         |   8 +-
 Documentation/userspace-api/landlock.rst    |   8 +-
 include/uapi/linux/landlock.h               |   6 +-
 security/landlock/cap.c                     | 110 ++++++-
 tools/testing/selftests/landlock/cap_test.c | 336 ++++++++++++++++++++
 tools/testing/selftests/landlock/common.h   |   4 +-
 6 files changed, 451 insertions(+), 21 deletions(-)

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.56.0
author maintainer
#1 lore raw

PATCH v2 1/6 landlock: Factor out capability denial checks

hook_capable() is the only place that checks a capability against a Landlock domain. commoncap also makes capability decisions from other LSM hooks, and the following commits add Landlock counterparts for them. Move the check and its denial logging into check_cap() so that these hooks share it.

No functional change.

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 36 +++++++++++++++++++++++++++---------
 1 file changed, 27 insertions(+), 9 deletions(-)
security/landlock/cap.c +27 -9
index b4f491b09baa..fa59118e3486 100644
@@ -24,25 +24,21 @@ static const struct access_masks cap_permission = {
 };
 
 /**
- * hook_capable - Deny capability use for Landlock-sandboxed processes
+ * check_cap - Check a capability use against the domain of @cred
  *
  * @cred: Credentials being checked.
- * @ns: Target user namespace (intentionally ignored; policy depends on the
- *      acting credentials and @cap, not namespace ownership).
  * @cap: Capability number (CAP_*).
  * @opts: Capability check options.  CAP_OPT_NOAUDIT skips the denial record:
  *        no audit record, no trace event, and no denial count.
  *
  * Pure bitmask check: denies the capability if it is not in the layer's allowed
- * set.  This hook is purely restrictive: commoncap is registered with
- * LSM_ORDER_FIRST so cap_capable() always runs first, which means Landlock can
- * deny capabilities that commoncap would allow, but never grant capabilities
- * that commoncap denied.
+ * set.  It does not check that @cred holds @cap: only call it for a capability
+ * that commoncap already granted.
  *
  * Return: 0 if allowed, -EPERM if capability use is denied.
  */
-static int hook_capable(const struct cred *cred, struct user_namespace *ns,
-			int cap, unsigned int opts)
+static int check_cap(const struct cred *const cred, const int cap,
+		     const unsigned int opts)
 {
 	const struct landlock_cred_security *subject;
 	size_t denied_layer;
@@ -72,6 +68,28 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return -EPERM;
 }
 
+/**
+ * hook_capable - Deny capability use for Landlock-sandboxed processes
+ *
+ * @cred: Credentials being checked.
+ * @ns: Target user namespace (intentionally ignored; policy depends on the
+ *      acting credentials and @cap, not namespace ownership).
+ * @cap: Capability number (CAP_*).
+ * @opts: Capability check options, see check_cap().
+ *
+ * This hook is purely restrictive: commoncap is registered with LSM_ORDER_FIRST
+ * so cap_capable() always runs first, which means Landlock can deny
+ * capabilities that commoncap would allow, but never grant capabilities that
+ * commoncap denied.
+ *
+ * Return: 0 if allowed, -EPERM if capability use is denied.
+ */
+static int hook_capable(const struct cred *cred, struct user_namespace *ns,
+			int cap, unsigned int opts)
+{
+	return check_cap(cred, cap, opts);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
 };
Signature · 1 line
2.56.0
#2 lore raw

Re: [PATCH v2 1/6] landlock: Factor out capability denial checks

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

hook_capable() is the only place that checks a capability against a Landlock domain. commoncap also makes capability decisions from other LSM hooks, and the following commits add Landlock counterparts for them. Move the check and its denial logging into check_cap() so that these hooks share it.

No functional change.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
reviewer Reviewed-by on v2 1/6
#3 lore raw

Re: [PATCH v2 1/6] landlock: Factor out capability denial checks

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

hook_capable() is the only place that checks a capability against a Landlock domain. commoncap also makes capability decisions from other LSM hooks, and the following commits add Landlock counterparts for them. Move the check and its denial logging into check_cap() so that these hooks share it.

No functional change.

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 36 +++++++++++++++++++++++++++---------
 1 file changed, 27 insertions(+), 9 deletions(-)
security/landlock/cap.c +27 -9
index b4f491b09baa..fa59118e3486 100644
@@ -24,25 +24,21 @@ static const struct access_masks cap_permission = {
 };
 
 /**
- * hook_capable - Deny capability use for Landlock-sandboxed processes
+ * check_cap - Check a capability use against the domain of @cred
  *
  * @cred: Credentials being checked.
- * @ns: Target user namespace (intentionally ignored; policy depends on the
- *      acting credentials and @cap, not namespace ownership).
  * @cap: Capability number (CAP_*).
  * @opts: Capability check options.  CAP_OPT_NOAUDIT skips the denial record:
  *        no audit record, no trace event, and no denial count.
  *
  * Pure bitmask check: denies the capability if it is not in the layer's allowed
- * set.  This hook is purely restrictive: commoncap is registered with
- * LSM_ORDER_FIRST so cap_capable() always runs first, which means Landlock can
- * deny capabilities that commoncap would allow, but never grant capabilities
- * that commoncap denied.
+ * set.  It does not check that @cred holds @cap: only call it for a capability
+ * that commoncap already granted.
  *
  * Return: 0 if allowed, -EPERM if capability use is denied.
  */
-static int hook_capable(const struct cred *cred, struct user_namespace *ns,
-			int cap, unsigned int opts)
+static int check_cap(const struct cred *const cred, const int cap,
+		     const unsigned int opts)
 {
 	const struct landlock_cred_security *subject;
 	size_t denied_layer;
@@ -72,6 +68,28 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return -EPERM;
 }
 
+/**
+ * hook_capable - Deny capability use for Landlock-sandboxed processes
+ *
+ * @cred: Credentials being checked.
+ * @ns: Target user namespace (intentionally ignored; policy depends on the
+ *      acting credentials and @cap, not namespace ownership).
+ * @cap: Capability number (CAP_*).
+ * @opts: Capability check options, see check_cap().
+ *
+ * This hook is purely restrictive: commoncap is registered with LSM_ORDER_FIRST
+ * so cap_capable() always runs first, which means Landlock can deny
+ * capabilities that commoncap would allow, but never grant capabilities that
+ * commoncap denied.
+ *
+ * Return: 0 if allowed, -EPERM if capability use is denied.
+ */
+static int hook_capable(const struct cred *cred, struct user_namespace *ns,
+			int cap, unsigned int opts)
+{
+	return check_cap(cred, cap, opts);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
 };
Signature · 1 line
2.56.0
author maintainer
#4 lore raw

PATCH v2 2/6 landlock: Mediate CAP_SYS_RAWIO for mappings below mmap_min_addr

In reply to Mickaël Salaün

Until now, a process in a domain that denies CAP_SYS_RAWIO could still map memory below the vm.mmap_min_addr limit if it held this capability. cap_mmap_addr() is commoncap's mmap_addr hook, and it checks CAP_SYS_RAWIO with cap_capable(), not security_capable(), so the check never reaches hook_capable(). Mapping the lowest pages is what this limit protects against, because it helps to exploit kernel NULL pointer dereferences.

Add a Landlock mmap_addr hook that checks CAP_SYS_RAWIO against the domain under the same condition as cap_mmap_addr(). With the same vm.mmap_min_addr value, the hook only denies mappings for which commoncap required the capability. security_mmap_addr() stops at commoncap's error, so processes without the capability get the same result as before. This also covers the x86 vm86(2) and vm86old(2) system calls, which use the same check for address 0.

Making cap_mmap_addr() call capable() would also fix this, but it would send every low mapping through the capable hook of all LSMs (SELinux, AppArmor, SafeSetID, BPF LSM programs), adding capability checks that their policies never had to handle. For instance, SELinux checks mmap_zero in its own mmap_addr hook and keeps it separate from the capability on purpose. LSMs with their own policy for low mappings implement it in this hook, so Landlock does the same.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
security/landlock/cap.c +22 -0
index fa59118e3486..10e1ca772b9c 100644
@@ -9,6 +9,7 @@
 #include <linux/cred.h>
 #include <linux/lsm_audit.h>
 #include <linux/lsm_hooks.h>
+#include <linux/security.h>
 #include <uapi/linux/landlock.h>
 
 #include "cap.h"
@@ -90,8 +91,29 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return check_cap(cred, cap, opts);
 }
 
+/**
+ * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr
+ *
+ * @addr: Address of the new mapping.
+ *
+ * cap_mmap_addr() requires CAP_SYS_RAWIO to map below dac_mmap_min_addr, but
+ * calls cap_capable() directly, which skips hook_capable().  Check the same
+ * condition against the domain.  commoncap runs first, so this only sees
+ * mappings that commoncap allowed.
+ *
+ * Return: 0 if allowed, -EPERM if CAP_SYS_RAWIO use is denied.
+ */
+static int hook_mmap_addr(unsigned long addr)
+{
+	if (addr >= dac_mmap_min_addr)
+		return 0;
+
+	return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
+	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
 };
 
 __init void landlock_add_cap_hooks(void)
Signature · 1 line
2.56.0
#5 lore raw

Re: [PATCH v2 2/6] landlock: Mediate CAP_SYS_RAWIO for mappings below mmap_min_addr

Sashiko has reviewed this patch and found no issues.
Quoted 24 lines

Until now, a process in a domain that denies CAP_SYS_RAWIO could still map memory below the vm.mmap_min_addr limit if it held this capability. cap_mmap_addr() is commoncap's mmap_addr hook, and it checks CAP_SYS_RAWIO with cap_capable(), not security_capable(), so the check never reaches hook_capable(). Mapping the lowest pages is what this limit protects against, because it helps to exploit kernel NULL pointer dereferences.

Add a Landlock mmap_addr hook that checks CAP_SYS_RAWIO against the domain under the same condition as cap_mmap_addr(). With the same vm.mmap_min_addr value, the hook only denies mappings for which commoncap required the capability. security_mmap_addr() stops at commoncap's error, so processes without the capability get the same result as before. This also covers the x86 vm86(2) and vm86old(2) system calls, which use the same check for address 0.

Making cap_mmap_addr() call capable() would also fix this, but it would send every low mapping through the capable hook of all LSMs (SELinux, AppArmor, SafeSetID, BPF LSM programs), adding capability checks that their policies never had to handle. For instance, SELinux checks mmap_zero in its own mmap_addr hook and keeps it separate from the capability on purpose. LSMs with their own policy for low mappings implement it in this hook, so Landlock does the same.

Quoted 6 lines
Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
reviewer Reviewed-by on v2 2/6
#6 lore raw

Re: [PATCH v2 2/6] landlock: Mediate CAP_SYS_RAWIO for mappings below mmap_min_addr

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

Until now, a process in a domain that denies CAP_SYS_RAWIO could still map memory below the vm.mmap_min_addr limit if it held this capability. cap_mmap_addr() is commoncap's mmap_addr hook, and it checks CAP_SYS_RAWIO with cap_capable(), not security_capable(), so the check never reaches hook_capable(). Mapping the lowest pages is what this limit protects against, because it helps to exploit kernel NULL pointer dereferences.

Add a Landlock mmap_addr hook that checks CAP_SYS_RAWIO against the domain under the same condition as cap_mmap_addr(). With the same vm.mmap_min_addr value, the hook only denies mappings for which commoncap required the capability. security_mmap_addr() stops at commoncap's error, so processes without the capability get the same result as before. This also covers the x86 vm86(2) and vm86old(2) system calls, which use the same check for address 0.

Making cap_mmap_addr() call capable() would also fix this, but it would send every low mapping through the capable hook of all LSMs (SELinux, AppArmor, SafeSetID, BPF LSM programs), adding capability checks that their policies never had to handle. For instance, SELinux checks mmap_zero in its own mmap_addr hook and keeps it separate from the capability on purpose. LSMs with their own policy for low mappings implement it in this hook, so Landlock does the same.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
security/landlock/cap.c +22 -0
index fa59118e3486..10e1ca772b9c 100644
@@ -9,6 +9,7 @@
 #include <linux/cred.h>
 #include <linux/lsm_audit.h>
 #include <linux/lsm_hooks.h>
+#include <linux/security.h>
 #include <uapi/linux/landlock.h>
 
 #include "cap.h"
@@ -90,8 +91,29 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return check_cap(cred, cap, opts);
 }
 
+/**
+ * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr
+ *
+ * @addr: Address of the new mapping.
+ *
+ * cap_mmap_addr() requires CAP_SYS_RAWIO to map below dac_mmap_min_addr, but
+ * calls cap_capable() directly, which skips hook_capable().  Check the same
+ * condition against the domain.  commoncap runs first, so this only sees
+ * mappings that commoncap allowed.
+ *
+ * Return: 0 if allowed, -EPERM if CAP_SYS_RAWIO use is denied.
+ */
+static int hook_mmap_addr(unsigned long addr)
+{
+	if (addr >= dac_mmap_min_addr)
+		return 0;
+
+	return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
+	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
 };
 
 __init void landlock_add_cap_hooks(void)
Signature · 1 line
2.56.0

Looks good; I compared this against the commoncap implementation of the same hook, and the logic checks out.

Minor nit, in case you end up sending a V3; I found the commit message a bit wordy.

It makes intuitively sense that the commoncap LSM does not want to invoke functions which themselves call into LSM hooks, even if it's just a safeguard to prevent accidental recursion or deep call stacks.

So for the few cases where commoncap checks capabilities directly, we need to do the equivalent checks in the same LSM hooks in Landlock. That means, we replicate the logic from the commoncap hook if necessary and treat it like a capability use that came in through the normal hook. This is similar to what SELinux already does as well.

What I would have found useful to discuss in this commit message would have been the story of PF_SUPERPRIV:

commoncap sets PF_SUPERPRIV when granting the capability use, and Landlock does not undo that when it rejects the capability use. In my understanding this is OK because the flag only gets used in "legacy accounting" use cases and the consequences are benign. The interaction with SELinux is already the same as well - it does not unset that flag.

—Günther

author maintainer
#7 lore raw

Re: [PATCH v2 2/6] landlock: Mediate CAP_SYS_RAWIO for mappings below mmap_min_addr

Quoted 88 lines · Günther Noack
Quoted 84 lines · Mickaël Salaün

Until now, a process in a domain that denies CAP_SYS_RAWIO could still map memory below the vm.mmap_min_addr limit if it held this capability. cap_mmap_addr() is commoncap's mmap_addr hook, and it checks CAP_SYS_RAWIO with cap_capable(), not security_capable(), so the check never reaches hook_capable(). Mapping the lowest pages is what this limit protects against, because it helps to exploit kernel NULL pointer dereferences.

Add a Landlock mmap_addr hook that checks CAP_SYS_RAWIO against the domain under the same condition as cap_mmap_addr(). With the same vm.mmap_min_addr value, the hook only denies mappings for which commoncap required the capability. security_mmap_addr() stops at commoncap's error, so processes without the capability get the same result as before. This also covers the x86 vm86(2) and vm86old(2) system calls, which use the same check for address 0.

Making cap_mmap_addr() call capable() would also fix this, but it would send every low mapping through the capable hook of all LSMs (SELinux, AppArmor, SafeSetID, BPF LSM programs), adding capability checks that their policies never had to handle. For instance, SELinux checks mmap_zero in its own mmap_addr hook and keeps it separate from the capability on purpose. LSMs with their own policy for low mappings implement it in this hook, so Landlock does the same.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
security/landlock/cap.c +22 -0
index fa59118e3486..10e1ca772b9c 100644
@@ -9,6 +9,7 @@
 #include <linux/cred.h>
 #include <linux/lsm_audit.h>
 #include <linux/lsm_hooks.h>
+#include <linux/security.h>
 #include <uapi/linux/landlock.h>
 
 #include "cap.h"
@@ -90,8 +91,29 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return check_cap(cred, cap, opts);
 }
 
+/**
+ * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr
+ *
+ * @addr: Address of the new mapping.
+ *
+ * cap_mmap_addr() requires CAP_SYS_RAWIO to map below dac_mmap_min_addr, but
+ * calls cap_capable() directly, which skips hook_capable().  Check the same
+ * condition against the domain.  commoncap runs first, so this only sees
+ * mappings that commoncap allowed.
+ *
+ * Return: 0 if allowed, -EPERM if CAP_SYS_RAWIO use is denied.
+ */
+static int hook_mmap_addr(unsigned long addr)
+{
+	if (addr >= dac_mmap_min_addr)
+		return 0;
+
+	return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
+	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
 };
 
 __init void landlock_add_cap_hooks(void)
Signature · 1 line
2.56.0
Quoted 6 lines

Looks good; I compared this against the commoncap implementation of the same hook, and the logic checks out.

Minor nit, in case you end up sending a V3; I found the commit message a bit wordy.

Indeed, I'll send a v3 with your feedback.

Quoted 14 lines

It makes intuitively sense that the commoncap LSM does not want to invoke functions which themselves call into LSM hooks, even if it's just a safeguard to prevent accidental recursion or deep call stacks.

So for the few cases where commoncap checks capabilities directly, we need to do the equivalent checks in the same LSM hooks in Landlock. That means, we replicate the logic from the commoncap hook if necessary and treat it like a capability use that came in through the normal hook. This is similar to what SELinux already does as well.

What I would have found useful to discuss in this commit message would have been the story of PF_SUPERPRIV:

Quoted 6 lines

commoncap sets PF_SUPERPRIV when granting the capability use, and Landlock does not undo that when it rejects the capability use. In my understanding this is OK because the flag only gets used in "legacy accounting" use cases and the consequences are benign. The interaction with SELinux is already the same as well - it does not unset that flag.

Good catch! I think it should not be addressed by this series but I just sent a fix for that:
https://lore.kernel.org/r/[email protected]

Quoted 3 lines

—Günther

author maintainer
#8 lore raw

PATCH v2 3/6 landlock: Mediate CAP_SETPCAP for inheritable capabilities

In reply to Mickaël Salaün

A process in a domain that denies CAP_SETPCAP could still add capabilities outside of its permitted set to its inheritable set with capset(2), if it held CAP_SETPCAP. cap_capset() checks CAP_SETPCAP with cap_capable() in cap_inh_is_capped(), so the check never reaches hook_capable(). Through file inheritable capabilities, such a set can grant new permitted capabilities on execve() when no_new_privs is not set, which is possible for a domain enforced by a task holding CAP_SYS_ADMIN.

Add a Landlock capset hook that checks CAP_SETPCAP against the domain under the same condition as cap_capset(). As with the mmap_addr hook, LSMs implement their own policy in this hook: SELinux checks capset with its own permission.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
security/landlock/cap.c +30 -0
index 10e1ca772b9c..c89e8d76db8c 100644
@@ -91,6 +91,35 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return check_cap(cred, cap, opts);
 }
 
+/**
+ * hook_capset - Restrict inheritable capability changes
+ *
+ * @new: New credentials (unused).
+ * @old: Current credentials.
+ * @effective: New effective set (unused).
+ * @inheritable: New inheritable set.
+ * @permitted: New permitted set (unused).
+ *
+ * cap_capset() requires CAP_SETPCAP to add inheritable capabilities that are
+ * not in the old permitted set, but calls cap_capable() directly, which skips
+ * hook_capable().  Check the same condition against the domain.  commoncap runs
+ * first, so this only sees requests that commoncap allowed.  capset(2) discards
+ * @new if this hook fails, so nothing is committed.
+ *
+ * Return: 0 if allowed, -EPERM if CAP_SETPCAP use is denied.
+ */
+static int hook_capset(struct cred *new, const struct cred *old,
+		       const kernel_cap_t *effective,
+		       const kernel_cap_t *inheritable,
+		       const kernel_cap_t *permitted)
+{
+	if (cap_issubset(*inheritable,
+			 cap_combine(old->cap_inheritable, old->cap_permitted)))
+		return 0;
+
+	return check_cap(old, CAP_SETPCAP, CAP_OPT_NONE);
+}
+
 /**
  * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr
  *
@@ -113,6 +142,7 @@ static int hook_mmap_addr(unsigned long addr)
 
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
+	LSM_HOOK_INIT(capset, hook_capset),
 	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
 };
 
Signature · 1 line
2.56.0
#9 lore raw

Re: [PATCH v2 3/6] landlock: Mediate CAP_SETPCAP for inheritable capabilities

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

A process in a domain that denies CAP_SETPCAP could still add capabilities outside of its permitted set to its inheritable set with capset(2), if it held CAP_SETPCAP. cap_capset() checks CAP_SETPCAP with cap_capable() in cap_inh_is_capped(), so the check never reaches hook_capable(). Through file inheritable capabilities, such a set can grant new permitted capabilities on execve() when no_new_privs is not set, which is possible for a domain enforced by a task holding CAP_SYS_ADMIN.

Add a Landlock capset hook that checks CAP_SETPCAP against the domain under the same condition as cap_capset(). As with the mmap_addr hook, LSMs implement their own policy in this hook: SELinux checks capset with its own permission.

Quoted 6 lines
Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
reviewer Reviewed-by on v2 3/6
#10 lore raw

Re: [PATCH v2 3/6] landlock: Mediate CAP_SETPCAP for inheritable capabilities

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

A process in a domain that denies CAP_SETPCAP could still add capabilities outside of its permitted set to its inheritable set with capset(2), if it held CAP_SETPCAP. cap_capset() checks CAP_SETPCAP with cap_capable() in cap_inh_is_capped(), so the check never reaches hook_capable(). Through file inheritable capabilities, such a set can grant new permitted capabilities on execve() when no_new_privs is not set, which is possible for a domain enforced by a task holding CAP_SYS_ADMIN.

Add a Landlock capset hook that checks CAP_SETPCAP against the domain under the same condition as cap_capset(). As with the mmap_addr hook, LSMs implement their own policy in this hook: SELinux checks capset with its own permission.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
security/landlock/cap.c +2 -0
index 10e1ca772b9c..c89e8d76db8c 100644
@@ -91,6 +91,35 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return check_cap(cred, cap, opts);
 }
 
+/**
+ * hook_capset - Restrict inheritable capability changes

security/landlock/cap.c static int hook_capable(const struct cred *cred, struct user_namespace *ns, · line 105

Quoted 10 lines
security/landlock/cap.c +10 -0
+ *
+ * @new: New credentials (unused).
+ * @old: Current credentials.
+ * @effective: New effective set (unused).
+ * @inheritable: New inheritable set.
+ * @permitted: New permitted set (unused).
+ *
+ * cap_capset() requires CAP_SETPCAP to add inheritable capabilities that are
+ * not in the old permitted set, but calls cap_capable() directly, which skips
+ * hook_capable().

It has taken me a bit of time to wrap my head around this one.

cap_capset() starts with:

	if (cap_inh_is_capped() &&
	    !cap_issubset(*inheritable,
			  cap_combine(old->cap_inheritable,
				      old->cap_permitted)))
		/* incapable of using this inheritable set */
		return -EPERM;

where cap_inh_is_capped() returns true if it does *not* have CAP_SETPCAP.

So when this Landlock hooks gets called, cap_capset() has already checked that we either have CAP_SETPCAP or inheritable ⊆ (old->inheritable ⋃ old->permitted). So the Landlock hook can check for the cap_issubset(...) condition to see whether CAP_SETPCAP had to be "used".

Maybe it would be easier to phrase it like that?

(A more specific nit about this comment, "calls cap_capable() *directly*" has confused me a bit, since cap_capset() calls cap_capable() only *indirectly* through cap_inh_is_capped(). Maybe "promptly", or "immediately" would be better?)

Quoted 32 lines

Check the same condition against the domain. commoncap runs
+ * first, so this only sees requests that commoncap allowed. capset(2) discards
+ * @new if this hook fails, so nothing is committed.
+ *
+ * Return: 0 if allowed, -EPERM if CAP_SETPCAP use is denied.
+ */

security/landlock/cap.c +13 -0
+static int hook_capset(struct cred *new, const struct cred *old,
+		       const kernel_cap_t *effective,
+		       const kernel_cap_t *inheritable,
+		       const kernel_cap_t *permitted)
+{
+	if (cap_issubset(*inheritable,
+			 cap_combine(old->cap_inheritable, old->cap_permitted)))
+		return 0;
+
+	return check_cap(old, CAP_SETPCAP, CAP_OPT_NONE);
+}
+
 /**
  * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr
  *
@@ -113,6 +142,7 @@ static int hook_mmap_addr(unsigned long addr)
 
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
+	LSM_HOOK_INIT(capset, hook_capset),
 	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
 };
 
Signature · 1 line
2.56.0

Code checks out, only minor comments about the documentation. It has taken me a bit to understand how the Landlock hook's logic matches the one in cap_capset().

—Günther

author maintainer
#11 lore raw

Re: [PATCH v2 3/6] landlock: Mediate CAP_SETPCAP for inheritable capabilities

Quoted 70 lines · Günther Noack
Quoted 39 lines · Mickaël Salaün

A process in a domain that denies CAP_SETPCAP could still add capabilities outside of its permitted set to its inheritable set with capset(2), if it held CAP_SETPCAP. cap_capset() checks CAP_SETPCAP with cap_capable() in cap_inh_is_capped(), so the check never reaches hook_capable(). Through file inheritable capabilities, such a set can grant new permitted capabilities on execve() when no_new_privs is not set, which is possible for a domain enforced by a task holding CAP_SYS_ADMIN.

Add a Landlock capset hook that checks CAP_SETPCAP against the domain under the same condition as cap_capset(). As with the mmap_addr hook, LSMs implement their own policy in this hook: SELinux checks capset with its own permission.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
security/landlock/cap.c +2 -0
index 10e1ca772b9c..c89e8d76db8c 100644
@@ -91,6 +91,35 @@ static int hook_capable(const struct cred *cred, struct user_namespace *ns,
 	return check_cap(cred, cap, opts);
 }
 
+/**
+ * hook_capset - Restrict inheritable capability changes

security/landlock/cap.c static int hook_capable(const struct cred *cred, struct user_namespace *ns, · line 105

Quoted 10 lines
security/landlock/cap.c +10 -0
+ *
+ * @new: New credentials (unused).
+ * @old: Current credentials.
+ * @effective: New effective set (unused).
+ * @inheritable: New inheritable set.
+ * @permitted: New permitted set (unused).
+ *
+ * cap_capset() requires CAP_SETPCAP to add inheritable capabilities that are
+ * not in the old permitted set, but calls cap_capable() directly, which skips
+ * hook_capable().

It has taken me a bit of time to wrap my head around this one.

cap_capset() starts with:

	if (cap_inh_is_capped() &&
	    !cap_issubset(*inheritable,
			  cap_combine(old->cap_inheritable,
				      old->cap_permitted)))
		/* incapable of using this inheritable set */
		return -EPERM;

where cap_inh_is_capped() returns true if it does *not* have CAP_SETPCAP.

So when this Landlock hooks gets called, cap_capset() has already checked that we either have CAP_SETPCAP or inheritable ⊆ (old->inheritable ⋃ old->permitted). So the Landlock hook can check for the cap_issubset(...) condition to see whether CAP_SETPCAP had to be "used".

Quoted 7 lines

Maybe it would be easier to phrase it like that?

(A more specific nit about this comment, "calls cap_capable() *directly*" has confused me a bit, since cap_capset() calls cap_capable() only *indirectly* through cap_inh_is_capped(). Maybe "promptly", or "immediately" would be better?)

I agree, the v3 should address your concerns.

Quoted 41 lines
Quoted 33 lines

Check the same condition against the domain. commoncap runs
+ * first, so this only sees requests that commoncap allowed. capset(2) discards
+ * @new if this hook fails, so nothing is committed.
+ *
+ * Return: 0 if allowed, -EPERM if CAP_SETPCAP use is denied.
+ */

security/landlock/cap.c +13 -0
+static int hook_capset(struct cred *new, const struct cred *old,
+		       const kernel_cap_t *effective,
+		       const kernel_cap_t *inheritable,
+		       const kernel_cap_t *permitted)
+{
+	if (cap_issubset(*inheritable,
+			 cap_combine(old->cap_inheritable, old->cap_permitted)))
+		return 0;
+
+	return check_cap(old, CAP_SETPCAP, CAP_OPT_NONE);
+}
+
 /**
  * hook_mmap_addr - Restrict mappings below dac_mmap_min_addr
  *
@@ -113,6 +142,7 @@ static int hook_mmap_addr(unsigned long addr)
 
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
+	LSM_HOOK_INIT(capset, hook_capset),
 	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
 };
 
Signature · 1 line
2.56.0

Code checks out, only minor comments about the documentation. It has taken me a bit to understand how the Landlock hook's logic matches the one in cap_capset().

—Günther

author maintainer
#12 lore raw

PATCH v2 4/6 landlock: Mediate CAP_SYS_ADMIN for the admin memory reserve

In reply to Mickaël Salaün

With vm.overcommit_memory set to 2, __vm_enough_memory() keeps the vm.admin_reserve_kbytes reserve for callers whose LSMs all agree that they hold CAP_SYS_ADMIN. cap_vm_enough_memory() checks it with cap_capable(), so a process in a domain that denies CAP_SYS_ADMIN could still use this reserve, which is meant to let an administrator recover from memory exhaustion.

Add a Landlock vm_enough_memory hook that withholds the reserve when the domain denies CAP_SYS_ADMIN. Like commoncap and SELinux, do not audit this check: it only selects a limit, it runs for every accounted mapping, and withholding the reserve can only make an allocation fail with -ENOMEM. As with the previous hooks, LSMs implement their own policy in this hook: SELinux already checks CAP_SYS_ADMIN in its own vm_enough_memory hook, so making commoncap call security_capable() would make SELinux check it twice.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
security/landlock/cap.c +22 -0
index c89e8d76db8c..c9a900888f3b 100644
@@ -140,10 +140,32 @@ static int hook_mmap_addr(unsigned long addr)
 	return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE);
 }
 
+/**
+ * hook_vm_enough_memory - Restrict the admin memory reserve
+ *
+ * @mm: Address space being charged (unused).
+ * @pages: Number of pages being charged (unused).
+ *
+ * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes
+ * reserve, but calls cap_capable() directly, which skips hook_capable().  Check
+ * the same capability against the domain.  commoncap runs first, so this only
+ * sees tasks that commoncap let use the reserve.  Like commoncap, do not log
+ * denials: this only selects a memory limit.
+ *
+ * Return: 0 if the domain does not withhold the reserve, -EPERM if
+ * CAP_SYS_ADMIN use is denied.  An error does not fail the allocation by
+ * itself, but without the reserve, the allocation may fail with -ENOMEM.
+ */
+static int hook_vm_enough_memory(struct mm_struct *mm, long pages)
+{
+	return check_cap(current_cred(), CAP_SYS_ADMIN, CAP_OPT_NOAUDIT);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
 	LSM_HOOK_INIT(capset, hook_capset),
 	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
+	LSM_HOOK_INIT(vm_enough_memory, hook_vm_enough_memory),
 };
 
 __init void landlock_add_cap_hooks(void)
Signature · 1 line
2.56.0
#13 lore raw

Re: [PATCH v2 4/6] landlock: Mediate CAP_SYS_ADMIN for the admin memory reserve

Sashiko has reviewed this patch and found no issues.
Quoted 16 lines

With vm.overcommit_memory set to 2, __vm_enough_memory() keeps the vm.admin_reserve_kbytes reserve for callers whose LSMs all agree that they hold CAP_SYS_ADMIN. cap_vm_enough_memory() checks it with cap_capable(), so a process in a domain that denies CAP_SYS_ADMIN could still use this reserve, which is meant to let an administrator recover from memory exhaustion.

Add a Landlock vm_enough_memory hook that withholds the reserve when the domain denies CAP_SYS_ADMIN. Like commoncap and SELinux, do not audit this check: it only selects a limit, it runs for every accounted mapping, and withholding the reserve can only make an allocation fail with -ENOMEM. As with the previous hooks, LSMs implement their own policy in this hook: SELinux already checks CAP_SYS_ADMIN in its own vm_enough_memory hook, so making commoncap call security_capable() would make SELinux check it twice.

Quoted 6 lines
Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
reviewer Reviewed-by on v2 4/6
#14 lore raw

Re: [PATCH v2 4/6] landlock: Mediate CAP_SYS_ADMIN for the admin memory reserve

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

With vm.overcommit_memory set to 2, __vm_enough_memory() keeps the vm.admin_reserve_kbytes reserve for callers whose LSMs all agree that they hold CAP_SYS_ADMIN. cap_vm_enough_memory() checks it with cap_capable(), so a process in a domain that denies CAP_SYS_ADMIN could still use this reserve, which is meant to let an administrator recover from memory exhaustion.

Add a Landlock vm_enough_memory hook that withholds the reserve when the domain denies CAP_SYS_ADMIN. Like commoncap and SELinux, do not audit this check: it only selects a limit, it runs for every accounted mapping, and withholding the reserve can only make an allocation fail with -ENOMEM. As with the previous hooks, LSMs implement their own policy in this hook: SELinux already checks CAP_SYS_ADMIN in its own vm_enough_memory hook, so making commoncap call security_capable() would make SELinux check it twice.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 security/landlock/cap.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
security/landlock/cap.c +22 -0
index c89e8d76db8c..c9a900888f3b 100644
@@ -140,10 +140,32 @@ static int hook_mmap_addr(unsigned long addr)
 	return check_cap(current_cred(), CAP_SYS_RAWIO, CAP_OPT_NONE);
 }
 
+/**
+ * hook_vm_enough_memory - Restrict the admin memory reserve
+ *
+ * @mm: Address space being charged (unused).
+ * @pages: Number of pages being charged (unused).
+ *
+ * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes
+ * reserve, but calls cap_capable() directly, which skips hook_capable().  Check
+ * the same capability against the domain.  commoncap runs first, so this only
+ * sees tasks that commoncap let use the reserve.  Like commoncap, do not log
+ * denials: this only selects a memory limit.
+ *
+ * Return: 0 if the domain does not withhold the reserve, -EPERM if
+ * CAP_SYS_ADMIN use is denied.  An error does not fail the allocation by
+ * itself, but without the reserve, the allocation may fail with -ENOMEM.
+ */
+static int hook_vm_enough_memory(struct mm_struct *mm, long pages)
+{
+	return check_cap(current_cred(), CAP_SYS_ADMIN, CAP_OPT_NOAUDIT);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capable, hook_capable),
 	LSM_HOOK_INIT(capset, hook_capset),
 	LSM_HOOK_INIT(mmap_addr, hook_mmap_addr),
+	LSM_HOOK_INIT(vm_enough_memory, hook_vm_enough_memory),
 };
 
 __init void landlock_add_cap_hooks(void)
Signature · 1 line
2.56.0
author maintainer
#15 lore raw

PATCH v2 5/6 selftests/landlock: Test capability checks outside the capable hook

In reply to Mickaël Salaün

Test the capability checks that commoncap makes from LSM hooks other than capable and that the previous commits make Landlock restrict:
mapping below vm.mmap_min_addr (CAP_SYS_RAWIO) and adding inheritable capabilities outside of the permitted set (CAP_SETPCAP).

Each test first checks that the operation fails without the capability, so that it exercises the capability check, and then checks it with the capability effective in four variants: unsandboxed, in a domain that denies the capability, in a domain that allows it, and in a domain that does not handle capabilities. The mmap_addr tests map the last page below vm.mmap_min_addr, and skip if the architecture rejects it before the mmap_addr hook (e.g. 32-bit ARM).

Audit tests check that these denials are logged, that the admin reserve check is not, and that allowed uses log nothing. The admin reserve check has no functional test: it only has an effect with vm.overcommit_memory=2, a system-wide setting that a test cannot change without racing with other processes.

Add CAP_SETPCAP and CAP_SYS_RAWIO to the capabilities that the tests may raise, and drop the stale count from the comment of this list.

Without the mmap_addr and capset fixes, their denied variants and the denial audit test fail.

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Replace the admin reserve test, which changed system-wide overcommit settings and was racy (e.g. with swap, as reported by Sashiko), with a comment.
- Map the last page below vm.mmap_min_addr instead of page 0, and skip when the architecture rejects it, e.g. on 32-bit ARM (reported by Sashiko).
- Mention CAP_SETPCAP in the commit message (reported by Sashiko).
- Add Serge Hallyn's Acked-by.

---
 tools/testing/selftests/landlock/cap_test.c | 336 ++++++++++++++++++++
 tools/testing/selftests/landlock/common.h   |   4 +-
 2 files changed, 339 insertions(+), 1 deletion(-)
tools/testing/selftests/landlock/cap_test.c +336 -0
index 3d7fd02e21ed..39ef57a49dc9 100644
@@ -12,7 +12,9 @@
 #include <linux/landlock.h>
 #include <sched.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
+#include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/wait.h>
 #include <sys/xattr.h>
@@ -738,6 +740,251 @@ TEST(cap_target_userns_independent)
 	EXPECT_EQ(0, close(target_userns_fd));
 }
 
+/*
+ * Capability checks that commoncap makes from hooks other than the capable
+ * hook.  Each test first checks that the operation needs the capability, then
+ * checks it with the capability effective.  Variants cover an unsandboxed
+ * baseline, a domain that denies the capability, a domain that allows it, and a
+ * domain that does not handle capabilities.
+ */
+/* clang-format off */
+FIXTURE(cap_other_hooks) {};
+/* clang-format on */
+
+FIXTURE_VARIANT(cap_other_hooks)
+{
+	const bool is_sandboxed;
+	const bool handle_caps;
+	const bool is_allowed;
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, unsandboxed) {
+	.is_sandboxed = false,
+	.handle_caps = false,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, denied) {
+	.is_sandboxed = true,
+	.handle_caps = true,
+	.is_allowed = false,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, allowed) {
+	.is_sandboxed = true,
+	.handle_caps = true,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, unhandled) {
+	.is_sandboxed = true,
+	.handle_caps = false,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+FIXTURE_SETUP(cap_other_hooks)
+{
+	disable_caps(_metadata);
+}
+
+FIXTURE_TEARDOWN(cap_other_hooks)
+{
+}
+
+/*
+ * Creates a ruleset that handles capabilities and allows @cap if @is_allowed,
+ * or, if !@handle_caps, a ruleset that only handles a filesystem access right.
+ * Returns the ruleset FD, or -1 with errno set.
+ */
+static int create_variant_ruleset(const bool handle_caps, const bool is_allowed,
+				  const int cap)
+{
+	const struct landlock_ruleset_attr fs_attr = {
+		.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE,
+	};
+	int ruleset_fd, err;
+
+	if (!handle_caps)
+		return landlock_create_ruleset(&fs_attr, sizeof(fs_attr), 0);
+
+	ruleset_fd = create_cap_ruleset();
+	if (ruleset_fd < 0 || !is_allowed)
+		return ruleset_fd;
+
+	if (add_cap_rule(ruleset_fd, cap)) {
+		err = errno;
+		close(ruleset_fd);
+		errno = err;
+		return -1;
+	}
+	return ruleset_fd;
+}
+
+static void
+enforce_cap_variant(struct __test_metadata *const _metadata,
+		    const FIXTURE_VARIANT(cap_other_hooks) *const variant,
+		    const int cap)
+{
+	int ruleset_fd;
+
+	if (!variant->is_sandboxed)
+		return;
+
+	ruleset_fd = create_variant_ruleset(variant->handle_caps,
+					    variant->is_allowed, cap);
+	ASSERT_LE(0, ruleset_fd);
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+}
+
+static unsigned long read_sysctl(struct __test_metadata *const _metadata,
+				 const char *const path)
+{
+	char buf[32];
+	ssize_t len;
+	int fd;
+
+	fd = open(path, O_RDONLY | O_CLOEXEC);
+	ASSERT_LE(0, fd)
+	{
+		TH_LOG("Failed to open %s: %s", path, strerror(errno));
+	}
+	len = read(fd, buf, sizeof(buf) - 1);
+	ASSERT_LT(0, len);
+	EXPECT_EQ(0, close(fd));
+
+	buf[len] = '\0';
+	return strtoul(buf, NULL, 10);
+}
+
+/*
+ * Returns the last page below the vm.mmap_min_addr sysctl, or MAP_FAILED if
+ * there is none or if the architecture rejects it before the mmap_addr hook
+ * (e.g. below FIRST_USER_ADDRESS on 32-bit ARM).  The caller must not have
+ * CAP_SYS_RAWIO in its effective set.
+ */
+static void *get_low_page(struct __test_metadata *const _metadata)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	unsigned long min_addr;
+	void *addr, *ret;
+
+	min_addr = read_sysctl(_metadata, "/proc/sys/vm/mmap_min_addr");
+	if (!min_addr)
+		return MAP_FAILED;
+
+	addr = (void *)((min_addr - 1) & ~(page_size - 1));
+	ret = mmap(addr, page_size, PROT_READ,
+		   MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	ASSERT_EQ(MAP_FAILED, ret);
+	if (errno == EINVAL)
+		return MAP_FAILED;
+
+	ASSERT_EQ(EPERM, errno);
+	return addr;
+}
+
+/*
+ * cap_mmap_addr() requires CAP_SYS_RAWIO to map below the vm.mmap_min_addr
+ * sysctl (dac_mmap_min_addr).
+ */
+TEST_F(cap_other_hooks, mmap_min_addr)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	void *low_page, *addr;
+
+	low_page = get_low_page(_metadata);
+	if (low_page == MAP_FAILED)
+		SKIP(return, "Cannot map below vm.mmap_min_addr");
+
+	enforce_cap_variant(_metadata, variant, CAP_SYS_RAWIO);
+
+	addr = mmap(low_page, page_size, PROT_READ,
+		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	EXPECT_EQ(MAP_FAILED, addr);
+	EXPECT_EQ(EPERM, errno);
+
+	set_cap(_metadata, CAP_SYS_RAWIO);
+	addr = mmap(low_page, page_size, PROT_READ,
+		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	if (variant->is_allowed) {
+		EXPECT_EQ(low_page, addr)
+		{
+			TH_LOG("Failed to map below vm.mmap_min_addr: %s",
+			       strerror(errno));
+		}
+		if (addr != MAP_FAILED)
+			EXPECT_EQ(0, munmap(addr, page_size));
+	} else {
+		EXPECT_EQ(MAP_FAILED, addr);
+		EXPECT_EQ(EPERM, errno);
+		if (addr != MAP_FAILED)
+			munmap(addr, page_size);
+	}
+	clear_cap(_metadata, CAP_SYS_RAWIO);
+}
+
+static int add_inheritable_cap(const cap_value_t cap)
+{
+	cap_t cap_p;
+	int ret, err;
+
+	cap_p = cap_get_proc();
+	if (!cap_p)
+		return -1;
+
+	ret = cap_set_flag(cap_p, CAP_INHERITABLE, 1, &cap, CAP_SET);
+	if (!ret)
+		ret = cap_set_proc(cap_p);
+	err = errno;
+	cap_free(cap_p);
+	errno = err;
+	return ret;
+}
+
+/*
+ * cap_capset() requires CAP_SETPCAP to add an inheritable capability that is
+ * not in the permitted set.  CAP_NET_RAW is in the bounding set, but
+ * disable_caps() does not put it in the permitted set.
+ */
+TEST_F(cap_other_hooks, capset_inheritable)
+{
+	enforce_cap_variant(_metadata, variant, CAP_SETPCAP);
+
+	EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+	EXPECT_EQ(EPERM, errno);
+
+	set_cap(_metadata, CAP_SETPCAP);
+	if (variant->is_allowed) {
+		EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW))
+		{
+			TH_LOG("Failed to raise CAP_NET_RAW: %s",
+			       strerror(errno));
+		}
+	} else {
+		EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+		EXPECT_EQ(EPERM, errno);
+	}
+	clear_cap(_metadata, CAP_SETPCAP);
+}
+
+/*
+ * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes
+ * reserve, but only with vm.overcommit_memory=2.  The Landlock check of this
+ * reserve has no functional test: it would have to change these system-wide
+ * settings and set a tight commit limit, which could make allocations of other
+ * processes fail and would race with them.  cap_audit.other_hooks checks that
+ * this check is not logged.
+ */
+
 /* Audit tests */
 
 static int matches_log_cap(int audit_fd, int cap_number)
@@ -828,6 +1075,95 @@ TEST_F(cap_audit, denied)
 	EXPECT_EQ(0, records.domain);
 }
 
+/*
+ * Denials in the capset and mmap_addr paths are audited like capable hook
+ * denials.  The vm_enough_memory hook only withholds the admin reserve, with
+ * CAP_OPT_NOAUDIT, so an accounted mapping made with CAP_SYS_ADMIN effective
+ * leaves no record.
+ */
+TEST_F(cap_audit, other_hooks)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	struct audit_records records = {};
+	void *low_page, *addr;
+	int ruleset_fd;
+	__u64 domain_id;
+
+	low_page = get_low_page(_metadata);
+	ruleset_fd = create_cap_ruleset();
+	ASSERT_LE(0, ruleset_fd);
+	/* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL));
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	set_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+	EXPECT_EQ(EPERM, errno);
+	clear_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP));
+	EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, getpid(),
+						  &domain_id));
+
+	if (low_page != MAP_FAILED) {
+		set_cap(_metadata, CAP_SYS_RAWIO);
+		addr = mmap(low_page, page_size, PROT_READ,
+			    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+		EXPECT_EQ(MAP_FAILED, addr);
+		EXPECT_EQ(EPERM, errno);
+		clear_cap(_metadata, CAP_SYS_RAWIO);
+		EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SYS_RAWIO));
+	}
+
+	set_cap(_metadata, CAP_SYS_ADMIN);
+	addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	EXPECT_NE(MAP_FAILED, addr);
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+	if (addr != MAP_FAILED)
+		EXPECT_EQ(0, munmap(addr, page_size));
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);
+	EXPECT_EQ(0, records.domain);
+}
+
+/* Allowed capability uses in the capset and mmap_addr paths. */
+TEST_F(cap_audit, other_hooks_allowed)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	struct audit_records records = {};
+	void *low_page, *addr;
+	int ruleset_fd;
+
+	low_page = get_low_page(_metadata);
+	ruleset_fd = create_cap_ruleset();
+	ASSERT_LE(0, ruleset_fd);
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SETPCAP));
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SYS_RAWIO));
+	/* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL));
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	set_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW));
+	clear_cap(_metadata, CAP_SETPCAP);
+
+	if (low_page != MAP_FAILED) {
+		set_cap(_metadata, CAP_SYS_RAWIO);
+		addr = mmap(low_page, page_size, PROT_READ,
+			    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+		EXPECT_EQ(low_page, addr);
+		clear_cap(_metadata, CAP_SYS_RAWIO);
+		if (addr != MAP_FAILED)
+			EXPECT_EQ(0, munmap(addr, page_size));
+	}
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);
+}
+
 TEST_F(cap_audit, allowed)
 {
 	struct audit_records records = {};
tools/testing/selftests/landlock/common.h +3 -1
index e29406900c04..a6fdfb422fad 100644
@@ -36,7 +36,7 @@ static const char bin_wait_pipe_sandbox[] = "./wait-pipe-sandbox";
 static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)
 {
 	cap_t cap_p;
-	/* Only these three capabilities are useful for the tests. */
+	/* Only these capabilities are useful for the tests. */
 	const cap_value_t caps[] = {
 		/* clang-format off */
 		CAP_AUDIT_CONTROL,
@@ -44,9 +44,11 @@ static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)
 		CAP_MKNOD,
 		CAP_NET_ADMIN,
 		CAP_NET_BIND_SERVICE,
+		CAP_SETPCAP,
 		CAP_SETUID,
 		CAP_SYS_ADMIN,
 		CAP_SYS_CHROOT,
+		CAP_SYS_RAWIO,
 		/* clang-format on */
 	};
 	const unsigned int noroot = SECBIT_NOROOT | SECBIT_NOROOT_LOCKED;
Signature · 1 line
2.56.0
#16 lore raw

Re: [PATCH v2 5/6] selftests/landlock: Test capability checks outside the capable hook

Sashiko has reviewed this patch and found no issues.
Quoted 22 lines

Test the capability checks that commoncap makes from LSM hooks other than capable and that the previous commits make Landlock restrict:
mapping below vm.mmap_min_addr (CAP_SYS_RAWIO) and adding inheritable capabilities outside of the permitted set (CAP_SETPCAP).

Each test first checks that the operation fails without the capability, so that it exercises the capability check, and then checks it with the capability effective in four variants: unsandboxed, in a domain that denies the capability, in a domain that allows it, and in a domain that does not handle capabilities. The mmap_addr tests map the last page below vm.mmap_min_addr, and skip if the architecture rejects it before the mmap_addr hook (e.g. 32-bit ARM).

Audit tests check that these denials are logged, that the admin reserve check is not, and that allowed uses log nothing. The admin reserve check has no functional test: it only has an effect with vm.overcommit_memory=2, a system-wide setting that a test cannot change without racing with other processes.

Add CAP_SETPCAP and CAP_SYS_RAWIO to the capabilities that the tests may raise, and drop the stale count from the comment of this list.

Quoted 8 lines

Without the mmap_addr and capset fixes, their denied variants and the denial audit test fail.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#17 lore raw

Re: [PATCH v2 5/6] selftests/landlock: Test capability checks outside the capable hook

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

Test the capability checks that commoncap makes from LSM hooks other than capable and that the previous commits make Landlock restrict:
mapping below vm.mmap_min_addr (CAP_SYS_RAWIO) and adding inheritable capabilities outside of the permitted set (CAP_SETPCAP).

Each test first checks that the operation fails without the capability, so that it exercises the capability check, and then checks it with the capability effective in four variants: unsandboxed, in a domain that denies the capability, in a domain that allows it, and in a domain that does not handle capabilities. The mmap_addr tests map the last page below vm.mmap_min_addr, and skip if the architecture rejects it before the mmap_addr hook (e.g. 32-bit ARM).

Audit tests check that these denials are logged, that the admin reserve check is not, and that allowed uses log nothing. The admin reserve check has no functional test: it only has an effect with vm.overcommit_memory=2, a system-wide setting that a test cannot change without racing with other processes.

Add CAP_SETPCAP and CAP_SYS_RAWIO to the capabilities that the tests may raise, and drop the stale count from the comment of this list.

Without the mmap_addr and capset fixes, their denied variants and the denial audit test fail.

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Replace the admin reserve test, which changed system-wide overcommit settings and was racy (e.g. with swap, as reported by Sashiko), with a comment.
- Map the last page below vm.mmap_min_addr instead of page 0, and skip when the architecture rejects it, e.g. on 32-bit ARM (reported by Sashiko).
- Mention CAP_SETPCAP in the commit message (reported by Sashiko).
- Add Serge Hallyn's Acked-by.

---
 tools/testing/selftests/landlock/cap_test.c | 336 ++++++++++++++++++++
 tools/testing/selftests/landlock/common.h   |   4 +-
 2 files changed, 339 insertions(+), 1 deletion(-)
tools/testing/selftests/landlock/cap_test.c +58 -0
index 3d7fd02e21ed..39ef57a49dc9 100644
@@ -12,7 +12,9 @@
 #include <linux/landlock.h>
 #include <sched.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
+#include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/wait.h>
 #include <sys/xattr.h>
@@ -738,6 +740,251 @@ TEST(cap_target_userns_independent)
 	EXPECT_EQ(0, close(target_userns_fd));
 }
 
+/*
+ * Capability checks that commoncap makes from hooks other than the capable
+ * hook.  Each test first checks that the operation needs the capability, then
+ * checks it with the capability effective.  Variants cover an unsandboxed
+ * baseline, a domain that denies the capability, a domain that allows it, and a
+ * domain that does not handle capabilities.
+ */
+/* clang-format off */
+FIXTURE(cap_other_hooks) {};
+/* clang-format on */
+
+FIXTURE_VARIANT(cap_other_hooks)
+{
+	const bool is_sandboxed;
+	const bool handle_caps;
+	const bool is_allowed;
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, unsandboxed) {
+	.is_sandboxed = false,
+	.handle_caps = false,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, denied) {
+	.is_sandboxed = true,
+	.handle_caps = true,
+	.is_allowed = false,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, allowed) {
+	.is_sandboxed = true,
+	.handle_caps = true,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, unhandled) {
+	.is_sandboxed = true,
+	.handle_caps = false,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+FIXTURE_SETUP(cap_other_hooks)
+{
+	disable_caps(_metadata);
+}
+
+FIXTURE_TEARDOWN(cap_other_hooks)

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 808

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+{
+}
+
+/*
+ * Creates a ruleset that handles capabilities and allows @cap if @is_allowed,
+ * or, if !@handle_caps, a ruleset that only handles a filesystem access right.
+ * Returns the ruleset FD, or -1 with errno set.
+ */
+static int create_variant_ruleset(const bool handle_caps, const bool is_allowed,
+				  const int cap)

Nit: Maybe rename "is_allowed" to "allow_caps", so that it's a bit clearer that this only makes sense in the case where caps are also handled. Or maybe just guard it on "cap" being non-zero, and rename that appropriately?

Quoted 107 lines
tools/testing/selftests/landlock/cap_test.c +107 -0
+{
+	const struct landlock_ruleset_attr fs_attr = {
+		.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE,
+	};
+	int ruleset_fd, err;
+
+	if (!handle_caps)
+		return landlock_create_ruleset(&fs_attr, sizeof(fs_attr), 0);
+
+	ruleset_fd = create_cap_ruleset();
+	if (ruleset_fd < 0 || !is_allowed)
+		return ruleset_fd;
+
+	if (add_cap_rule(ruleset_fd, cap)) {
+		err = errno;
+		close(ruleset_fd);
+		errno = err;
+		return -1;
+	}
+	return ruleset_fd;
+}
+
+static void
+enforce_cap_variant(struct __test_metadata *const _metadata,
+		    const FIXTURE_VARIANT(cap_other_hooks) *const variant,
+		    const int cap)
+{
+	int ruleset_fd;
+
+	if (!variant->is_sandboxed)
+		return;
+
+	ruleset_fd = create_variant_ruleset(variant->handle_caps,
+					    variant->is_allowed, cap);
+	ASSERT_LE(0, ruleset_fd);
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+}
+
+static unsigned long read_sysctl(struct __test_metadata *const _metadata,
+				 const char *const path)
+{
+	char buf[32];
+	ssize_t len;
+	int fd;
+
+	fd = open(path, O_RDONLY | O_CLOEXEC);
+	ASSERT_LE(0, fd)
+	{
+		TH_LOG("Failed to open %s: %s", path, strerror(errno));
+	}
+	len = read(fd, buf, sizeof(buf) - 1);
+	ASSERT_LT(0, len);
+	EXPECT_EQ(0, close(fd));
+
+	buf[len] = '\0';
+	return strtoul(buf, NULL, 10);
+}
+
+/*
+ * Returns the last page below the vm.mmap_min_addr sysctl, or MAP_FAILED if
+ * there is none or if the architecture rejects it before the mmap_addr hook
+ * (e.g. below FIRST_USER_ADDRESS on 32-bit ARM).  The caller must not have
+ * CAP_SYS_RAWIO in its effective set.
+ */
+static void *get_low_page(struct __test_metadata *const _metadata)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	unsigned long min_addr;
+	void *addr, *ret;
+
+	min_addr = read_sysctl(_metadata, "/proc/sys/vm/mmap_min_addr");
+	if (!min_addr)
+		return MAP_FAILED;
+
+	addr = (void *)((min_addr - 1) & ~(page_size - 1));
+	ret = mmap(addr, page_size, PROT_READ,
+		   MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	ASSERT_EQ(MAP_FAILED, ret);
+	if (errno == EINVAL)
+		return MAP_FAILED;
+
+	ASSERT_EQ(EPERM, errno);
+	return addr;
+}
+
+/*
+ * cap_mmap_addr() requires CAP_SYS_RAWIO to map below the vm.mmap_min_addr
+ * sysctl (dac_mmap_min_addr).
+ */
+TEST_F(cap_other_hooks, mmap_min_addr)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	void *low_page, *addr;
+
+	low_page = get_low_page(_metadata);
+	if (low_page == MAP_FAILED)
+		SKIP(return, "Cannot map below vm.mmap_min_addr");
+
+	enforce_cap_variant(_metadata, variant, CAP_SYS_RAWIO);
+
+	addr = mmap(low_page, page_size, PROT_READ,
+		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	EXPECT_EQ(MAP_FAILED, addr);
+	EXPECT_EQ(EPERM, errno);
+
+	set_cap(_metadata, CAP_SYS_RAWIO);

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 925

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+	addr = mmap(low_page, page_size, PROT_READ,
+		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	if (variant->is_allowed) {
+		EXPECT_EQ(low_page, addr)
+		{
+			TH_LOG("Failed to map below vm.mmap_min_addr: %s",
+			       strerror(errno));
+		}
+		if (addr != MAP_FAILED)
+			EXPECT_EQ(0, munmap(addr, page_size));

If you used ASSERT(low_page, addr) above, you would not need to check for MAP_FAILED here.

I get the feeling that you are using EXPECT because you want to do the munmap call? Is that strictly necessary? I believe that the tests are running in a fork, so if they mess up their memory mapping, it wouldn't be problematic? (We already have many other cleanups that don't get done properly if an ASSERT fails, e.g. FD closing)

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 928

Quoted 3 lines
tools/testing/selftests/landlock/cap_test.c +3 -0
+	} else {
+		EXPECT_EQ(MAP_FAILED, addr);
+		EXPECT_EQ(EPERM, errno);

Same here.

errno is undefined unless the mmap failed, so the line checking for MAP_FAILED should use ASSERT_EQ IMHO.

Compare my selftest cleanup commit for that at:
https://lore.kernel.org/all/[email protected]/

Quoted 25 lines
tools/testing/selftests/landlock/cap_test.c +25 -0
+		if (addr != MAP_FAILED)
+			munmap(addr, page_size);
+	}
+	clear_cap(_metadata, CAP_SYS_RAWIO);
+}
+
+static int add_inheritable_cap(const cap_value_t cap)
+{
+	cap_t cap_p;
+	int ret, err;
+
+	cap_p = cap_get_proc();
+	if (!cap_p)
+		return -1;
+
+	ret = cap_set_flag(cap_p, CAP_INHERITABLE, 1, &cap, CAP_SET);
+	if (!ret)
+		ret = cap_set_proc(cap_p);
+	err = errno;
+	cap_free(cap_p);
+	errno = err;
+	return ret;
+}
+
+/*

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 963

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+ * cap_capset() requires CAP_SETPCAP to add an inheritable capability that is
+ * not in the permitted set.  CAP_NET_RAW is in the bounding set, but
+ * disable_caps() does not put it in the permitted set.
+ */
+TEST_F(cap_other_hooks, capset_inheritable)
+{
+	enforce_cap_variant(_metadata, variant, CAP_SETPCAP);
+
+	EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+	EXPECT_EQ(EPERM, errno);

Ditto about errno checking and ASSERT.

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 974

Quoted 11 lines
tools/testing/selftests/landlock/cap_test.c +11 -0
+
+	set_cap(_metadata, CAP_SETPCAP);
+	if (variant->is_allowed) {
+		EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW))
+		{
+			TH_LOG("Failed to raise CAP_NET_RAW: %s",
+			       strerror(errno));
+		}
+	} else {
+		EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+		EXPECT_EQ(EPERM, errno);

Also here (errno checking and ASSERT). I'll refrain from commenting on these further below to not spam you, but there are more instances of it below.

Quoted 61 lines
tools/testing/selftests/landlock/cap_test.c +54 -0
+	}
+	clear_cap(_metadata, CAP_SETPCAP);
+}
+
+/*
+ * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes
+ * reserve, but only with vm.overcommit_memory=2.  The Landlock check of this
+ * reserve has no functional test: it would have to change these system-wide
+ * settings and set a tight commit limit, which could make allocations of other
+ * processes fail and would race with them.  cap_audit.other_hooks checks that
+ * this check is not logged.
+ */
+
 /* Audit tests */
 
 static int matches_log_cap(int audit_fd, int cap_number)
@@ -828,6 +1075,95 @@ TEST_F(cap_audit, denied)
 	EXPECT_EQ(0, records.domain);
 }
 
+/*
+ * Denials in the capset and mmap_addr paths are audited like capable hook
+ * denials.  The vm_enough_memory hook only withholds the admin reserve, with
+ * CAP_OPT_NOAUDIT, so an accounted mapping made with CAP_SYS_ADMIN effective
+ * leaves no record.
+ */
+TEST_F(cap_audit, other_hooks)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	struct audit_records records = {};
+	void *low_page, *addr;
+	int ruleset_fd;
+	__u64 domain_id;
+
+	low_page = get_low_page(_metadata);
+	ruleset_fd = create_cap_ruleset();
+	ASSERT_LE(0, ruleset_fd);
+	/* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL));
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	set_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+	EXPECT_EQ(EPERM, errno);
+	clear_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP));
+	EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, getpid(),
+						  &domain_id));
+
+	if (low_page != MAP_FAILED) {
+		set_cap(_metadata, CAP_SYS_RAWIO);
+		addr = mmap(low_page, page_size, PROT_READ,
+			    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+		EXPECT_EQ(MAP_FAILED, addr);
+		EXPECT_EQ(EPERM, errno);
+		clear_cap(_metadata, CAP_SYS_RAWIO);
+		EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SYS_RAWIO));
+	}
+
+	set_cap(_metadata, CAP_SYS_ADMIN);

tools/testing/selftests/landlock/cap_test.c TEST_F(cap_audit, denied) · line 1128

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+	addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	EXPECT_NE(MAP_FAILED, addr);
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+	if (addr != MAP_FAILED)
+		EXPECT_EQ(0, munmap(addr, page_size));
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);
+	EXPECT_EQ(0, records.domain);

Similar problem: "records" is undefined if audit_count_records fails, so audit_count_records should use ASSERT. See
https://lore.kernel.org/all/[email protected]/
which fixes this across all existing tests.

Quoted 26 lines
tools/testing/selftests/landlock/cap_test.c +26 -0
+}
+
+/* Allowed capability uses in the capset and mmap_addr paths. */
+TEST_F(cap_audit, other_hooks_allowed)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	struct audit_records records = {};
+	void *low_page, *addr;
+	int ruleset_fd;
+
+	low_page = get_low_page(_metadata);
+	ruleset_fd = create_cap_ruleset();
+	ASSERT_LE(0, ruleset_fd);
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SETPCAP));
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SYS_RAWIO));
+	/* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL));
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	set_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW));
+	clear_cap(_metadata, CAP_SETPCAP);
+
+	if (low_page != MAP_FAILED) {
+		set_cap(_metadata, CAP_SYS_RAWIO);

tools/testing/selftests/landlock/cap_test.c TEST_F(cap_audit, denied) · line 1164

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+		addr = mmap(low_page, page_size, PROT_READ,
+			    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+		EXPECT_EQ(low_page, addr);
+		clear_cap(_metadata, CAP_SYS_RAWIO);
+		if (addr != MAP_FAILED)
+			EXPECT_EQ(0, munmap(addr, page_size));
+	}
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);

Here as well.

Quoted 33 lines
tools/testing/selftests/landlock/cap_test.c +2 -0
+}
+
 TEST_F(cap_audit, allowed)
 {
 	struct audit_records records = {};
tools/testing/selftests/landlock/common.h +3 -1
index e29406900c04..a6fdfb422fad 100644
@@ -36,7 +36,7 @@ static const char bin_wait_pipe_sandbox[] = "./wait-pipe-sandbox";
 static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)
 {
 	cap_t cap_p;
-	/* Only these three capabilities are useful for the tests. */
+	/* Only these capabilities are useful for the tests. */
 	const cap_value_t caps[] = {
 		/* clang-format off */
 		CAP_AUDIT_CONTROL,
@@ -44,9 +44,11 @@ static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)
 		CAP_MKNOD,
 		CAP_NET_ADMIN,
 		CAP_NET_BIND_SERVICE,
+		CAP_SETPCAP,
 		CAP_SETUID,
 		CAP_SYS_ADMIN,
 		CAP_SYS_CHROOT,
+		CAP_SYS_RAWIO,
 		/* clang-format on */
 	};
 	const unsigned int noroot = SECBIT_NOROOT | SECBIT_NOROOT_LOCKED;
Signature · 1 line
2.56.0
author maintainer
#18 lore raw

Re: [PATCH v2 5/6] selftests/landlock: Test capability checks outside the capable hook

v3 should address your review.

Quoted 487 lines · Günther Noack
Quoted 121 lines · Mickaël Salaün

Test the capability checks that commoncap makes from LSM hooks other than capable and that the previous commits make Landlock restrict:
mapping below vm.mmap_min_addr (CAP_SYS_RAWIO) and adding inheritable capabilities outside of the permitted set (CAP_SETPCAP).

Each test first checks that the operation fails without the capability, so that it exercises the capability check, and then checks it with the capability effective in four variants: unsandboxed, in a domain that denies the capability, in a domain that allows it, and in a domain that does not handle capabilities. The mmap_addr tests map the last page below vm.mmap_min_addr, and skip if the architecture rejects it before the mmap_addr hook (e.g. 32-bit ARM).

Audit tests check that these denials are logged, that the admin reserve check is not, and that allowed uses log nothing. The admin reserve check has no functional test: it only has an effect with vm.overcommit_memory=2, a system-wide setting that a test cannot change without racing with other processes.

Add CAP_SETPCAP and CAP_SYS_RAWIO to the capabilities that the tests may raise, and drop the stale count from the comment of this list.

Without the mmap_addr and capset fixes, their denied variants and the denial audit test fail.

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Replace the admin reserve test, which changed system-wide overcommit settings and was racy (e.g. with swap, as reported by Sashiko), with a comment.
- Map the last page below vm.mmap_min_addr instead of page 0, and skip when the architecture rejects it, e.g. on 32-bit ARM (reported by Sashiko).
- Mention CAP_SETPCAP in the commit message (reported by Sashiko).
- Add Serge Hallyn's Acked-by.

---
 tools/testing/selftests/landlock/cap_test.c | 336 ++++++++++++++++++++
 tools/testing/selftests/landlock/common.h   |   4 +-
 2 files changed, 339 insertions(+), 1 deletion(-)
tools/testing/selftests/landlock/cap_test.c +58 -0
index 3d7fd02e21ed..39ef57a49dc9 100644
@@ -12,7 +12,9 @@
 #include <linux/landlock.h>
 #include <sched.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
+#include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/wait.h>
 #include <sys/xattr.h>
@@ -738,6 +740,251 @@ TEST(cap_target_userns_independent)
 	EXPECT_EQ(0, close(target_userns_fd));
 }
 
+/*
+ * Capability checks that commoncap makes from hooks other than the capable
+ * hook.  Each test first checks that the operation needs the capability, then
+ * checks it with the capability effective.  Variants cover an unsandboxed
+ * baseline, a domain that denies the capability, a domain that allows it, and a
+ * domain that does not handle capabilities.
+ */
+/* clang-format off */
+FIXTURE(cap_other_hooks) {};
+/* clang-format on */
+
+FIXTURE_VARIANT(cap_other_hooks)
+{
+	const bool is_sandboxed;
+	const bool handle_caps;
+	const bool is_allowed;
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, unsandboxed) {
+	.is_sandboxed = false,
+	.handle_caps = false,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, denied) {
+	.is_sandboxed = true,
+	.handle_caps = true,
+	.is_allowed = false,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, allowed) {
+	.is_sandboxed = true,
+	.handle_caps = true,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(cap_other_hooks, unhandled) {
+	.is_sandboxed = true,
+	.handle_caps = false,
+	.is_allowed = true,
+};
+/* clang-format on */
+
+FIXTURE_SETUP(cap_other_hooks)
+{
+	disable_caps(_metadata);
+}
+
+FIXTURE_TEARDOWN(cap_other_hooks)

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 808

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+{
+}
+
+/*
+ * Creates a ruleset that handles capabilities and allows @cap if @is_allowed,
+ * or, if !@handle_caps, a ruleset that only handles a filesystem access right.
+ * Returns the ruleset FD, or -1 with errno set.
+ */
+static int create_variant_ruleset(const bool handle_caps, const bool is_allowed,
+				  const int cap)

Nit: Maybe rename "is_allowed" to "allow_caps", so that it's a bit clearer that this only makes sense in the case where caps are also handled. Or maybe just guard it on "cap" being non-zero, and rename that appropriately?

Quoted 107 lines
tools/testing/selftests/landlock/cap_test.c +107 -0
+{
+	const struct landlock_ruleset_attr fs_attr = {
+		.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE,
+	};
+	int ruleset_fd, err;
+
+	if (!handle_caps)
+		return landlock_create_ruleset(&fs_attr, sizeof(fs_attr), 0);
+
+	ruleset_fd = create_cap_ruleset();
+	if (ruleset_fd < 0 || !is_allowed)
+		return ruleset_fd;
+
+	if (add_cap_rule(ruleset_fd, cap)) {
+		err = errno;
+		close(ruleset_fd);
+		errno = err;
+		return -1;
+	}
+	return ruleset_fd;
+}
+
+static void
+enforce_cap_variant(struct __test_metadata *const _metadata,
+		    const FIXTURE_VARIANT(cap_other_hooks) *const variant,
+		    const int cap)
+{
+	int ruleset_fd;
+
+	if (!variant->is_sandboxed)
+		return;
+
+	ruleset_fd = create_variant_ruleset(variant->handle_caps,
+					    variant->is_allowed, cap);
+	ASSERT_LE(0, ruleset_fd);
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+}
+
+static unsigned long read_sysctl(struct __test_metadata *const _metadata,
+				 const char *const path)
+{
+	char buf[32];
+	ssize_t len;
+	int fd;
+
+	fd = open(path, O_RDONLY | O_CLOEXEC);
+	ASSERT_LE(0, fd)
+	{
+		TH_LOG("Failed to open %s: %s", path, strerror(errno));
+	}
+	len = read(fd, buf, sizeof(buf) - 1);
+	ASSERT_LT(0, len);
+	EXPECT_EQ(0, close(fd));
+
+	buf[len] = '\0';
+	return strtoul(buf, NULL, 10);
+}
+
+/*
+ * Returns the last page below the vm.mmap_min_addr sysctl, or MAP_FAILED if
+ * there is none or if the architecture rejects it before the mmap_addr hook
+ * (e.g. below FIRST_USER_ADDRESS on 32-bit ARM).  The caller must not have
+ * CAP_SYS_RAWIO in its effective set.
+ */
+static void *get_low_page(struct __test_metadata *const _metadata)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	unsigned long min_addr;
+	void *addr, *ret;
+
+	min_addr = read_sysctl(_metadata, "/proc/sys/vm/mmap_min_addr");
+	if (!min_addr)
+		return MAP_FAILED;
+
+	addr = (void *)((min_addr - 1) & ~(page_size - 1));
+	ret = mmap(addr, page_size, PROT_READ,
+		   MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	ASSERT_EQ(MAP_FAILED, ret);
+	if (errno == EINVAL)
+		return MAP_FAILED;
+
+	ASSERT_EQ(EPERM, errno);
+	return addr;
+}
+
+/*
+ * cap_mmap_addr() requires CAP_SYS_RAWIO to map below the vm.mmap_min_addr
+ * sysctl (dac_mmap_min_addr).
+ */
+TEST_F(cap_other_hooks, mmap_min_addr)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	void *low_page, *addr;
+
+	low_page = get_low_page(_metadata);
+	if (low_page == MAP_FAILED)
+		SKIP(return, "Cannot map below vm.mmap_min_addr");
+
+	enforce_cap_variant(_metadata, variant, CAP_SYS_RAWIO);
+
+	addr = mmap(low_page, page_size, PROT_READ,
+		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	EXPECT_EQ(MAP_FAILED, addr);
+	EXPECT_EQ(EPERM, errno);
+
+	set_cap(_metadata, CAP_SYS_RAWIO);

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 925

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+	addr = mmap(low_page, page_size, PROT_READ,
+		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+	if (variant->is_allowed) {
+		EXPECT_EQ(low_page, addr)
+		{
+			TH_LOG("Failed to map below vm.mmap_min_addr: %s",
+			       strerror(errno));
+		}
+		if (addr != MAP_FAILED)
+			EXPECT_EQ(0, munmap(addr, page_size));

If you used ASSERT(low_page, addr) above, you would not need to check for MAP_FAILED here.

I get the feeling that you are using EXPECT because you want to do the munmap call? Is that strictly necessary? I believe that the tests are running in a fork, so if they mess up their memory mapping, it wouldn't be problematic? (We already have many other cleanups that don't get done properly if an ASSERT fails, e.g. FD closing)

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 928

Quoted 3 lines
tools/testing/selftests/landlock/cap_test.c +3 -0
+	} else {
+		EXPECT_EQ(MAP_FAILED, addr);
+		EXPECT_EQ(EPERM, errno);

Same here.

errno is undefined unless the mmap failed, so the line checking for MAP_FAILED should use ASSERT_EQ IMHO.

Compare my selftest cleanup commit for that at:
https://lore.kernel.org/all/[email protected]/

Quoted 25 lines
tools/testing/selftests/landlock/cap_test.c +25 -0
+		if (addr != MAP_FAILED)
+			munmap(addr, page_size);
+	}
+	clear_cap(_metadata, CAP_SYS_RAWIO);
+}
+
+static int add_inheritable_cap(const cap_value_t cap)
+{
+	cap_t cap_p;
+	int ret, err;
+
+	cap_p = cap_get_proc();
+	if (!cap_p)
+		return -1;
+
+	ret = cap_set_flag(cap_p, CAP_INHERITABLE, 1, &cap, CAP_SET);
+	if (!ret)
+		ret = cap_set_proc(cap_p);
+	err = errno;
+	cap_free(cap_p);
+	errno = err;
+	return ret;
+}
+
+/*

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 963

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+ * cap_capset() requires CAP_SETPCAP to add an inheritable capability that is
+ * not in the permitted set.  CAP_NET_RAW is in the bounding set, but
+ * disable_caps() does not put it in the permitted set.
+ */
+TEST_F(cap_other_hooks, capset_inheritable)
+{
+	enforce_cap_variant(_metadata, variant, CAP_SETPCAP);
+
+	EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+	EXPECT_EQ(EPERM, errno);

Ditto about errno checking and ASSERT.

tools/testing/selftests/landlock/cap_test.c TEST(cap_target_userns_independent) · line 974

Quoted 11 lines
tools/testing/selftests/landlock/cap_test.c +11 -0
+
+	set_cap(_metadata, CAP_SETPCAP);
+	if (variant->is_allowed) {
+		EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW))
+		{
+			TH_LOG("Failed to raise CAP_NET_RAW: %s",
+			       strerror(errno));
+		}
+	} else {
+		EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+		EXPECT_EQ(EPERM, errno);

Also here (errno checking and ASSERT). I'll refrain from commenting on these further below to not spam you, but there are more instances of it below.

Quoted 61 lines
tools/testing/selftests/landlock/cap_test.c +54 -0
+	}
+	clear_cap(_metadata, CAP_SETPCAP);
+}
+
+/*
+ * cap_vm_enough_memory() lets CAP_SYS_ADMIN use the vm.admin_reserve_kbytes
+ * reserve, but only with vm.overcommit_memory=2.  The Landlock check of this
+ * reserve has no functional test: it would have to change these system-wide
+ * settings and set a tight commit limit, which could make allocations of other
+ * processes fail and would race with them.  cap_audit.other_hooks checks that
+ * this check is not logged.
+ */
+
 /* Audit tests */
 
 static int matches_log_cap(int audit_fd, int cap_number)
@@ -828,6 +1075,95 @@ TEST_F(cap_audit, denied)
 	EXPECT_EQ(0, records.domain);
 }
 
+/*
+ * Denials in the capset and mmap_addr paths are audited like capable hook
+ * denials.  The vm_enough_memory hook only withholds the admin reserve, with
+ * CAP_OPT_NOAUDIT, so an accounted mapping made with CAP_SYS_ADMIN effective
+ * leaves no record.
+ */
+TEST_F(cap_audit, other_hooks)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	struct audit_records records = {};
+	void *low_page, *addr;
+	int ruleset_fd;
+	__u64 domain_id;
+
+	low_page = get_low_page(_metadata);
+	ruleset_fd = create_cap_ruleset();
+	ASSERT_LE(0, ruleset_fd);
+	/* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL));
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	set_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(-1, add_inheritable_cap(CAP_NET_RAW));
+	EXPECT_EQ(EPERM, errno);
+	clear_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SETPCAP));
+	EXPECT_EQ(0, matches_log_domain_allocated(self->audit_fd, getpid(),
+						  &domain_id));
+
+	if (low_page != MAP_FAILED) {
+		set_cap(_metadata, CAP_SYS_RAWIO);
+		addr = mmap(low_page, page_size, PROT_READ,
+			    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+		EXPECT_EQ(MAP_FAILED, addr);
+		EXPECT_EQ(EPERM, errno);
+		clear_cap(_metadata, CAP_SYS_RAWIO);
+		EXPECT_EQ(0, matches_log_cap(self->audit_fd, CAP_SYS_RAWIO));
+	}
+
+	set_cap(_metadata, CAP_SYS_ADMIN);

tools/testing/selftests/landlock/cap_test.c TEST_F(cap_audit, denied) · line 1128

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+	addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	EXPECT_NE(MAP_FAILED, addr);
+	clear_cap(_metadata, CAP_SYS_ADMIN);
+	if (addr != MAP_FAILED)
+		EXPECT_EQ(0, munmap(addr, page_size));
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);
+	EXPECT_EQ(0, records.domain);

Similar problem: "records" is undefined if audit_count_records fails, so audit_count_records should use ASSERT. See
https://lore.kernel.org/all/[email protected]/
which fixes this across all existing tests.

Quoted 26 lines
tools/testing/selftests/landlock/cap_test.c +26 -0
+}
+
+/* Allowed capability uses in the capset and mmap_addr paths. */
+TEST_F(cap_audit, other_hooks_allowed)
+{
+	const size_t page_size = sysconf(_SC_PAGESIZE);
+	struct audit_records records = {};
+	void *low_page, *addr;
+	int ruleset_fd;
+
+	low_page = get_low_page(_metadata);
+	ruleset_fd = create_cap_ruleset();
+	ASSERT_LE(0, ruleset_fd);
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SETPCAP));
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_SYS_RAWIO));
+	/* Allow CAP_AUDIT_CONTROL for child-side audit cleanup. */
+	ASSERT_EQ(0, add_cap_rule(ruleset_fd, CAP_AUDIT_CONTROL));
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	set_cap(_metadata, CAP_SETPCAP);
+	EXPECT_EQ(0, add_inheritable_cap(CAP_NET_RAW));
+	clear_cap(_metadata, CAP_SETPCAP);
+
+	if (low_page != MAP_FAILED) {
+		set_cap(_metadata, CAP_SYS_RAWIO);

tools/testing/selftests/landlock/cap_test.c TEST_F(cap_audit, denied) · line 1164

Quoted 10 lines
tools/testing/selftests/landlock/cap_test.c +10 -0
+		addr = mmap(low_page, page_size, PROT_READ,
+			    MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+		EXPECT_EQ(low_page, addr);
+		clear_cap(_metadata, CAP_SYS_RAWIO);
+		if (addr != MAP_FAILED)
+			EXPECT_EQ(0, munmap(addr, page_size));
+	}
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);

Here as well.

Quoted 33 lines
tools/testing/selftests/landlock/cap_test.c +2 -0
+}
+
 TEST_F(cap_audit, allowed)
 {
 	struct audit_records records = {};
tools/testing/selftests/landlock/common.h +3 -1
index e29406900c04..a6fdfb422fad 100644
@@ -36,7 +36,7 @@ static const char bin_wait_pipe_sandbox[] = "./wait-pipe-sandbox";
 static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)
 {
 	cap_t cap_p;
-	/* Only these three capabilities are useful for the tests. */
+	/* Only these capabilities are useful for the tests. */
 	const cap_value_t caps[] = {
 		/* clang-format off */
 		CAP_AUDIT_CONTROL,
@@ -44,9 +44,11 @@ static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)
 		CAP_MKNOD,
 		CAP_NET_ADMIN,
 		CAP_NET_BIND_SERVICE,
+		CAP_SETPCAP,
 		CAP_SETUID,
 		CAP_SYS_ADMIN,
 		CAP_SYS_CHROOT,
+		CAP_SYS_RAWIO,
 		/* clang-format on */
 	};
 	const unsigned int noroot = SECBIT_NOROOT | SECBIT_NOROOT_LOCKED;
Signature · 1 line
2.56.0
author maintainer
#19 lore raw

PATCH v2 6/6 landlock: Fix capability restriction documentation

In reply to Mickaël Salaün

Some documented claims about LANDLOCK_PERMISSION_CAPABILITY_USE do not hold for every capability check. Remove them instead of listing their exceptions, and call it a permission instead of a hook.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 Documentation/security/landlock.rst      | 8 ++++----
 Documentation/userspace-api/landlock.rst | 8 ++++----
 include/uapi/linux/landlock.h            | 6 +++---
 3 files changed, 11 insertions(+), 11 deletions(-)
Documentation/security/landlock.rst +4 -4
index d81f1c2cd236..98c2e7139e8d 100644
@@ -8,7 +8,7 @@ Landlock LSM: kernel documentation
 ==================================
 
 :Author: Mickaël Salaün
-:Date: October 2026
+:Date: November 2026
 
 Landlock's goal is to create scoped access-control (i.e. sandboxing).  To
 harden a whole system, this feature should be available to any process,
@@ -359,9 +359,9 @@ framework in ``log.c``, compiled under ``CONFIG_SECURITY_LANDLOCK_LOG``
 (automatically selected by ``CONFIG_AUDIT`` or ``CONFIG_TRACEPOINTS``).
 
 Audit records respect audit configuration, the domain's Landlock log
-flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire unconditionally,
-independent of these settings.  The denial counter (``num_denials``) is
-always incremented regardless of logging configuration.
+flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire independently of
+these settings.  The denial counter (``num_denials``) is
+incremented regardless of logging configuration.
 
 Each denial tracepoint carries a ``logged`` field reporting the
 audit-logging verdict: whether the denial would be written to the audit
Documentation/userspace-api/landlock.rst +4 -4
index 3d45b956b640..d00e94d8ed37 100644
@@ -8,7 +8,7 @@ Landlock: unprivileged access control
 =====================================
 
 :Author: Mickaël Salaün
-:Date: October 2026
+:Date: November 2026
 
 The goal of Landlock is to enable restriction of ambient rights (e.g. global
 filesystem or network access) for a set of processes.  Because Landlock
@@ -532,7 +532,7 @@ acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`.  Namespaces
 the process is already a member of when the domain is enforced are implicitly
 allowed (the process could not continue running otherwise); rules describe
 which new namespace types the process may acquire.
-``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates every exercise of a capability
+``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates the exercise of capabilities
 after the domain is enforced, regardless
 of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER``
 grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.).  Configuring
@@ -641,9 +641,9 @@ after a domain is enforced through user namespace entry or :manpage:`capset(2)`;
 privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain
 capabilities through :manpage:`execve(2)` of binaries with file capabilities.
 In all cases, :manpage:`capget(2)` will report the credential's capability sets,
-but any denied capability will fail with ``EPERM`` when exercised.  Do not rely
+but any denied capability will fail when exercised.  Do not rely
 on :manpage:`capget(2)` to determine whether the policy permits a given
-capability; only the actual operation will return ``EPERM`` upon denial.
+capability.
 
 Truncating files
 ----------------
include/uapi/linux/landlock.h +3 -3
index 24510e5d8479..c9e4ce23778b 100644
@@ -622,9 +622,9 @@ struct landlock_capability_attr {
  * - %LANDLOCK_PERMISSION_CAPABILITY_USE: Restrict the use of specific Linux
  *   capabilities.  A process in a Landlock domain that handles this permission
  *   is denied from exercising capabilities that are not explicitly allowed by a
- *   %LANDLOCK_RULE_CAPABILITY rule.  This hook is purely restrictive: it can
- *   deny capabilities that the kernel would otherwise grant, but it can never
- *   grant capabilities that the kernel already denied.  Support added in
+ *   %LANDLOCK_RULE_CAPABILITY rule.  This permission is purely restrictive: it
+ *   can deny capabilities that the kernel would otherwise grant, but it can
+ *   never grant capabilities that the kernel already denied.  Support added in
  *   Landlock ABI version 12.
  */
 #define LANDLOCK_PERMISSION_NAMESPACE_USE			(1ULL << 0)
Signature · 1 line
2.56.0
#20 lore raw

Re: [PATCH v2 6/6] landlock: Fix capability restriction documentation

Sashiko has reviewed this patch and found no issues.
Quoted 10 lines

Some documented claims about LANDLOCK_PERMISSION_CAPABILITY_USE do not hold for every capability check. Remove them instead of listing their exceptions, and call it a permission instead of a hook.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
reviewer Reviewed-by on v2 6/6
#21 lore raw

Re: [PATCH v2 6/6] landlock: Fix capability restriction documentation

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

Some documented claims about LANDLOCK_PERMISSION_CAPABILITY_USE do not hold for every capability check. Remove them instead of listing their exceptions, and call it a permission instead of a hook.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 Documentation/security/landlock.rst      | 8 ++++----
 Documentation/userspace-api/landlock.rst | 8 ++++----
 include/uapi/linux/landlock.h            | 6 +++---
 3 files changed, 11 insertions(+), 11 deletions(-)
Documentation/security/landlock.rst +4 -4
index d81f1c2cd236..98c2e7139e8d 100644
@@ -8,7 +8,7 @@ Landlock LSM: kernel documentation
 ==================================
 
 :Author: Mickaël Salaün
-:Date: October 2026
+:Date: November 2026
 
 Landlock's goal is to create scoped access-control (i.e. sandboxing).  To
 harden a whole system, this feature should be available to any process,
@@ -359,9 +359,9 @@ framework in ``log.c``, compiled under ``CONFIG_SECURITY_LANDLOCK_LOG``
 (automatically selected by ``CONFIG_AUDIT`` or ``CONFIG_TRACEPOINTS``).
 
 Audit records respect audit configuration, the domain's Landlock log
-flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire unconditionally,
-independent of these settings.  The denial counter (``num_denials``) is
-always incremented regardless of logging configuration.
+flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire independently of
+these settings.  The denial counter (``num_denials``) is
+incremented regardless of logging configuration.
 
 Each denial tracepoint carries a ``logged`` field reporting the
 audit-logging verdict: whether the denial would be written to the audit
Documentation/userspace-api/landlock.rst +4 -4
index 3d45b956b640..d00e94d8ed37 100644
@@ -8,7 +8,7 @@ Landlock: unprivileged access control
 =====================================
 
 :Author: Mickaël Salaün
-:Date: October 2026
+:Date: November 2026
 
 The goal of Landlock is to enable restriction of ambient rights (e.g. global
 filesystem or network access) for a set of processes.  Because Landlock
@@ -532,7 +532,7 @@ acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`.  Namespaces
 the process is already a member of when the domain is enforced are implicitly
 allowed (the process could not continue running otherwise); rules describe
 which new namespace types the process may acquire.
-``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates every exercise of a capability
+``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates the exercise of capabilities
 after the domain is enforced, regardless
 of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER``
 grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.).  Configuring
@@ -641,9 +641,9 @@ after a domain is enforced through user namespace entry or :manpage:`capset(2)`;
 privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain
 capabilities through :manpage:`execve(2)` of binaries with file capabilities.
 In all cases, :manpage:`capget(2)` will report the credential's capability sets,
-but any denied capability will fail with ``EPERM`` when exercised.  Do not rely
+but any denied capability will fail when exercised.  Do not rely
 on :manpage:`capget(2)` to determine whether the policy permits a given
-capability; only the actual operation will return ``EPERM`` upon denial.
+capability.
 
 Truncating files
 ----------------
include/uapi/linux/landlock.h +0 -0
index 24510e5d8479..c9e4ce23778b 100644

include/uapi/linux/landlock.h struct landlock_capability_attr { · line 625

Quoted 7 lines
include/uapi/linux/landlock.h +1 -3
@@ -622,9 +622,9 @@ struct landlock_capability_attr {
  * - %LANDLOCK_PERMISSION_CAPABILITY_USE: Restrict the use of specific Linux
  *   capabilities.  A process in a Landlock domain that handles this permission
  *   is denied from exercising capabilities that are not explicitly allowed by a
- *   %LANDLOCK_RULE_CAPABILITY rule.  This hook is purely restrictive: it can
- *   deny capabilities that the kernel would otherwise grant, but it can never
- *   grant capabilities that the kernel already denied.  Support added in
+ *   %LANDLOCK_RULE_CAPABILITY rule.  This permission is purely restrictive: it

"The permission is purely restrictive"... that sounds like an oxymoron, similar for "[The permission] can deny capabilities..." in the sentence below.

It is not complicated though; How about just shortening the sentences "This hook is purely restrictive: it can deny ..., but it can never grant capabilities that the kernel already denied" down to

Landlock only reduces the capabilities that processes can use. It does not let processes use capabilities that they don't already have without Landlock.

?

Quoted 8 lines
include/uapi/linux/landlock.h +2 -0
+ *   can deny capabilities that the kernel would otherwise grant, but it can
+ *   never grant capabilities that the kernel already denied.  Support added in
  *   Landlock ABI version 12.
  */
 #define LANDLOCK_PERMISSION_NAMESPACE_USE			(1ULL << 0)
Signature · 1 line
2.56.0
author maintainer
#22 lore raw

Re: [PATCH v2 6/6] landlock: Fix capability restriction documentation

Quoted 99 lines · Günther Noack
Quoted 86 lines · Mickaël Salaün

Some documented claims about LANDLOCK_PERMISSION_CAPABILITY_USE do not hold for every capability check. Remove them instead of listing their exceptions, and call it a permission instead of a hook.

Cc Günther Noack <[email protected]>
Cc Paul Moore <[email protected]>
Cc Serge Hallyn <[email protected]>
Fixes 97c8386f1d74 ("landlock: Enforce capability restrictions")

---

Changes since v1:
https://patch.msgid.link/[email protected]
- Add Serge Hallyn's Acked-by.

---
 Documentation/security/landlock.rst      | 8 ++++----
 Documentation/userspace-api/landlock.rst | 8 ++++----
 include/uapi/linux/landlock.h            | 6 +++---
 3 files changed, 11 insertions(+), 11 deletions(-)
Documentation/security/landlock.rst +4 -4
index d81f1c2cd236..98c2e7139e8d 100644
@@ -8,7 +8,7 @@ Landlock LSM: kernel documentation
 ==================================
 
 :Author: Mickaël Salaün
-:Date: October 2026
+:Date: November 2026
 
 Landlock's goal is to create scoped access-control (i.e. sandboxing).  To
 harden a whole system, this feature should be available to any process,
@@ -359,9 +359,9 @@ framework in ``log.c``, compiled under ``CONFIG_SECURITY_LANDLOCK_LOG``
 (automatically selected by ``CONFIG_AUDIT`` or ``CONFIG_TRACEPOINTS``).
 
 Audit records respect audit configuration, the domain's Landlock log
-flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire unconditionally,
-independent of these settings.  The denial counter (``num_denials``) is
-always incremented regardless of logging configuration.
+flags, and ``LANDLOCK_LOG_DISABLED``.  Tracepoints fire independently of
+these settings.  The denial counter (``num_denials``) is
+incremented regardless of logging configuration.
 
 Each denial tracepoint carries a ``logged`` field reporting the
 audit-logging verdict: whether the denial would be written to the audit
Documentation/userspace-api/landlock.rst +4 -4
index 3d45b956b640..d00e94d8ed37 100644
@@ -8,7 +8,7 @@ Landlock: unprivileged access control
 =====================================
 
 :Author: Mickaël Salaün
-:Date: October 2026
+:Date: November 2026
 
 The goal of Landlock is to enable restriction of ambient rights (e.g. global
 filesystem or network access) for a set of processes.  Because Landlock
@@ -532,7 +532,7 @@ acquisition via :manpage:`open_tree(2)` / :manpage:`fsmount(2)`.  Namespaces
 the process is already a member of when the domain is enforced are implicitly
 allowed (the process could not continue running otherwise); rules describe
 which new namespace types the process may acquire.
-``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates every exercise of a capability
+``LANDLOCK_PERMISSION_CAPABILITY_USE`` gates the exercise of capabilities
 after the domain is enforced, regardless
 of how the capability was obtained (inherited credentials, ``CLONE_NEWUSER``
 grant, ``setuid``/file-cap-bearing :manpage:`execve(2)`, etc.).  Configuring
@@ -641,9 +641,9 @@ after a domain is enforced through user namespace entry or :manpage:`capset(2)`;
 privileged sandboxes that did not set ``PR_SET_NO_NEW_PRIVS`` may also gain
 capabilities through :manpage:`execve(2)` of binaries with file capabilities.
 In all cases, :manpage:`capget(2)` will report the credential's capability sets,
-but any denied capability will fail with ``EPERM`` when exercised.  Do not rely
+but any denied capability will fail when exercised.  Do not rely
 on :manpage:`capget(2)` to determine whether the policy permits a given
-capability; only the actual operation will return ``EPERM`` upon denial.
+capability.
 
 Truncating files
 ----------------
include/uapi/linux/landlock.h +0 -0
index 24510e5d8479..c9e4ce23778b 100644

include/uapi/linux/landlock.h struct landlock_capability_attr { · line 625

Quoted 7 lines
include/uapi/linux/landlock.h +1 -3
@@ -622,9 +622,9 @@ struct landlock_capability_attr {
  * - %LANDLOCK_PERMISSION_CAPABILITY_USE: Restrict the use of specific Linux
  *   capabilities.  A process in a Landlock domain that handles this permission
  *   is denied from exercising capabilities that are not explicitly allowed by a
- *   %LANDLOCK_RULE_CAPABILITY rule.  This hook is purely restrictive: it can
- *   deny capabilities that the kernel would otherwise grant, but it can never
- *   grant capabilities that the kernel already denied.  Support added in
+ *   %LANDLOCK_RULE_CAPABILITY rule.  This permission is purely restrictive: it

"The permission is purely restrictive"... that sounds like an oxymoron, similar for "[The permission] can deny capabilities..." in the sentence below.

Quoted 7 lines

It is not complicated though; How about just shortening the sentences "This hook is purely restrictive: it can deny ..., but it can never grant capabilities that the kernel already denied" down to

Landlock only reduces the capabilities that processes can use. It does not let processes use capabilities that they don't already have without Landlock.

Much better, thanks!

Quoted 14 lines

?

Quoted 8 lines
include/uapi/linux/landlock.h +2 -0
+ *   can deny capabilities that the kernel would otherwise grant, but it can
+ *   never grant capabilities that the kernel already denied.  Support added in
  *   Landlock ABI version 12.
  */
 #define LANDLOCK_PERMISSION_NAMESPACE_USE			(1ULL << 0)
Signature · 1 line
2.56.0