t_ptrace.c revision 1.7
1/*	$NetBSD: t_ptrace.c,v 1.7 2025/05/02 02:24:44 riastradh Exp $	*/
2
3/*-
4 * Copyright (c) 2016 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__RCSID("$NetBSD: t_ptrace.c,v 1.7 2025/05/02 02:24:44 riastradh Exp $");
31
32#include <sys/param.h>
33#include <sys/types.h>
34#include <sys/ptrace.h>
35#include <sys/stat.h>
36#include <sys/sysctl.h>
37#include <err.h>
38#include <errno.h>
39#include <unistd.h>
40
41#include <atf-c.h>
42
43#include "h_macros.h"
44
45/*
46 * A child process cannot call atf functions and expect them to magically
47 * work like in the parent.
48 * The printf(3) messaging from a child will not work out of the box as well
49 * without establishing a communication protocol with its parent. To not
50 * overcomplicate the tests - do not log from a child and use err(3)/errx(3)
51 * wrapped with FORKEE_ASSERT()/FORKEE_ASSERTX() as that is guaranteed to work.
52 */
53#define FORKEE_ASSERTX(x)						      \
54do {									      \
55	int ret = (x);							      \
56	if (!ret)							      \
57		errx(EXIT_FAILURE, "%s:%d %s(): Assertion failed for: %s",    \
58		    __FILE__, __LINE__, __func__, #x);			      \
59} while (0)
60
61#define FORKEE_ASSERT(x)						      \
62do {									      \
63	int ret = (x);							      \
64	if (!ret)							      \
65		err(EXIT_FAILURE, "%s:%d %s(): Assertion failed for: %s",     \
66		    __FILE__, __LINE__, __func__, #x);			      \
67} while (0)
68
69#define FORKEE_ASSERT_EQ(x, y)						      \
70do {									      \
71	uintmax_t vx = (x);						      \
72	uintmax_t vy = (y);						      \
73	int ret = vx == vy;						      \
74	if (!ret)							      \
75		errx(EXIT_FAILURE, "%s:%d %s(): Assertion failed for: "	      \
76		    "%s(%ju) == %s(%ju)", __FILE__, __LINE__, __func__,	      \
77		    #x, vx, #y, vy);					      \
78} while (0)
79
80ATF_TC(attach_pid0);
81ATF_TC_HEAD(attach_pid0, tc)
82{
83	atf_tc_set_md_var(tc, "descr",
84	    "Assert that a debugger cannot attach to PID 0");
85}
86
87ATF_TC_BODY(attach_pid0, tc)
88{
89	errno = 0;
90	ATF_REQUIRE_ERRNO(EPERM, ptrace(PT_ATTACH, 0, NULL, 0) == -1);
91}
92
93ATF_TC(attach_pid1);
94ATF_TC_HEAD(attach_pid1, tc)
95{
96	atf_tc_set_md_var(tc, "descr",
97	    "Assert that a debugger cannot attach to PID 1 (as non-root)");
98
99	atf_tc_set_md_var(tc, "require.user", "unprivileged");
100}
101
102ATF_TC_BODY(attach_pid1, tc)
103{
104	ATF_REQUIRE_ERRNO(EPERM, ptrace(PT_ATTACH, 1, NULL, 0) == -1);
105}
106
107ATF_TC(attach_pid1_securelevel);
108ATF_TC_HEAD(attach_pid1_securelevel, tc)
109{
110	atf_tc_set_md_var(tc, "descr",
111	    "Assert that a debugger cannot attach to PID 1 with "
112	    "securelevel >= 0 (as root)");
113
114	atf_tc_set_md_var(tc, "require.user", "root");
115}
116
117ATF_TC_BODY(attach_pid1_securelevel, tc)
118{
119	int level;
120	size_t len = sizeof(level);
121
122	RL(sysctlbyname("kern.securelevel", &level, &len, NULL, 0));
123
124	if (level < 0) {
125		atf_tc_skip("Test must be run with securelevel >= 0");
126	}
127
128	ATF_REQUIRE_ERRNO(EPERM, ptrace(PT_ATTACH, 1, NULL, 0) == -1);
129}
130
131ATF_TC(attach_self);
132ATF_TC_HEAD(attach_self, tc)
133{
134	atf_tc_set_md_var(tc, "descr",
135	    "Assert that a debugger cannot attach to self (as it's nonsense)");
136}
137
138ATF_TC_BODY(attach_self, tc)
139{
140	ATF_REQUIRE_ERRNO(EINVAL, ptrace(PT_ATTACH, getpid(), NULL, 0) == -1);
141}
142
143ATF_TC(attach_chroot);
144ATF_TC_HEAD(attach_chroot, tc)
145{
146	atf_tc_set_md_var(tc, "descr",
147	    "Assert that a debugger cannot trace another process unless the "
148	    "process's root directory is at or below the tracing process's "
149	    "root");
150
151	atf_tc_set_md_var(tc, "require.user", "root");
152}
153
154ATF_TC_BODY(attach_chroot, tc)
155{
156	char buf[PATH_MAX];
157	pid_t child;
158	int fds_toparent[2], fds_fromparent[2];
159	int rv;
160	uint8_t msg = 0xde; /* dummy message for IPC based on pipe(2) */
161
162	(void)memset(buf, '\0', sizeof(buf));
163	REQUIRE_LIBC(getcwd(buf, sizeof(buf)), NULL);
164	(void)strlcat(buf, "/dir", sizeof(buf));
165
166	RL(mkdir(buf, 0500));
167	RL(chdir(buf));
168
169	RL(pipe(fds_toparent));
170	RL(pipe(fds_fromparent));
171	child = atf_utils_fork();
172	if (child == 0) {
173		FORKEE_ASSERT(close(fds_toparent[0]) == 0);
174		FORKEE_ASSERT(close(fds_fromparent[1]) == 0);
175
176		FORKEE_ASSERT(chroot(buf) == 0);
177
178		FORKEE_ASSERT((rv = write(fds_toparent[1], &msg, sizeof(msg)))
179		    != -1);
180		FORKEE_ASSERT_EQ(rv, sizeof(msg));
181
182		if (ptrace(PT_ATTACH, getppid(), NULL, 0) == 0) {
183			errx(EXIT_FAILURE, "%s unexpectedly succeeded",
184			    "ptrace(PT_ATTACH, getppid(), NULL, 0)");
185		} else if (errno != EPERM) {
186			err(EXIT_FAILURE, "%s failed but not with EPERM",
187			    "ptrace(PT_ATTACH, getppid(), NULL, 0)");
188		}
189
190		FORKEE_ASSERT((rv = read(fds_fromparent[0], &msg, sizeof(msg)))
191		    != -1);
192		FORKEE_ASSERT_EQ(rv, sizeof(msg));
193
194		_exit(0);
195	}
196	RL(close(fds_toparent[1]));
197	RL(close(fds_fromparent[0]));
198
199	printf("Waiting for chrooting of the child PID %d", child);
200	RL(rv = read(fds_toparent[0], &msg, sizeof(msg)));
201	ATF_REQUIRE(rv == sizeof(msg));
202
203	printf("Child is ready, it will try to PT_ATTACH to parent\n");
204	RL(rv = write(fds_fromparent[1], &msg, sizeof(msg)));
205	ATF_REQUIRE(rv == sizeof(msg));
206
207        printf("fds_fromparent is no longer needed - close it\n");
208        RL(close(fds_fromparent[1]));
209
210        printf("fds_toparent is no longer needed - close it\n");
211        RL(close(fds_toparent[0]));
212}
213
214ATF_TC(traceme_twice);
215ATF_TC_HEAD(traceme_twice, tc)
216{
217	atf_tc_set_md_var(tc, "descr",
218	    "Assert that a process cannot mark its parent a debugger twice");
219}
220
221ATF_TC_BODY(traceme_twice, tc)
222{
223
224	printf("Mark the parent process (PID %d) a debugger of PID %d",
225	       getppid(), getpid());
226	RL(ptrace(PT_TRACE_ME, 0, NULL, 0));
227
228	printf("Mark the parent process (PID %d) a debugger of PID %d again",
229	       getppid(), getpid());
230	ATF_REQUIRE_ERRNO(EBUSY, ptrace(PT_TRACE_ME, 0, NULL, 0) == -1);
231}
232
233ATF_TP_ADD_TCS(tp)
234{
235	setvbuf(stdout, NULL, _IONBF, 0);
236	setvbuf(stderr, NULL, _IONBF, 0);
237	ATF_TP_ADD_TC(tp, attach_pid0);
238	ATF_TP_ADD_TC(tp, attach_pid1);
239	ATF_TP_ADD_TC(tp, attach_pid1_securelevel);
240	ATF_TP_ADD_TC(tp, attach_self);
241	ATF_TP_ADD_TC(tp, attach_chroot);
242	ATF_TP_ADD_TC(tp, traceme_twice);
243
244	return atf_no_error();
245}
246