xref: /freebsd/tests/sys/pmc/pmc_credexec_test.c (revision bea7b932b9eeaff39393347e0600b982fd859a92)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2026 Alexander Leidinger <netchild@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other advertising materials provided with the
14  *    distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  * Credential-transition tests for a process-mode PMC across exec(), the
32  * companion to pmc_exec_test.c.  Where that file proves the driver drops a
33  * PMC when its target execs into credentials its owner may no longer
34  * trace, these prove the two cases the drop must not overreach into: an
35  * exec that changes no credentials keeps the PMC, and an exec of a set-id
36  * binary whose credential change the kernel then suppresses, because the
37  * target is ptrace(2)d, keeps it too - do_execve() derives the set-id from
38  * the image alone and suppresses it afterwards, clearing P_SUGID and
39  * leaving the ids untouched, so the owner is still entitled.  The third
40  * case covers fexecve(2), which reaches the same hook as execve(2).
41  * These exercise what FreeBSD-SA-26:56.hwpmc reworked, not what it fixed.
42  *
43  * As in pmc_exec_test.c the owner must be unprivileged, and the test must
44  * not lower its own privilege: setuid(2) sets P_SUGID, fork(2) passes it
45  * to the target, and p_candebug() then refuses that target to its own
46  * owner.  Not covered, because each needs privileged setup a require.user
47  * body cannot build: a set-id exec on a nosuid mount, a set-id #!
48  * interpreter, and the two jail transitions.
49  */
50 
51 #include <sys/types.h>
52 #include <sys/ptrace.h>
53 #include <sys/stat.h>
54 #include <sys/wait.h>
55 
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <pmc.h>
59 #include <signal.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 
64 #include <atf-c.h>
65 
66 static const char *counting_events[] = {
67 	"instructions",
68 	"cycles",
69 	"branches",
70 	"unhalted-core-cycles",
71 	"inst_retired.any",
72 	"cpu_clk_unhalted.thread",
73 	"ls_not_halted_cyc",
74 	NULL
75 };
76 
77 /**
78  * @internal
79  * Exec targets.  'setid' is the bit the entry must carry to exercise the
80  * case; the argument vectors are chosen so the program touches nothing.
81  * A target that blocks on stdin stays alive after the exec so that the
82  * still-attached question can be asked; the caller holds the read end open.
83  */
84 struct exec_target {
85 	const char	*path;
86 	const char	*const argv[5];
87 	mode_t		 setid;
88 	int		 blocks_on_stdin;
89 };
90 
91 /**
92  * @internal
93  * Set-gid, blocks on stdin: stays alive so "still attached?" is answerable.
94  */
95 static const struct exec_target setgid_targets[] = {
96 	{ "/usr/bin/wall", { "wall", NULL }, S_ISGID, 1 },
97 	{ NULL, { NULL }, 0, 0 }
98 };
99 
100 /** Set-uid, exits at once: for a drop-case, completing without a panic is
101  * @internal
102  * the whole assertion. */
103 static const struct exec_target setuid_targets[] = {
104 	{ "/sbin/ping", { "ping", "-c", "1", "127.0.0.1", NULL }, S_ISUID, 0 },
105 	{ NULL, { NULL }, 0, 0 }
106 };
107 
108 /** An ordinary, non-set-id target that blocks: sleep ignores stdin but
109  * @internal
110  * stays alive on its own, which is all exec_ordinary_keeps_pmc needs. */
111 static const struct exec_target ordinary_targets[] = {
112 	{ "/bin/sleep", { "sleep", "30", NULL }, 0, 0 },
113 	{ NULL, { NULL }, 0, 0 }
114 };
115 
116 static const struct exec_target *
pick_target(const struct exec_target * tab,bool need_setid)117 pick_target(const struct exec_target *tab, bool need_setid)
118 {
119 	struct stat sb;
120 	int i;
121 
122 	for (i = 0; tab[i].path != NULL; i++) {
123 		if (stat(tab[i].path, &sb) != 0)
124 			continue;
125 		if (need_setid && (sb.st_mode & tab[i].setid) == 0)
126 			continue;
127 		return (&tab[i]);
128 	}
129 	return (NULL);
130 }
131 
132 static pmc_id_t
allocate_counting_pmc(void)133 allocate_counting_pmc(void)
134 {
135 	pmc_id_t id = PMC_ID_INVALID;
136 	int i;
137 
138 	for (i = 0; counting_events[i] != NULL; i++) {
139 		if (pmc_allocate(counting_events[i], PMC_MODE_TC, 0,
140 		    PMC_CPU_ANY, &id, 0) == 0)
141 			return (id);
142 	}
143 	return (PMC_ID_INVALID);
144 }
145 
146 static void
spin(void)147 spin(void)
148 {
149 	volatile unsigned long s = 0;
150 	int i;
151 
152 	for (i = 0; i < 2000000; i++)
153 		s += i;
154 }
155 
156 static void
require_unprivileged_owner(void)157 require_unprivileged_owner(void)
158 {
159 
160 	if (geteuid() == 0)
161 		atf_tc_skip("the PMC owner must be unprivileged: root may "
162 		    "trace any credentials, so the check under test is never "
163 		    "reached");
164 }
165 
166 /**
167  * @internal
168  * How the target should behave between fork and the measured exec.
169  */
170 enum exec_via {
171 	VIA_EXECVE,	/* plain execve(2) */
172 	VIA_FEXECVE,	/* fexecve(2) of an fd opened O_EXEC */
173 	VIA_TRACED,	/* PT_TRACE_ME first, so the exec is credential-safe */
174 };
175 
176 /**
177  * @internal
178  * Fork a target, attach a running counting PMC, and let it exec.  On
179  * return the PMC is released.  When 'inspect' is set the target is expected
180  * to stay alive past the exec, and *still_attached reports whether the PMC
181  * survived it; a drop-case passes inspect=0 for a target that exits at once
182  * (it has already torn its own descriptor down, so there is nothing to ask).
183  */
184 static void
run_target(const struct exec_target * t,enum exec_via via,int inspect,int * still_attached)185 run_target(const struct exec_target *t, enum exec_via via, int inspect,
186     int *still_attached)
187 {
188 	pmc_id_t id;
189 	pid_t target;
190 	char token;
191 	int gopipe[2], inpipe[2], status;
192 
193 	ATF_REQUIRE(pipe(gopipe) == 0);
194 	ATF_REQUIRE(pipe(inpipe) == 0);
195 	ATF_REQUIRE((target = fork()) >= 0);
196 
197 	if (target == 0) {
198 		int fd;
199 
200 		(void)close(gopipe[1]);
201 		if (t->blocks_on_stdin)
202 			(void)dup2(inpipe[0], STDIN_FILENO);
203 		(void)close(inpipe[1]);
204 		if (via == VIA_TRACED)
205 			(void)ptrace(PT_TRACE_ME, 0, NULL, 0);
206 		if (read(gopipe[0], &token, 1) != 1)
207 			_exit(1);
208 		spin();
209 		if (via == VIA_FEXECVE) {
210 			if ((fd = open(t->path, O_EXEC)) < 0)
211 				_exit(1);
212 			(void)fexecve(fd, __DECONST(char **, t->argv), NULL);
213 		} else {
214 			(void)execv(t->path, __DECONST(char **, t->argv));
215 		}
216 		_exit(1);
217 	}
218 	(void)close(gopipe[0]);
219 	(void)close(inpipe[0]);
220 
221 	if (pmc_init() != 0) {
222 		(void)kill(target, SIGKILL);
223 		(void)waitpid(target, &status, 0);
224 		atf_tc_skip("hwpmc(4) is not available");
225 	}
226 	if ((id = allocate_counting_pmc()) == PMC_ID_INVALID) {
227 		(void)kill(target, SIGKILL);
228 		(void)waitpid(target, &status, 0);
229 		atf_tc_skip("no process-mode counting event is allocatable");
230 	}
231 
232 	ATF_REQUIRE_MSG(pmc_attach(id, target) == 0, "pmc_attach: %s",
233 	    strerror(errno));
234 	ATF_REQUIRE(pmc_start(id) == 0);
235 
236 	/* Into the exec. */
237 	ATF_REQUIRE(write(gopipe[1], "g", 1) == 1);
238 	(void)close(gopipe[1]);
239 
240 	if (via == VIA_TRACED) {
241 		/*
242 		 * The exec of a set-id binary under a tracer stops the
243 		 * target with SIGTRAP and leaves its credentials unchanged.
244 		 * Reap that stop and detach the tracer; the hwpmc decision
245 		 * was already taken at exec time, so from here the target
246 		 * runs as an ordinary blocked process.
247 		 */
248 		ATF_REQUIRE(waitpid(target, &status, 0) == target);
249 		ATF_REQUIRE_MSG(WIFSTOPPED(status),
250 		    "traced target did not stop at exec (status 0x%x)", status);
251 		ATF_REQUIRE_MSG(ptrace(PT_DETACH, target, (caddr_t)1, 0) == 0,
252 		    "PT_DETACH: %s", strerror(errno));
253 	}
254 
255 	if (inspect) {
256 		(void)usleep(400000);
257 		errno = 0;
258 		*still_attached = pmc_detach(id, target) == 0;
259 		if (!*still_attached)
260 			ATF_REQUIRE_MSG(errno == ESRCH, "pmc_detach: %s",
261 			    strerror(errno));
262 		(void)kill(target, SIGKILL);
263 	} else {
264 		*still_attached = 0;
265 	}
266 	(void)waitpid(target, &status, 0);
267 	(void)pmc_release(id);
268 }
269 
270 ATF_TC(exec_ordinary_keeps_pmc);
ATF_TC_HEAD(exec_ordinary_keeps_pmc,tc)271 ATF_TC_HEAD(exec_ordinary_keeps_pmc, tc)
272 {
273 
274 	atf_tc_set_md_var(tc, "descr",
275 	    "a process-mode PMC survives an exec that does not change the "
276 	    "target's credentials");
277 	atf_tc_set_md_var(tc, "require.user", "unprivileged");
278 }
ATF_TC_BODY(exec_ordinary_keeps_pmc,tc)279 ATF_TC_BODY(exec_ordinary_keeps_pmc, tc)
280 {
281 	const struct exec_target *t;
282 	int still_attached;
283 
284 	require_unprivileged_owner();
285 	if ((t = pick_target(ordinary_targets, false)) == NULL)
286 		atf_tc_skip("no ordinary exec target available");
287 
288 	run_target(t, VIA_EXECVE, 1, &still_attached);
289 	ATF_REQUIRE_MSG(still_attached,
290 	    "the PMC was dropped across an exec that changed no credentials");
291 }
292 
293 ATF_TC(exec_setid_traced_keeps_pmc);
ATF_TC_HEAD(exec_setid_traced_keeps_pmc,tc)294 ATF_TC_HEAD(exec_setid_traced_keeps_pmc, tc)
295 {
296 
297 	atf_tc_set_md_var(tc, "descr",
298 	    "a process-mode PMC survives its target's exec of a set-id binary "
299 	    "when tracing suppresses the credential change and the owner "
300 	    "remains entitled");
301 	atf_tc_set_md_var(tc, "require.user", "unprivileged");
302 }
ATF_TC_BODY(exec_setid_traced_keeps_pmc,tc)303 ATF_TC_BODY(exec_setid_traced_keeps_pmc, tc)
304 {
305 	const struct exec_target *t;
306 	int still_attached;
307 
308 	require_unprivileged_owner();
309 	if ((t = pick_target(setgid_targets, true)) == NULL)
310 		atf_tc_skip("no set-gid exec target available");
311 
312 	run_target(t, VIA_TRACED, 1, &still_attached);
313 	ATF_REQUIRE_MSG(still_attached,
314 	    "the PMC was dropped although tracing left the target's "
315 	    "credentials unchanged and its owner still entitled");
316 }
317 
318 ATF_TC(exec_fexecve_setid_drops_pmc);
ATF_TC_HEAD(exec_fexecve_setid_drops_pmc,tc)319 ATF_TC_HEAD(exec_fexecve_setid_drops_pmc, tc)
320 {
321 
322 	atf_tc_set_md_var(tc, "descr",
323 	    "a process-mode PMC is detached when its target reaches a "
324 	    "credential-changing set-id binary through fexecve(2)");
325 	atf_tc_set_md_var(tc, "require.user", "unprivileged");
326 }
ATF_TC_BODY(exec_fexecve_setid_drops_pmc,tc)327 ATF_TC_BODY(exec_fexecve_setid_drops_pmc, tc)
328 {
329 	const struct exec_target *t;
330 	int still_attached;
331 
332 	require_unprivileged_owner();
333 	if ((t = pick_target(setuid_targets, true)) == NULL)
334 		atf_tc_skip("no set-uid exec target available");
335 
336 	/* Completing at all is the assertion. */
337 	run_target(t, VIA_FEXECVE, 0, &still_attached);
338 }
339 
ATF_TP_ADD_TCS(tp)340 ATF_TP_ADD_TCS(tp)
341 {
342 
343 	ATF_TP_ADD_TC(tp, exec_ordinary_keeps_pmc);
344 	ATF_TP_ADD_TC(tp, exec_setid_traced_keeps_pmc);
345 	ATF_TP_ADD_TC(tp, exec_fexecve_setid_drops_pmc);
346 
347 	return (atf_no_error());
348 }
349