linux-security-module.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH 0/2] selftests/yama: add ptrace_scope and PR_SET_PTRACER tests
@ 2026-11-25 12:59 Guicai Ma
  2026-11-25 12:59 ` [PATCH 1/2] selftests/yama: add ptrace_scope selftests Guicai Ma
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: Guicai Ma @ 2026-11-25 12:59 UTC (permalink / raw)
  To: Kees Cook, Shuah Khan, linux-kselftest, linux-kernel
  Cc: linux-security-module, Paul Moore

Yama has no selftest coverage.  This series adds a new selftests/yama
directory: 1/2 provides the scaffolding and covers the ptrace_scope
sysctl and the attach matrix, 2/2 adds the PR_SET_PTRACER exception
tests.

The PR_SET_PTRACER lifecycle tests exercise the same grant, replacement
and revocation semantics as the recent tracer-lifetime fix linked below,
and pass both on mainline and with that fix applied.

Scope 3 is irreversible until reboot, so it is only tested when
ptrace_scope is already 3, or when YAMA_TEST_NO_ATTACH=1 opts in.
Privileged cases are skipped when the capability set does not allow
them, so the tests also run in restricted containers.

Tested on arm64 (QEMU/KVM, KASAN + lockdep): 10 rounds of both binaries
as root and as an unprivileged user, plus a final ptrace_scope=3 pass;
a boot with lsm=capability verifies that every test skips cleanly when
Yama is inactive.

Link: https://lore.kernel.org/r/20261123165357.4092273-1-bsdhenrymartin@gmail.com

Guicai Ma (2):
  selftests/yama: add ptrace_scope selftests
  selftests/yama: add PR_SET_PTRACER tests

 MAINTAINERS                                   |   1 +
 tools/testing/selftests/Makefile              |   1 +
 tools/testing/selftests/yama/.gitignore       |   3 +
 tools/testing/selftests/yama/Makefile         |  13 +
 tools/testing/selftests/yama/common.h         | 233 +++++++++
 tools/testing/selftests/yama/config           |   4 +
 .../selftests/yama/ptrace_scope_test.c        | 452 ++++++++++++++++++
 tools/testing/selftests/yama/ptracer_test.c   | 403 ++++++++++++++++
 8 files changed, 1110 insertions(+)
 create mode 100644 tools/testing/selftests/yama/.gitignore
 create mode 100644 tools/testing/selftests/yama/Makefile
 create mode 100644 tools/testing/selftests/yama/common.h
 create mode 100644 tools/testing/selftests/yama/config
 create mode 100644 tools/testing/selftests/yama/ptrace_scope_test.c
 create mode 100644 tools/testing/selftests/yama/ptracer_test.c

-- 
2.47.3

^ permalink raw reply	[flat|nested] 4+ messages in thread

* [PATCH 1/2] selftests/yama: add ptrace_scope selftests
  2026-11-25 12:59 [PATCH 0/2] selftests/yama: add ptrace_scope and PR_SET_PTRACER tests Guicai Ma
@ 2026-11-25 12:59 ` Guicai Ma
  2026-11-25 12:59 ` [PATCH 2/2] selftests/yama: add PR_SET_PTRACER tests Guicai Ma
  2026-11-25 13:06 ` [PATCH 0/2] selftests/yama: add ptrace_scope and " sashiko-bot
  2 siblings, 0 replies; 4+ messages in thread
From: Guicai Ma @ 2026-11-25 12:59 UTC (permalink / raw)
  To: Kees Cook, Shuah Khan, linux-kselftest, linux-kernel
  Cc: linux-security-module, Paul Moore

Yama has no selftest coverage.  Add a selftests/yama
directory covering the ptrace_scope sysctl and its attach rules.

Test the sysctl access rules (EACCES for unprivileged writers, EPERM
for UID 0 without CAP_SYS_PTRACE, EINVAL for out-of-range values).
The PTRACE_ATTACH and PTRACE_TRACEME matrix for scopes 0, 1 and 2
covers parent to child, child to parent, unprivileged siblings, a
CAP_SYS_PTRACE holder tracing a non-descendant, and children asking
an unprivileged or CAP_SYS_PTRACE parent to trace them.

Scope 3 denies every attach and is irreversible until reboot, so it
is only tested when already active or when YAMA_TEST_NO_ATTACH=1
opts in.

Every forked helper reports readiness once its credentials are in
place, and the parent waits for that before any ptrace attempt, so
no result depends on child scheduling.  Privileged cases are skipped
when the capability set does not allow them, so the tests also run
in restricted environments.

Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
---
 MAINTAINERS                                   |   1 +
 tools/testing/selftests/Makefile              |   1 +
 tools/testing/selftests/yama/.gitignore       |   2 +
 tools/testing/selftests/yama/Makefile         |  11 +
 tools/testing/selftests/yama/common.h         | 233 +++++++++
 tools/testing/selftests/yama/config           |   4 +
 .../selftests/yama/ptrace_scope_test.c        | 452 ++++++++++++++++++
 7 files changed, 704 insertions(+)
 create mode 100644 tools/testing/selftests/yama/.gitignore
 create mode 100644 tools/testing/selftests/yama/Makefile
 create mode 100644 tools/testing/selftests/yama/common.h
 create mode 100644 tools/testing/selftests/yama/config
 create mode 100644 tools/testing/selftests/yama/ptrace_scope_test.c

diff --git a/MAINTAINERS b/MAINTAINERS
index d738990161bd..aacab71a5400 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -30887,6 +30887,7 @@ S:	Supported
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux.git for-next/hardening
 F:	Documentation/admin-guide/LSM/Yama.rst
 F:	security/yama/
+F:	tools/testing/selftests/yama/
 
 YAML NETLINK (YNL)
 M:	Donald Hunter <donald.hunter@gmail.com>
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04..1f83d2ddd2eb 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -150,6 +150,7 @@ TARGETS += mm
 TARGETS += vfio
 TARGETS += x86
 TARGETS += x86/bugs
+TARGETS += yama
 TARGETS += zram
 #Please keep the TARGETS list alphabetically sorted
 # Run "make quicktest=1 run_tests" or
diff --git a/tools/testing/selftests/yama/.gitignore b/tools/testing/selftests/yama/.gitignore
new file mode 100644
index 000000000000..6ffe677a8695
--- /dev/null
+++ b/tools/testing/selftests/yama/.gitignore
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0
+ptrace_scope_test
diff --git a/tools/testing/selftests/yama/Makefile b/tools/testing/selftests/yama/Makefile
new file mode 100644
index 000000000000..f0dd1ed89d20
--- /dev/null
+++ b/tools/testing/selftests/yama/Makefile
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# First run: make -C ../../../.. headers_install
+
+CFLAGS += -Wall -O2 $(KHDR_INCLUDES)
+
+LOCAL_HDRS += common.h
+
+TEST_GEN_PROGS := ptrace_scope_test
+
+include ../lib.mk
diff --git a/tools/testing/selftests/yama/common.h b/tools/testing/selftests/yama/common.h
new file mode 100644
index 000000000000..80d2b9427d25
--- /dev/null
+++ b/tools/testing/selftests/yama/common.h
@@ -0,0 +1,233 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Shared helpers for the Yama selftests.
+ */
+#ifndef YAMA_COMMON_H
+#define YAMA_COMMON_H
+
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/capability.h>
+#include <linux/prctl.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/ptrace.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#define YAMA_SYSCTL_PATH "/proc/sys/kernel/yama/ptrace_scope"
+#define UNPRIV_UID 65534
+
+/* Matches the enum in security/yama/yama_lsm.c. */
+enum yama_scope {
+	YAMA_SCOPE_DISABLED = 0,
+	YAMA_SCOPE_RELATIONAL,
+	YAMA_SCOPE_CAPABILITY,
+	YAMA_SCOPE_NO_ATTACH,
+};
+
+/* ---- ptrace_scope sysctl ---- */
+
+static inline int read_ptrace_scope(int *scope)
+{
+	char buf[16];
+	char *end;
+	long val;
+	ssize_t n;
+	int fd;
+	int rc;
+
+	fd = open(YAMA_SYSCTL_PATH, O_RDONLY);
+	if (fd < 0)
+		return -errno;
+	n = read(fd, buf, sizeof(buf) - 1);
+	rc = n < 0 ? -errno : 0;
+	close(fd);
+	if (rc)
+		return rc;
+	buf[n] = '\0';
+
+	errno = 0;
+	val = strtol(buf, &end, 10);
+	if (errno || end == buf || (*end != '\n' && *end != '\0'))
+		return -EINVAL;
+	*scope = (int)val;
+	return 0;
+}
+
+static inline int write_ptrace_scope_str(const char *str)
+{
+	size_t len = strlen(str);
+	ssize_t n;
+	int fd;
+	int rc;
+
+	fd = open(YAMA_SYSCTL_PATH, O_WRONLY);
+	if (fd < 0)
+		return -errno;
+	n = write(fd, str, len);
+	rc = n < 0 ? -errno : (n == (ssize_t)len ? 0 : -EIO);
+	close(fd);
+	return rc;
+}
+
+static inline int write_ptrace_scope(int scope)
+{
+	char buf[16];
+
+	snprintf(buf, sizeof(buf), "%d\n", scope);
+	return write_ptrace_scope_str(buf);
+}
+
+/* ---- capabilities ---- */
+
+/* Check the effective capability mask of the current task. */
+static inline bool has_cap(int cap)
+{
+	struct __user_cap_header_struct hdr = {
+		.version = _LINUX_CAPABILITY_VERSION_3,
+	};
+	struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3] = {};
+
+	if (syscall(__NR_capget, &hdr, data) < 0)
+		return false;
+	return data[CAP_TO_INDEX(cap)].effective & CAP_TO_MASK(cap);
+}
+
+static inline bool has_cap_sys_ptrace(void)
+{
+	return has_cap(CAP_SYS_PTRACE);
+}
+
+/*
+ * Test children drop to UNPRIV_UID, which a UID 0 task can only do
+ * with CAP_SETUID and CAP_SETGID (containers often run UID 0 with a
+ * reduced capability set).
+ */
+static inline bool can_drop_unpriv(void)
+{
+	return geteuid() != 0 ||
+	       (has_cap(CAP_SETUID) && has_cap(CAP_SETGID));
+}
+
+/* The CAP_SYS_PTRACE cases need the capability and droppable children. */
+static inline bool can_test_cap_ptrace(void)
+{
+	return geteuid() == 0 && has_cap_sys_ptrace() && can_drop_unpriv();
+}
+
+/* ---- credentials ---- */
+
+static inline int set_caps_mask(uint32_t mask)
+{
+	struct __user_cap_header_struct hdr = {
+		.version = _LINUX_CAPABILITY_VERSION_3,
+	};
+	struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3] = {};
+
+	data[0].effective = mask;
+	data[0].permitted = mask;
+	if (syscall(__NR_capset, &hdr, data) < 0)
+		return -errno;
+	return 0;
+}
+
+/*
+ * Dropping UIDs clears the dumpable flag, which would make the DAC
+ * checks in ptrace_may_access() fail before Yama runs, so restore it
+ * afterwards.
+ */
+static inline int drop_unpriv(void)
+{
+	if (geteuid() == 0 &&
+	    (setresgid(UNPRIV_UID, UNPRIV_UID, UNPRIV_UID) < 0 ||
+	     setresuid(UNPRIV_UID, UNPRIV_UID, UNPRIV_UID) < 0))
+		return -errno;
+	if (set_caps_mask(0) < 0)
+		return -errno;
+	if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0)
+		return -errno;
+	return 0;
+}
+
+/* ---- process helpers ---- */
+
+/* Pipe I/O with EINTR retry; return a negative errno on failure. */
+static inline int read_full(int fd, void *buf, size_t len)
+{
+	uint8_t *p = buf;
+
+	while (len) {
+		ssize_t n = read(fd, p, len);
+
+		if (n < 0) {
+			if (errno == EINTR)
+				continue;
+			return -errno;
+		}
+		if (!n)
+			return -EIO;
+		p += n;
+		len -= n;
+	}
+	return 0;
+}
+
+static inline int write_full(int fd, const void *buf, size_t len)
+{
+	const uint8_t *p = buf;
+
+	while (len) {
+		ssize_t n = write(fd, p, len);
+
+		if (n < 0) {
+			if (errno == EINTR)
+				continue;
+			return -errno;
+		}
+		if (!n)
+			return -EIO;
+		p += n;
+		len -= n;
+	}
+	return 0;
+}
+
+/* Wait for a child and return its exit status as a negative errno. */
+static inline int wait_result(pid_t pid)
+{
+	int status;
+
+	while (waitpid(pid, &status, 0) < 0) {
+		if (errno != EINTR)
+			return -errno;
+	}
+	if (!WIFEXITED(status))
+		return -EFAULT;
+	return -WEXITSTATUS(status);
+}
+
+static inline int try_attach(pid_t target)
+{
+	int status;
+
+	if (ptrace(PTRACE_ATTACH, target, NULL, NULL) < 0)
+		return -errno;
+	while (waitpid(target, &status, 0) < 0) {
+		if (errno != EINTR) {
+			ptrace(PTRACE_DETACH, target, NULL, NULL);
+			return -errno;
+		}
+	}
+	if (ptrace(PTRACE_DETACH, target, NULL, NULL) < 0)
+		return -errno;
+	return 0;
+}
+
+#endif /* YAMA_COMMON_H */
diff --git a/tools/testing/selftests/yama/config b/tools/testing/selftests/yama/config
new file mode 100644
index 000000000000..aa19bccbfcaf
--- /dev/null
+++ b/tools/testing/selftests/yama/config
@@ -0,0 +1,4 @@
+CONFIG_PROC_FS=y
+CONFIG_PROC_SYSCTL=y
+CONFIG_SECURITY=y
+CONFIG_SECURITY_YAMA=y
diff --git a/tools/testing/selftests/yama/ptrace_scope_test.c b/tools/testing/selftests/yama/ptrace_scope_test.c
new file mode 100644
index 000000000000..0abfd21c246f
--- /dev/null
+++ b/tools/testing/selftests/yama/ptrace_scope_test.c
@@ -0,0 +1,452 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * ptrace_scope selftests for the Yama LSM.
+ *
+ * Every forked helper reports readiness once its credentials are in
+ * place, and the parent waits for that before any ptrace attempt, so
+ * no result depends on child scheduling.
+ */
+#include "kselftest_harness.h"
+#include "common.h"
+
+/* Credential setups for forked children. */
+enum {
+	CRED_UNPRIV,		/* unprivileged UID, no capabilities */
+	CRED_UID0_NOCAP,	/* UID 0, no capabilities */
+	CRED_CAP_PTRACE,	/* unprivileged UID, CAP_SYS_PTRACE */
+};
+
+/* Keep CAP_SYS_PTRACE across the drop to an unprivileged UID. */
+static int drop_unpriv_keep_ptrace(void)
+{
+	if (geteuid() != 0)
+		return -EPERM;
+	if (prctl(PR_SET_KEEPCAPS, 1L, 0, 0, 0) < 0 ||
+	    setresgid(UNPRIV_UID, UNPRIV_UID, UNPRIV_UID) < 0 ||
+	    setresuid(UNPRIV_UID, UNPRIV_UID, UNPRIV_UID) < 0)
+		return -errno;
+	if (set_caps_mask(1U << CAP_SYS_PTRACE) < 0)
+		return -errno;
+	if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0)
+		return -errno;
+	return 0;
+}
+
+static int setup_cred(int cred)
+{
+	switch (cred) {
+	case CRED_UID0_NOCAP:
+		return set_caps_mask(0);
+	case CRED_CAP_PTRACE:
+		return drop_unpriv_keep_ptrace();
+	default:
+		return drop_unpriv();
+	}
+}
+
+static int attach_fn(void *arg)
+{
+	return try_attach(*(pid_t *)arg);
+}
+
+/*
+ * Fork a short-lived child that sets up @cred, reports readiness, then
+ * waits for a release byte on *go before running fn(arg) (or exiting
+ * immediately when fn is NULL).  The child exits with the negative
+ * errno result of fn().
+ */
+static pid_t fork_helper(int cred, int (*fn)(void *), void *arg, int *go)
+{
+	char b;
+	int ready[2], release[2];
+	pid_t pid;
+	int rc;
+
+	if (pipe(ready) < 0)
+		return -errno;
+	if (pipe(release) < 0) {
+		rc = -errno;
+		close(ready[0]);
+		close(ready[1]);
+		return rc;
+	}
+	pid = fork();
+	if (pid < 0) {
+		rc = -errno;
+		close(ready[0]);
+		close(ready[1]);
+		close(release[0]);
+		close(release[1]);
+		return rc;
+	}
+	if (pid == 0) {
+		close(ready[0]);
+		close(release[1]);
+		rc = setup_cred(cred);
+		if (rc < 0)
+			_exit(-rc);
+		if (write_full(ready[1], "1", 1) < 0)
+			_exit(EIO);
+		if (read_full(release[0], &b, 1) < 0)
+			_exit(EIO);
+		close(release[0]);
+		close(ready[1]);
+		rc = fn ? fn(arg) : 0;
+		_exit(rc < 0 ? -rc : 0);
+	}
+	close(ready[1]);
+	close(release[0]);
+	rc = read_full(ready[0], &b, 1);
+	close(ready[0]);
+	if (rc < 0) {
+		/* The child died before reporting readiness. */
+		close(release[1]);
+		rc = wait_result(pid);
+		return rc < 0 ? rc : -ECHILD;
+	}
+	*go = release[1];
+	return pid;
+}
+
+/* Release a fork_helper() child and return its result. */
+static int release_helper(int go, pid_t pid)
+{
+	int rc;
+
+	rc = write_full(go, "1", 1);
+	close(go);
+	if (rc < 0)
+		return rc;
+	return wait_result(pid);
+}
+
+/*
+ * Fork a child that sets up @cred, runs fn(arg) immediately and exits
+ * with the negative errno result of fn().
+ */
+static int child_run(int (*fn)(void *), void *arg, int cred)
+{
+	pid_t pid = fork();
+	int rc;
+
+	if (pid < 0)
+		return -errno;
+	if (pid == 0) {
+		rc = setup_cred(cred);
+		if (rc < 0)
+			_exit(-rc);
+		rc = fn(arg);
+		_exit(rc < 0 ? -rc : 0);
+	}
+	return wait_result(pid);
+}
+
+/* ---- scenarios ---- */
+
+static int parent_attach_fn(void *arg)
+{
+	pid_t target;
+	int go;
+	int rc;
+
+	(void)arg;
+	target = fork_helper(CRED_UNPRIV, NULL, NULL, &go);
+	if (target < 0)
+		return target;
+	rc = try_attach(target);
+	release_helper(go, target);
+	return rc;
+}
+
+/* The child attempts to attach its own parent (this process). */
+static int child_attach_fn(void *arg)
+{
+	pid_t self = getpid();
+	pid_t tracer;
+	int go;
+
+	(void)arg;
+	tracer = fork_helper(CRED_UNPRIV, attach_fn, &self, &go);
+	if (tracer < 0)
+		return tracer;
+	return release_helper(go, tracer);
+}
+
+/* One child of this process attaches another one: they are siblings. */
+static int sibling_fn(void *arg)
+{
+	pid_t target;
+	pid_t tracer;
+	int tgo, go;
+	int rc;
+
+	(void)arg;
+	target = fork_helper(CRED_UNPRIV, NULL, NULL, &tgo);
+	if (target < 0)
+		return target;
+	tracer = fork_helper(CRED_UNPRIV, attach_fn, &target, &go);
+	if (tracer < 0) {
+		release_helper(tgo, target);
+		return tracer;
+	}
+	rc = release_helper(go, tracer);
+	release_helper(tgo, target);
+	return rc;
+}
+
+/*
+ * The child asks its real parent (this process) to trace it; the
+ * parent's credentials decide the outcome.  Called through child_run()
+ * with CRED_UNPRIV for an unprivileged parent or CRED_CAP_PTRACE for
+ * a parent that only holds CAP_SYS_PTRACE.
+ */
+static int traceme_fn(void *arg)
+{
+	pid_t child;
+	int rc;
+
+	(void)arg;
+	child = fork();
+	if (child < 0)
+		return -errno;
+	if (child == 0) {
+		rc = drop_unpriv();
+		if (rc < 0)
+			_exit(-rc);
+		if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) < 0)
+			_exit(errno);
+		_exit(0);
+	}
+	return wait_result(child);
+}
+
+static int write_scope_fn(void *arg)
+{
+	(void)arg;
+	return write_ptrace_scope(YAMA_SCOPE_RELATIONAL);
+}
+
+/*
+ * A CAP_SYS_PTRACE holder attaches a target that is not its descendant:
+ * the target and the holder are both children of the root caller, so
+ * they are siblings.
+ */
+static int cap_sibling_attach(void)
+{
+	pid_t target;
+	pid_t holder;
+	int tgo, hgo;
+	int rc;
+
+	target = fork_helper(CRED_UNPRIV, NULL, NULL, &tgo);
+	if (target < 0)
+		return target;
+	holder = fork_helper(CRED_CAP_PTRACE, attach_fn, &target, &hgo);
+	if (holder < 0) {
+		release_helper(tgo, target);
+		return holder;
+	}
+	rc = release_helper(hgo, holder);
+	release_helper(tgo, target);
+	return rc;
+}
+
+/* ---- sysctl ---- */
+
+TEST(sysctl_permissions_and_bounds)
+{
+	int orig_scope = -1, cur_scope = -1;
+	int rc;
+
+	rc = read_ptrace_scope(&orig_scope);
+	if (rc == -ENOENT)
+		SKIP(return, "Yama is not active");
+	ASSERT_EQ(0, rc);
+	EXPECT_GE(orig_scope, YAMA_SCOPE_DISABLED);
+	EXPECT_LE(orig_scope, YAMA_SCOPE_NO_ATTACH);
+
+	if (geteuid() != 0) {
+		/* The sysctl is 0644: unprivileged writers get EACCES. */
+		EXPECT_EQ(-EACCES, write_ptrace_scope(orig_scope));
+	} else if (!has_cap_sys_ptrace()) {
+		/* UID 0 without CAP_SYS_PTRACE: the handler returns EPERM. */
+		EXPECT_EQ(-EPERM, write_ptrace_scope_str("1\n"));
+	} else if (!can_drop_unpriv()) {
+		SKIP(return, "cannot drop privileges for test children");
+	} else {
+		/* Unprivileged writer: EACCES from the 0644 file mode. */
+		EXPECT_EQ(-EACCES,
+			  child_run(write_scope_fn, NULL, CRED_UNPRIV));
+		/* UID 0 without CAP_SYS_PTRACE: yama_dointvec_minmax(). */
+		EXPECT_EQ(-EPERM,
+			  child_run(write_scope_fn, NULL, CRED_UID0_NOCAP));
+
+		/* Out-of-range values are rejected and change nothing. */
+		EXPECT_EQ(-EINVAL, write_ptrace_scope_str("-1\n"));
+		EXPECT_EQ(-EINVAL, write_ptrace_scope_str("4\n"));
+		ASSERT_EQ(0, read_ptrace_scope(&cur_scope));
+		EXPECT_EQ(orig_scope, cur_scope);
+	}
+}
+
+/* ---- scope matrix ---- */
+
+FIXTURE(yama_scope) {
+	int orig_scope;
+	bool restore;
+	const char *skip;
+};
+
+FIXTURE_VARIANT(yama_scope) {
+	int scope;
+	int expect_parent_attach;
+	int expect_child_attach;
+	int expect_sibling_attach;
+	int expect_traceme;
+	int expect_cap_attach;
+	int expect_cap_traceme;
+};
+
+FIXTURE_VARIANT_ADD(yama_scope, disabled) {
+	.scope = YAMA_SCOPE_DISABLED,
+	.expect_parent_attach = 0,
+	.expect_child_attach = 0,
+	.expect_sibling_attach = 0,
+	.expect_traceme = 0,
+	.expect_cap_attach = 0,
+	.expect_cap_traceme = 0,
+};
+
+FIXTURE_VARIANT_ADD(yama_scope, relational) {
+	.scope = YAMA_SCOPE_RELATIONAL,
+	.expect_parent_attach = 0,
+	.expect_child_attach = -EPERM,
+	.expect_sibling_attach = -EPERM,
+	.expect_traceme = 0,
+	.expect_cap_attach = 0,
+	.expect_cap_traceme = 0,
+};
+
+FIXTURE_VARIANT_ADD(yama_scope, capability) {
+	.scope = YAMA_SCOPE_CAPABILITY,
+	.expect_parent_attach = -EPERM,
+	.expect_child_attach = -EPERM,
+	.expect_sibling_attach = -EPERM,
+	.expect_traceme = -EPERM,
+	.expect_cap_attach = 0,
+	.expect_cap_traceme = 0,
+};
+
+FIXTURE_SETUP(yama_scope)
+{
+	int rc;
+
+	self->skip = NULL;
+	self->restore = false;
+
+	rc = read_ptrace_scope(&self->orig_scope);
+	if (rc == -ENOENT) {
+		self->skip = "Yama is not active";
+		return;
+	}
+	ASSERT_EQ(0, rc);
+
+	if (!can_drop_unpriv()) {
+		self->skip = "cannot drop privileges for test children";
+		return;
+	}
+
+	if (self->orig_scope == variant->scope)
+		return;
+	if (self->orig_scope == YAMA_SCOPE_NO_ATTACH) {
+		self->skip = "ptrace_scope is locked at 3";
+		return;
+	}
+
+	rc = write_ptrace_scope(variant->scope);
+	if (rc == -EACCES || rc == -EPERM) {
+		self->skip = "need CAP_SYS_PTRACE to change ptrace_scope";
+		return;
+	}
+	ASSERT_EQ(0, rc);
+	self->restore = true;
+}
+
+FIXTURE_TEARDOWN(yama_scope)
+{
+	if (self->restore)
+		EXPECT_EQ(0, write_ptrace_scope(self->orig_scope));
+}
+
+TEST_F(yama_scope, attach_matrix)
+{
+	if (self->skip)
+		SKIP(return, "%s", self->skip);
+
+	/* Unprivileged parent attaching its child. */
+	EXPECT_EQ(variant->expect_parent_attach,
+		  child_run(parent_attach_fn, NULL, CRED_UNPRIV));
+	/* Unprivileged child attaching its parent. */
+	EXPECT_EQ(variant->expect_child_attach,
+		  child_run(child_attach_fn, NULL, CRED_UNPRIV));
+	/* Unprivileged siblings attaching each other. */
+	EXPECT_EQ(variant->expect_sibling_attach,
+		  child_run(sibling_fn, NULL, CRED_UNPRIV));
+	/* Child asking its unprivileged parent to trace it. */
+	EXPECT_EQ(variant->expect_traceme,
+		  child_run(traceme_fn, NULL, CRED_UNPRIV));
+
+	if (can_test_cap_ptrace()) {
+		/* CAP_SYS_PTRACE holder attaching a non-descendant. */
+		EXPECT_EQ(variant->expect_cap_attach,
+			  cap_sibling_attach());
+		/* Child asking a CAP_SYS_PTRACE parent to trace it. */
+		EXPECT_EQ(variant->expect_cap_traceme,
+			  child_run(traceme_fn, NULL, CRED_CAP_PTRACE));
+	}
+}
+
+/* ---- scope 3: no attach, irreversible until reboot ---- */
+
+TEST(scope3_no_attach)
+{
+	int scope = -1;
+	int rc;
+
+	rc = read_ptrace_scope(&scope);
+	if (rc == -ENOENT)
+		SKIP(return, "Yama is not active");
+	ASSERT_EQ(0, rc);
+	if (!can_drop_unpriv())
+		SKIP(return, "cannot drop privileges for test children");
+
+	if (scope != YAMA_SCOPE_NO_ATTACH) {
+		const char *opt_in = getenv("YAMA_TEST_NO_ATTACH");
+
+		if (!opt_in || strcmp(opt_in, "1"))
+			SKIP(return,
+			     "ptrace_scope=3 is irreversible; set YAMA_TEST_NO_ATTACH=1 to test it");
+		rc = write_ptrace_scope(YAMA_SCOPE_NO_ATTACH);
+		if (rc == -EACCES || rc == -EPERM)
+			SKIP(return, "need CAP_SYS_PTRACE to set ptrace_scope=3");
+		ASSERT_EQ(0, rc);
+	}
+
+	/* Once at 3 the sysctl locks: writes below the maximum fail. */
+	if (geteuid() == 0 && has_cap_sys_ptrace())
+		EXPECT_EQ(-EINVAL, write_ptrace_scope(YAMA_SCOPE_DISABLED));
+	ASSERT_EQ(0, read_ptrace_scope(&scope));
+	EXPECT_EQ(YAMA_SCOPE_NO_ATTACH, scope);
+
+	/* Every attach and TRACEME is denied, whoever attempts it. */
+	EXPECT_EQ(-EPERM, child_run(parent_attach_fn, NULL, CRED_UNPRIV));
+	EXPECT_EQ(-EPERM, child_run(child_attach_fn, NULL, CRED_UNPRIV));
+	EXPECT_EQ(-EPERM, child_run(sibling_fn, NULL, CRED_UNPRIV));
+	EXPECT_EQ(-EPERM, child_run(traceme_fn, NULL, CRED_UNPRIV));
+	if (can_test_cap_ptrace()) {
+		EXPECT_EQ(-EPERM, cap_sibling_attach());
+		EXPECT_EQ(-EPERM, child_run(traceme_fn, NULL, CRED_CAP_PTRACE));
+	}
+}
+
+TEST_HARNESS_MAIN
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [PATCH 2/2] selftests/yama: add PR_SET_PTRACER tests
  2026-11-25 12:59 [PATCH 0/2] selftests/yama: add ptrace_scope and PR_SET_PTRACER tests Guicai Ma
  2026-11-25 12:59 ` [PATCH 1/2] selftests/yama: add ptrace_scope selftests Guicai Ma
@ 2026-11-25 12:59 ` Guicai Ma
  2026-11-25 13:06 ` [PATCH 0/2] selftests/yama: add ptrace_scope and " sashiko-bot
  2 siblings, 0 replies; 4+ messages in thread
From: Guicai Ma @ 2026-11-25 12:59 UTC (permalink / raw)
  To: Kees Cook, Shuah Khan, linux-kselftest, linux-kernel
  Cc: linux-security-module, Paul Moore

Add a second test program covering the PR_SET_PTRACER exception list
of Yama.

The lifecycle test checks that a reaped PID is rejected with EINVAL,
that a granted tracer and its descendants may attach while unrelated
processes may not, that granting another tracer revokes the first one
while it is still alive, that PR_SET_PTRACER(0) revokes the current
grant, and that PR_SET_PTRACER_ANY admits every process.  A second
test runs the same prctl() calls from a non-leader thread to verify
that the exception is recorded with process granularity.

Tracers stay alive across the assertions, so each grant, replacement
and clear is observed on the task it applies to.  Workers report
readiness once their credentials are in place, and each child closes
the pipes of the workers spawned before it, so no result depends on
scheduling and teardown never deadlocks on inherited pipe ends.

Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
---
 tools/testing/selftests/yama/.gitignore     |   1 +
 tools/testing/selftests/yama/Makefile       |   4 +-
 tools/testing/selftests/yama/ptracer_test.c | 403 ++++++++++++++++++++
 3 files changed, 407 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/yama/ptracer_test.c

diff --git a/tools/testing/selftests/yama/.gitignore b/tools/testing/selftests/yama/.gitignore
index 6ffe677a8695..4270fbb194a3 100644
--- a/tools/testing/selftests/yama/.gitignore
+++ b/tools/testing/selftests/yama/.gitignore
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0
 ptrace_scope_test
+ptracer_test
diff --git a/tools/testing/selftests/yama/Makefile b/tools/testing/selftests/yama/Makefile
index f0dd1ed89d20..dffecfbefd7a 100644
--- a/tools/testing/selftests/yama/Makefile
+++ b/tools/testing/selftests/yama/Makefile
@@ -6,6 +6,8 @@ CFLAGS += -Wall -O2 $(KHDR_INCLUDES)
 
 LOCAL_HDRS += common.h
 
-TEST_GEN_PROGS := ptrace_scope_test
+TEST_GEN_PROGS := ptrace_scope_test ptracer_test
 
 include ../lib.mk
+
+$(OUTPUT)/ptracer_test: LDLIBS += -lpthread
diff --git a/tools/testing/selftests/yama/ptracer_test.c b/tools/testing/selftests/yama/ptracer_test.c
new file mode 100644
index 000000000000..25638c9629c4
--- /dev/null
+++ b/tools/testing/selftests/yama/ptracer_test.c
@@ -0,0 +1,403 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * PR_SET_PTRACER selftests for the Yama LSM.
+ *
+ * The tracee and the tracer workers are unprivileged children of the
+ * test process, so every attach attempt has to pass Yama's relation
+ * checks instead of the descendant rule.  Tracers stay alive across
+ * the assertions, so each grant, replacement and clear is observed on
+ * the task it applies to.  Every worker reports readiness before the
+ * first command, and commands queue in the pipes, so no result depends
+ * on child scheduling.
+ */
+#include <pthread.h>
+
+#include "kselftest_harness.h"
+#include "common.h"
+
+/* Tracee commands: apply PR_SET_PTRACER with @arg, directly or from a
+ * non-leader thread.
+ */
+enum {
+	TRACEE_PTRACER = 1,
+	TRACEE_PTRACER_THREAD,
+};
+
+/* Tracer commands: attach the tracee directly or through a forked
+ * child, i.e. as a descendant of the tracer.
+ */
+enum {
+	TRACER_ATTACH = 1,
+	TRACER_ATTACH_VIA_CHILD,
+};
+
+struct worker {
+	pid_t pid;
+	int go;		/* parent to worker: one command at a time */
+	int res;	/* worker to parent: one int result per command */
+};
+
+/* Attach as a descendant of the caller: a child of this process. */
+static int attach_via_child(pid_t target)
+{
+	pid_t child;
+	int rc;
+
+	child = fork();
+	if (child < 0)
+		return -errno;
+	if (child == 0) {
+		rc = try_attach(target);
+		_exit(rc < 0 ? -rc : 0);
+	}
+	return wait_result(child);
+}
+
+/* ---- tracee worker ---- */
+
+struct prctl_thread_arg {
+	unsigned long arg2;
+	int rc;
+};
+
+static void *ptracer_prctl_thread(void *data)
+{
+	struct prctl_thread_arg *a = data;
+
+	if (prctl(PR_SET_PTRACER, a->arg2, 0, 0, 0) < 0)
+		a->rc = -errno;
+	else
+		a->rc = 0;
+	return NULL;
+}
+
+/*
+ * Run PR_SET_PTRACER on a non-leader thread: the exception must be
+ * recorded for the whole thread group.
+ */
+static int prctl_ptracer_thread(unsigned long arg2)
+{
+	struct prctl_thread_arg a = {
+		.arg2 = arg2,
+		.rc = -EIO,
+	};
+	pthread_t th;
+	int rc;
+
+	/* pthread_create() returns the error number, it does not set errno. */
+	rc = pthread_create(&th, NULL, ptracer_prctl_thread, &a);
+	if (rc)
+		return -rc;
+	pthread_join(th, NULL);
+	return a.rc;
+}
+
+/* The tracee: apply PR_SET_PTRACER on request. */
+static void tracee_loop(int go, int res, pid_t target)
+{
+	unsigned long arg;
+	uint8_t cmd;
+	int rc;
+
+	(void)target;
+	for (;;) {
+		if (read_full(go, &cmd, sizeof(cmd)) < 0 ||
+		    read_full(go, &arg, sizeof(arg)) < 0)
+			return;
+		if (cmd == TRACEE_PTRACER)
+			rc = prctl(PR_SET_PTRACER, arg, 0, 0, 0) < 0 ?
+				-errno : 0;
+		else if (cmd == TRACEE_PTRACER_THREAD)
+			rc = prctl_ptracer_thread(arg);
+		else
+			return;
+		if (write_full(res, &rc, sizeof(rc)) < 0)
+			return;
+	}
+}
+
+/* ---- tracer worker ---- */
+
+/* The tracer: attach the tracee on request. */
+static void tracer_loop(int go, int res, pid_t target)
+{
+	unsigned long arg;
+	uint8_t cmd;
+	int rc;
+
+	for (;;) {
+		if (read_full(go, &cmd, sizeof(cmd)) < 0 ||
+		    read_full(go, &arg, sizeof(arg)) < 0)
+			return;
+		rc = cmd == TRACER_ATTACH_VIA_CHILD ?
+			attach_via_child(target) : try_attach(target);
+		if (write_full(res, &rc, sizeof(rc)) < 0)
+			return;
+	}
+}
+
+/* ---- worker spawn and control ---- */
+
+#define MAX_WORKERS 4
+
+/* All workers spawned by one test. */
+struct worker_set {
+	struct worker w[MAX_WORKERS];
+	int n;
+};
+
+/*
+ * Fork a worker that drops to unprivileged credentials and serves
+ * commands until its go pipe closes.  The child closes the pipes of
+ * previously spawned workers, which would otherwise keep each other's
+ * write ends open and never see EOF.  The worker reports readiness
+ * once its credentials are in place, so a setup failure is reported
+ * here and not as a later command failure.
+ */
+static pid_t fork_worker(struct worker_set *s, pid_t target,
+			 void (*loop)(int, int, pid_t))
+{
+	struct worker *w = &s->w[s->n];
+	int go[2], res[2];
+	pid_t pid;
+	char b;
+	int rc;
+	int i;
+
+	if (s->n >= MAX_WORKERS)
+		return -E2BIG;
+	if (pipe(go) < 0)
+		return -errno;
+	if (pipe(res) < 0) {
+		rc = -errno;
+		close(go[0]);
+		close(go[1]);
+		return rc;
+	}
+	pid = fork();
+	if (pid < 0) {
+		rc = -errno;
+		close(go[0]);
+		close(go[1]);
+		close(res[0]);
+		close(res[1]);
+		return rc;
+	}
+	if (pid == 0) {
+		close(go[1]);
+		close(res[0]);
+		for (i = 0; i < s->n; i++) {
+			close(s->w[i].go);
+			close(s->w[i].res);
+		}
+		rc = drop_unpriv();
+		if (rc < 0)
+			_exit(-rc);
+		if (write_full(res[1], "1", 1) < 0)
+			_exit(EIO);
+		loop(go[0], res[1], target);
+		_exit(0);
+	}
+	close(go[0]);
+	close(res[1]);
+	w->pid = pid;
+	w->go = go[1];
+	w->res = res[0];
+	s->n++;
+
+	rc = read_full(w->res, &b, 1);
+	if (rc < 0) {
+		/* The worker died before reporting readiness. */
+		close(w->go);
+		close(w->res);
+		s->n--;
+		rc = wait_result(pid);
+		return rc < 0 ? rc : -ECHILD;
+	}
+	return pid;
+}
+
+static pid_t fork_tracee(struct worker_set *s)
+{
+	return fork_worker(s, 0, tracee_loop);
+}
+
+static pid_t fork_tracer(struct worker_set *s, pid_t target)
+{
+	return fork_worker(s, target, tracer_loop);
+}
+
+/* Send one command and return the worker's int result. */
+static int worker_cmd(struct worker *w, uint8_t cmd, unsigned long arg)
+{
+	int rc;
+	int res;
+
+	rc = write_full(w->go, &cmd, sizeof(cmd));
+	if (!rc)
+		rc = write_full(w->go, &arg, sizeof(arg));
+	if (rc)
+		return rc;
+	if (read_full(w->res, &res, sizeof(res)) < 0)
+		return -EIO;
+	return res;
+}
+
+/* PR_SET_PTRACER(@arg2) on the tracee, directly or from a thread. */
+static int tracee_prctl(struct worker *w, unsigned long arg2, bool thread)
+{
+	return worker_cmd(w, thread ? TRACEE_PTRACER_THREAD : TRACEE_PTRACER,
+			  arg2);
+}
+
+/* Attach the tracee from the tracer, or from a descendant of it. */
+static int tracer_attach(struct worker *w, bool via_child)
+{
+	return worker_cmd(w, via_child ? TRACER_ATTACH_VIA_CHILD :
+			TRACER_ATTACH, 0);
+}
+
+/* Close every command pipe, then reap all workers. */
+static void workers_stop(struct worker_set *s)
+{
+	int i;
+
+	for (i = 0; i < s->n; i++) {
+		close(s->w[i].go);
+		close(s->w[i].res);
+	}
+	for (i = 0; i < s->n; i++)
+		wait_result(s->w[i].pid);
+}
+
+/* ---- tests ---- */
+
+FIXTURE(yama_relational) {
+	int orig_scope;
+	bool restore;
+	const char *skip;
+};
+
+FIXTURE_SETUP(yama_relational)
+{
+	int rc;
+
+	self->skip = NULL;
+	self->restore = false;
+
+	rc = read_ptrace_scope(&self->orig_scope);
+	if (rc == -ENOENT) {
+		self->skip = "Yama is not active";
+		return;
+	}
+	ASSERT_EQ(0, rc);
+
+	if (!can_drop_unpriv()) {
+		self->skip = "cannot drop privileges for test children";
+		return;
+	}
+
+	if (self->orig_scope == YAMA_SCOPE_RELATIONAL)
+		return;
+	if (self->orig_scope == YAMA_SCOPE_NO_ATTACH) {
+		self->skip = "ptrace_scope is locked at 3";
+		return;
+	}
+
+	rc = write_ptrace_scope(YAMA_SCOPE_RELATIONAL);
+	if (rc == -EACCES || rc == -EPERM) {
+		self->skip = "need CAP_SYS_PTRACE to set ptrace_scope=1";
+		return;
+	}
+	ASSERT_EQ(0, rc);
+	self->restore = true;
+}
+
+FIXTURE_TEARDOWN(yama_relational)
+{
+	if (self->restore)
+		EXPECT_EQ(0, write_ptrace_scope(self->orig_scope));
+}
+
+TEST_F(yama_relational, pr_set_ptracer_lifecycle)
+{
+	struct worker_set s = {};
+	struct worker *tracee = &s.w[0];
+	struct worker *t1 = &s.w[1];
+	struct worker *t2 = &s.w[2];
+	struct worker *t3 = &s.w[3];
+	pid_t dead;
+
+	if (self->skip)
+		SKIP(return, "%s", self->skip);
+
+	/* Spawn every worker first, so no later fork can recycle @dead. */
+	ASSERT_GE(fork_tracee(&s), 0);
+	ASSERT_GE(fork_tracer(&s, tracee->pid), 0);
+	ASSERT_GE(fork_tracer(&s, tracee->pid), 0);
+	ASSERT_GE(fork_tracer(&s, tracee->pid), 0);
+
+	/* A reaped PID is rejected. */
+	dead = fork();
+	ASSERT_GE(dead, 0);
+	if (dead == 0)
+		_exit(0);
+	ASSERT_EQ(0, wait_result(dead));
+	EXPECT_EQ(-EINVAL, tracee_prctl(tracee, dead, false));
+
+	/* A granted tracer and its descendants may attach, others not. */
+	EXPECT_EQ(0, tracee_prctl(tracee, t1->pid, false));
+	EXPECT_EQ(0, tracer_attach(t1, false));
+	EXPECT_EQ(0, tracer_attach(t1, true));
+	EXPECT_EQ(-EPERM, tracer_attach(t3, false));
+
+	/* Granting another tracer revokes the first one, which is alive. */
+	EXPECT_EQ(0, tracee_prctl(tracee, t2->pid, false));
+	EXPECT_EQ(-EPERM, tracer_attach(t1, false));
+	EXPECT_EQ(0, tracer_attach(t2, false));
+
+	/* Clearing removes the exception. */
+	EXPECT_EQ(0, tracee_prctl(tracee, 0, false));
+	EXPECT_EQ(-EPERM, tracer_attach(t2, false));
+
+	/* PR_SET_PTRACER_ANY admits any process. */
+	EXPECT_EQ(0, tracee_prctl(tracee, PR_SET_PTRACER_ANY, false));
+	EXPECT_EQ(0, tracer_attach(t1, false));
+	EXPECT_EQ(0, tracer_attach(t3, false));
+
+	workers_stop(&s);
+}
+
+TEST_F(yama_relational, pr_set_ptracer_non_leader_thread)
+{
+	struct worker_set s = {};
+	struct worker *tracee = &s.w[0];
+	struct worker *t1 = &s.w[1];
+	struct worker *t3 = &s.w[2];
+
+	if (self->skip)
+		SKIP(return, "%s", self->skip);
+
+	ASSERT_GE(fork_tracee(&s), 0);
+	ASSERT_GE(fork_tracer(&s, tracee->pid), 0);
+	ASSERT_GE(fork_tracer(&s, tracee->pid), 0);
+
+	/* Without a grant the tracer cannot attach. */
+	EXPECT_EQ(-EPERM, tracer_attach(t1, false));
+
+	/* A non-leader thread grants the exception process-wide. */
+	EXPECT_EQ(0, tracee_prctl(tracee, t1->pid, true));
+	EXPECT_EQ(0, tracer_attach(t1, false));
+
+	/* Clearing from a non-leader thread revokes it again. */
+	EXPECT_EQ(0, tracee_prctl(tracee, 0, true));
+	EXPECT_EQ(-EPERM, tracer_attach(t1, false));
+
+	/* ANY from a non-leader thread admits any process. */
+	EXPECT_EQ(0, tracee_prctl(tracee, PR_SET_PTRACER_ANY, true));
+	EXPECT_EQ(0, tracer_attach(t3, false));
+
+	workers_stop(&s);
+}
+
+TEST_HARNESS_MAIN
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 4+ messages in thread

* Re: [PATCH 0/2] selftests/yama: add ptrace_scope and PR_SET_PTRACER tests
  2026-11-25 12:59 [PATCH 0/2] selftests/yama: add ptrace_scope and PR_SET_PTRACER tests Guicai Ma
  2026-11-25 12:59 ` [PATCH 1/2] selftests/yama: add ptrace_scope selftests Guicai Ma
  2026-11-25 12:59 ` [PATCH 2/2] selftests/yama: add PR_SET_PTRACER tests Guicai Ma
@ 2026-11-25 13:06 ` sashiko-bot
  2 siblings, 0 replies; 4+ messages in thread
From: sashiko-bot @ 2026-11-25 13:06 UTC (permalink / raw)
  Cc: linux-security-module

Sashiko has reviewed this 2-patch series and found no issues.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261125125944.1768182-1-maguicai@kylinos.cn

^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2026-11-25 13:06 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-25 12:59 [PATCH 0/2] selftests/yama: add ptrace_scope and PR_SET_PTRACER tests Guicai Ma
2026-11-25 12:59 ` [PATCH 1/2] selftests/yama: add ptrace_scope selftests Guicai Ma
2026-11-25 12:59 ` [PATCH 2/2] selftests/yama: add PR_SET_PTRACER tests Guicai Ma
2026-11-25 13:06 ` [PATCH 0/2] selftests/yama: add ptrace_scope and " sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).