[PATCH 1/1] ptrace: Get tracer PID without reliance on the proc FS

From: Roman Kisel
Date: Thu Sep 05 2024 - 17:28:26 EST


For debugging, it might be useful to run the debug trap
instruction to break into the debugger. To detect the debugger
presence, the kernel provides the `/proc/self/status` pseudo-file
that needs to be searched for the "TracerPid:" string.

Provide a prctl command that returns the PID of the tracer if any.
That allows for much simpler logic in the user land, and makes it
possible to detect tracer presence even if PROC_FS is not enabled.

Signed-off-by: Roman Kisel <romank@xxxxxxxxxxxxxxxxxxx>
---
include/uapi/linux/ptrace.h | 1 +
kernel/ptrace.c | 11 ++++++++++-
2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/include/uapi/linux/ptrace.h b/include/uapi/linux/ptrace.h
index 72c038fc71d0..5056f5d1df6b 100644
--- a/include/uapi/linux/ptrace.h
+++ b/include/uapi/linux/ptrace.h
@@ -21,6 +21,7 @@

#define PTRACE_ATTACH 16
#define PTRACE_DETACH 17
+#define PTRACE_TRACER 18

#define PTRACE_SYSCALL 24

diff --git a/kernel/ptrace.c b/kernel/ptrace.c
index d5f89f9ef29f..91275c5c4f57 100644
--- a/kernel/ptrace.c
+++ b/kernel/ptrace.c
@@ -1258,7 +1258,7 @@ int ptrace_request(struct task_struct *child, long request,
SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,
unsigned long, data)
{
- struct task_struct *child;
+ struct task_struct *child, *tracer;
long ret;

if (request == PTRACE_TRACEME) {
@@ -1277,6 +1277,15 @@ SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,
goto out_put_task_struct;
}

+ if (request == PTRACE_TRACER) {
+ rcu_read_lock();
+ tracer = ptrace_parent(current);
+ ret = tracer ? task_pid_nr_ns(tracer,
+ task_active_pid_ns(current->parent)) : -ESRCH;
+ rcu_read_unlock();
+ goto out;
+ }
+
ret = ptrace_check_attach(child, request == PTRACE_KILL ||
request == PTRACE_INTERRUPT);
if (ret < 0)
--
2.34.1