xref: /linux/tools/testing/selftests/landlock/trace.h (revision a873f3c213a6fc09aaa2bb389fba49f9bbe9d589)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Landlock trace test helpers
4  *
5  * Copyright © 2026 Cloudflare, Inc.
6  */
7 
8 #define _GNU_SOURCE
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <regex.h>
12 #include <stdbool.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/mount.h>
17 #include <sys/stat.h>
18 #include <unistd.h>
19 
20 #include "kselftest_harness.h"
21 
22 #define TRACEFS_ROOT "/sys/kernel/tracing"
23 #define TRACEFS_LANDLOCK_DIR TRACEFS_ROOT "/events/landlock"
24 #define TRACEFS_CREATE_RULESET_ENABLE \
25 	TRACEFS_LANDLOCK_DIR "/landlock_create_ruleset/enable"
26 #define TRACEFS_CREATE_DOMAIN_ENABLE \
27 	TRACEFS_LANDLOCK_DIR "/landlock_create_domain/enable"
28 #define TRACEFS_ENFORCE_DOMAIN_ENABLE \
29 	TRACEFS_LANDLOCK_DIR "/landlock_enforce_domain/enable"
30 #define TRACEFS_ADD_RULE_PATH_BENEATH_ENABLE \
31 	TRACEFS_LANDLOCK_DIR "/landlock_add_rule_path_beneath/enable"
32 #define TRACEFS_ADD_RULE_NET_PORT_ENABLE \
33 	TRACEFS_LANDLOCK_DIR "/landlock_add_rule_net_port/enable"
34 #define TRACEFS_ADD_RULE_NAMESPACE_ENABLE \
35 	TRACEFS_LANDLOCK_DIR "/landlock_add_rule_namespace/enable"
36 #define TRACEFS_ADD_RULE_CAPABILITY_ENABLE \
37 	TRACEFS_LANDLOCK_DIR "/landlock_add_rule_capability/enable"
38 #define TRACEFS_CHECK_RULE_FS_ENABLE \
39 	TRACEFS_LANDLOCK_DIR "/landlock_check_rule_inode/enable"
40 #define TRACEFS_CHECK_RULE_NET_ENABLE \
41 	TRACEFS_LANDLOCK_DIR "/landlock_check_rule_net_port/enable"
42 #define TRACEFS_DENY_ACCESS_FS_ENABLE \
43 	TRACEFS_LANDLOCK_DIR "/landlock_deny_access_fs/enable"
44 #define TRACEFS_DENY_ACCESS_NET_ENABLE \
45 	TRACEFS_LANDLOCK_DIR "/landlock_deny_access_net/enable"
46 #define TRACEFS_DENY_PERMISSION_NAMESPACE_ENABLE \
47 	TRACEFS_LANDLOCK_DIR "/landlock_deny_permission_namespace/enable"
48 #define TRACEFS_DENY_PERMISSION_CAPABILITY_ENABLE \
49 	TRACEFS_LANDLOCK_DIR "/landlock_deny_permission_capability/enable"
50 #define TRACEFS_DENY_PTRACE_ENABLE \
51 	TRACEFS_LANDLOCK_DIR "/landlock_deny_ptrace/enable"
52 #define TRACEFS_DENY_SCOPE_SIGNAL_ENABLE \
53 	TRACEFS_LANDLOCK_DIR "/landlock_deny_scope_signal/enable"
54 #define TRACEFS_DENY_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE \
55 	TRACEFS_LANDLOCK_DIR                           \
56 	"/landlock_deny_scope_abstract_unix_socket/enable"
57 #define TRACEFS_FREE_DOMAIN_ENABLE \
58 	TRACEFS_LANDLOCK_DIR "/landlock_free_domain/enable"
59 #define TRACEFS_FREE_RULESET_ENABLE \
60 	TRACEFS_LANDLOCK_DIR "/landlock_free_ruleset/enable"
61 #define TRACEFS_TRACE TRACEFS_ROOT "/trace"
62 #define TRACEFS_SET_EVENT_PID TRACEFS_ROOT "/set_event_pid"
63 #define TRACEFS_OPTIONS_EVENT_FORK TRACEFS_ROOT "/options/event-fork"
64 
65 #define TRACE_BUFFER_SIZE (64 * 1024)
66 
67 /*
68  * Trace line prefix: matches the ftrace "trace" file format.  Format: "
69  * <task>-<pid> [<cpu>] <flags> <timestamp>: "
70  *
71  * The task parameter must be a string literal truncated to 15 chars
72  * (TASK_COMM_LEN - 1), matching what the kernel stores in task->comm.  The
73  * pattern accepts either the expected task name or "<...>" because the ftrace
74  * comm cache may evict short-lived processes (e.g., forked children that exit
75  * before the trace buffer is read).
76  *
77  * No unescaped '.' in any REGEX macro; literal dots use '\\.'.
78  */
79 #define TRACE_PREFIX(task)  \
80 	"^ *\\(<\\.\\.\\.>" \
81 	"\\|" task "\\)"    \
82 	"-[0-9]\\+ *\\[[0-9]\\+\\] [^ ]\\+ \\+[0-9]\\+\\.[0-9]\\+: "
83 
84 /*
85  * Task name for events emitted by kworker threads (e.g., free_domain fires from
86  * a work queue, not from the test process).
87  */
88 #define KWORKER_TASK "kworker/[0-9]\\+:[0-9]\\+"
89 
90 #define REGEX_ADD_RULE_PATH_BENEATH(task)  \
91 	TRACE_PREFIX(task)                 \
92 	"landlock_add_rule_path_beneath: " \
93 	"ruleset=[0-9a-f]\\+\\.[0-9]\\+ "  \
94 	"access_rights=[a-z_|]* "          \
95 	"dev=[0-9]\\+:[0-9]\\+ "           \
96 	"ino=[0-9]\\+ "                    \
97 	"path=[^ ]\\+$"
98 
99 #define REGEX_ADD_RULE_NET_PORT(task)     \
100 	TRACE_PREFIX(task)                \
101 	"landlock_add_rule_net_port: "    \
102 	"ruleset=[0-9a-f]\\+\\.[0-9]\\+ " \
103 	"access_rights=[a-z_|]* "         \
104 	"port=[0-9]\\+$"
105 
106 #define REGEX_ADD_RULE_NAMESPACE_VERSION(task, version) \
107 	TRACE_PREFIX(task)                              \
108 	"landlock_add_rule_namespace: "                 \
109 	"ruleset=[0-9a-f]\\+\\." version " "            \
110 	"permissions=[a-z._|]* "                        \
111 	"allowed_namespace_types=0x[0-9a-f]\\+ "        \
112 	"quiet_namespace_types=0x[0-9a-f]\\+$"
113 
114 #define REGEX_ADD_RULE_NAMESPACE(task) \
115 	REGEX_ADD_RULE_NAMESPACE_VERSION(task, "[0-9]\\+")
116 
117 #define REGEX_ADD_RULE_CAPABILITY_VERSION(task, version) \
118 	TRACE_PREFIX(task)                               \
119 	"landlock_add_rule_capability: "                 \
120 	"ruleset=[0-9a-f]\\+\\." version " "             \
121 	"permissions=[a-z._|]* "                         \
122 	"allowed_capabilities=0x[0-9a-f]\\+ "            \
123 	"quiet_capabilities=0x[0-9a-f]\\+$"
124 
125 #define REGEX_ADD_RULE_CAPABILITY(task) \
126 	REGEX_ADD_RULE_CAPABILITY_VERSION(task, "[0-9]\\+")
127 
128 #define REGEX_CREATE_RULESET(task)        \
129 	TRACE_PREFIX(task)                \
130 	"landlock_create_ruleset: "       \
131 	"ruleset=[0-9a-f]\\+\\.[0-9]\\+ " \
132 	"handled_fs=[a-z_|]* "            \
133 	"handled_net=[a-z_|]* "           \
134 	"scoped=[a-z_|]* "                \
135 	"handled_permissions=[a-z._|]*$"
136 
137 #define REGEX_CREATE_DOMAIN(task)  \
138 	TRACE_PREFIX(task)         \
139 	"landlock_create_domain: " \
140 	"domain=[0-9a-f]\\+ "      \
141 	"parent=[0-9a-f]\\+ "      \
142 	"ruleset=[0-9a-f]\\+\\.[0-9]\\+$"
143 
144 #define REGEX_CHECK_RULE_FS(task)     \
145 	TRACE_PREFIX(task)            \
146 	"landlock_check_rule_inode: " \
147 	"domain=[0-9a-f]\\+ "         \
148 	"access_request=[a-z_|]* "    \
149 	"dev=[0-9]\\+:[0-9]\\+ "      \
150 	"ino=[0-9]\\+ "               \
151 	"grants={[a-z_|,]*}$"
152 
153 #define REGEX_CHECK_RULE_NET(task)       \
154 	TRACE_PREFIX(task)               \
155 	"landlock_check_rule_net_port: " \
156 	"domain=[0-9a-f]\\+ "            \
157 	"access_request=[a-z_|]* "       \
158 	"port=[0-9]\\+ "                 \
159 	"grants={[a-z_|,]*}$"
160 
161 #define REGEX_DENY_ACCESS_FS(task)  \
162 	TRACE_PREFIX(task)          \
163 	"landlock_deny_access_fs: " \
164 	"domain=[0-9a-f]\\+ "       \
165 	"same_exec=[01] "           \
166 	"logged=[01] "              \
167 	"blockers=[a-z_|]* "        \
168 	"dev=[0-9]\\+:[0-9]\\+ "    \
169 	"ino=[0-9]\\+ "             \
170 	"path=[^ ]*$"
171 
172 #define REGEX_DENY_ACCESS_NET(task)  \
173 	TRACE_PREFIX(task)           \
174 	"landlock_deny_access_net: " \
175 	"domain=[0-9a-f]\\+ "        \
176 	"same_exec=[01] "            \
177 	"logged=[01] "               \
178 	"blockers=[a-z_|]* "         \
179 	"port=-\\?[0-9]\\+$"
180 
181 #define REGEX_DENY_PERMISSION_NAMESPACE(task)  \
182 	TRACE_PREFIX(task)                     \
183 	"landlock_deny_permission_namespace: " \
184 	"domain=[0-9a-f]\\+ "                  \
185 	"same_exec=[01] "                      \
186 	"logged=[01] "                         \
187 	"blockers=[a-z_|]* "                   \
188 	"namespace_op=\\(create\\|enter\\) "   \
189 	"namespace_type=0x[0-9a-f]\\+ "        \
190 	"namespace_id=[0-9]\\+$"
191 
192 #define REGEX_DENY_PERMISSION_CAPABILITY(task)  \
193 	TRACE_PREFIX(task)                      \
194 	"landlock_deny_permission_capability: " \
195 	"domain=[0-9a-f]\\+ "                   \
196 	"same_exec=[01] "                       \
197 	"logged=[01] "                          \
198 	"blockers=[a-z_|]* "                    \
199 	"capability=[0-9]\\+$"
200 
201 #define REGEX_DENY_PTRACE(task)      \
202 	TRACE_PREFIX(task)           \
203 	"landlock_deny_ptrace: "     \
204 	"domain=[0-9a-f]\\+ "        \
205 	"same_exec=[01] "            \
206 	"logged=[01] "               \
207 	"tracee_domain=[0-9a-f]\\+ " \
208 	"tracee_pid=[0-9]\\+ "       \
209 	"tracee_comm=[^ ]*$"
210 
211 #define REGEX_DENY_SCOPE_SIGNAL(task)  \
212 	TRACE_PREFIX(task)             \
213 	"landlock_deny_scope_signal: " \
214 	"domain=[0-9a-f]\\+ "          \
215 	"same_exec=[01] "              \
216 	"logged=[01] "                 \
217 	"target_domain=[0-9a-f]\\+ "   \
218 	"target_pid=[0-9]\\+ "         \
219 	"target_comm=[^ ]*$"
220 
221 #define REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(task)  \
222 	TRACE_PREFIX(task)                           \
223 	"landlock_deny_scope_abstract_unix_socket: " \
224 	"domain=[0-9a-f]\\+ "                        \
225 	"same_exec=[01] "                            \
226 	"logged=[01] "                               \
227 	"peer_domain=[0-9a-f]\\+ "                   \
228 	"peer_pid=[0-9]\\+ "                         \
229 	"sun_path=[^ ]*$"
230 
231 #define REGEX_FREE_DOMAIN(task)  \
232 	TRACE_PREFIX(task)       \
233 	"landlock_free_domain: " \
234 	"domain=[0-9a-f]\\+ "    \
235 	"denials=[0-9]\\+$"
236 
237 #define REGEX_FREE_RULESET(task)  \
238 	TRACE_PREFIX(task)        \
239 	"landlock_free_ruleset: " \
240 	"ruleset=[0-9a-f]\\+\\.[0-9]\\+$"
241 
242 static int __maybe_unused tracefs_write(const char *path, const char *value)
243 {
244 	int fd;
245 	ssize_t ret;
246 	size_t len = strlen(value);
247 
248 	fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC);
249 	if (fd < 0)
250 		return -errno;
251 
252 	ret = write(fd, value, len);
253 	close(fd);
254 	if (ret < 0)
255 		return -errno;
256 	if ((size_t)ret != len)
257 		return -EIO;
258 
259 	return 0;
260 }
261 
262 static int __maybe_unused tracefs_write_int(const char *path, int value)
263 {
264 	char buf[32];
265 
266 	snprintf(buf, sizeof(buf), "%d", value);
267 	return tracefs_write(path, buf);
268 }
269 
270 static int __maybe_unused tracefs_setup(void)
271 {
272 	struct stat st;
273 
274 	/* Mount tracefs if not already mounted. */
275 	if (stat(TRACEFS_ROOT, &st) != 0) {
276 		int ret = mount("tracefs", TRACEFS_ROOT, "tracefs", 0, NULL);
277 
278 		if (ret)
279 			return -errno;
280 	}
281 
282 	/* Verify landlock events are available. */
283 	if (stat(TRACEFS_LANDLOCK_DIR, &st) != 0)
284 		return -ENOENT;
285 
286 	return 0;
287 }
288 
289 /*
290  * Set up PID-based event filtering so only events from the current process and
291  * its children are recorded.  This is analogous to audit's AUDIT_EXE filter: it
292  * prevents events from unrelated processes from polluting the trace buffer.
293  */
294 static int __maybe_unused tracefs_set_pid_filter(pid_t pid)
295 {
296 	int ret;
297 
298 	/* Enable event-fork so children inherit the PID filter. */
299 	ret = tracefs_write(TRACEFS_OPTIONS_EVENT_FORK, "1");
300 	if (ret)
301 		return ret;
302 
303 	return tracefs_write_int(TRACEFS_SET_EVENT_PID, pid);
304 }
305 
306 /* Clear the PID filter to stop filtering by PID. */
307 static int __maybe_unused tracefs_clear_pid_filter(void)
308 {
309 	return tracefs_write(TRACEFS_SET_EVENT_PID, "");
310 }
311 
312 static int __maybe_unused tracefs_enable_event(const char *enable_path,
313 					       bool enable)
314 {
315 	return tracefs_write(enable_path, enable ? "1" : "0");
316 }
317 
318 static int __maybe_unused tracefs_clear(void)
319 {
320 	return tracefs_write(TRACEFS_TRACE, "");
321 }
322 
323 /*
324  * Reads the trace buffer content into a newly allocated buffer.  The caller is
325  * responsible for freeing the returned buffer.  Returns NULL on error.
326  */
327 static char __maybe_unused *tracefs_read_trace(void)
328 {
329 	char *buf;
330 	int fd;
331 	ssize_t total = 0, ret;
332 
333 	buf = malloc(TRACE_BUFFER_SIZE);
334 	if (!buf)
335 		return NULL;
336 
337 	fd = open(TRACEFS_TRACE, O_RDONLY | O_CLOEXEC);
338 	if (fd < 0) {
339 		free(buf);
340 		return NULL;
341 	}
342 
343 	while (total < TRACE_BUFFER_SIZE - 1) {
344 		ret = read(fd, buf + total, TRACE_BUFFER_SIZE - 1 - total);
345 		if (ret <= 0)
346 			break;
347 		total += ret;
348 	}
349 	close(fd);
350 	buf[total] = '\0';
351 	return buf;
352 }
353 
354 /* Counts the number of lines in @buf matching the basic regex @pattern. */
355 static int __maybe_unused tracefs_count_matches(const char *buf,
356 						const char *pattern)
357 {
358 	regex_t regex;
359 	int count = 0;
360 	const char *line, *end;
361 
362 	if (regcomp(&regex, pattern, 0) != 0)
363 		return -EINVAL;
364 
365 	line = buf;
366 	while (*line) {
367 		end = strchr(line, '\n');
368 		if (!end)
369 			end = line + strlen(line);
370 
371 		/* Create a temporary NUL-terminated line. */
372 		size_t len = end - line;
373 		char *tmp = malloc(len + 1);
374 
375 		if (tmp) {
376 			memcpy(tmp, line, len);
377 			tmp[len] = '\0';
378 			if (regexec(&regex, tmp, 0, NULL, 0) == 0)
379 				count++;
380 			free(tmp);
381 		}
382 
383 		if (*end == '\n')
384 			line = end + 1;
385 		else
386 			break;
387 	}
388 
389 	regfree(&regex);
390 	return count;
391 }
392 
393 /*
394  * Extracts the value of a named field from a trace line in @buf.  Searches for
395  * the first line matching @line_pattern, then extracts the value after
396  * "@field_name=" into @out.  Stops at space or newline.
397  *
398  * Returns 0 on success, -ENOENT if no match.
399  */
400 static int __maybe_unused tracefs_extract_field(const char *buf,
401 						const char *line_pattern,
402 						const char *field_name,
403 						char *out, size_t out_size)
404 {
405 	regex_t regex;
406 	const char *line, *end;
407 
408 	if (regcomp(&regex, line_pattern, 0) != 0)
409 		return -EINVAL;
410 
411 	line = buf;
412 	while (*line) {
413 		end = strchr(line, '\n');
414 		if (!end)
415 			end = line + strlen(line);
416 
417 		size_t len = end - line;
418 		char *tmp = malloc(len + 1);
419 
420 		if (tmp) {
421 			const char *field, *val_start;
422 			size_t field_len, val_len;
423 
424 			memcpy(tmp, line, len);
425 			tmp[len] = '\0';
426 
427 			if (regexec(&regex, tmp, 0, NULL, 0) != 0) {
428 				free(tmp);
429 				goto next;
430 			}
431 
432 			/*
433 			 * Find "field_name=" in the line, ensuring a word
434 			 * boundary before the field name to avoid substring
435 			 * matches (e.g., "port" in "sport").
436 			 */
437 			field_len = strlen(field_name);
438 			field = tmp;
439 			while ((field = strstr(field, field_name))) {
440 				if (field[field_len] == '=' &&
441 				    (field == tmp || field[-1] == ' '))
442 					break;
443 				field++;
444 			}
445 			if (!field) {
446 				free(tmp);
447 				regfree(&regex);
448 				return -ENOENT;
449 			}
450 
451 			val_start = field + field_len + 1;
452 			val_len = 0;
453 			while (val_start[val_len] &&
454 			       val_start[val_len] != ' ' &&
455 			       val_start[val_len] != '\n')
456 				val_len++;
457 
458 			if (val_len >= out_size)
459 				val_len = out_size - 1;
460 			memcpy(out, val_start, val_len);
461 			out[val_len] = '\0';
462 
463 			free(tmp);
464 			regfree(&regex);
465 			return 0;
466 		}
467 next:
468 		if (*end == '\n')
469 			line = end + 1;
470 		else
471 			break;
472 	}
473 
474 	regfree(&regex);
475 	return -ENOENT;
476 }
477 
478 /*
479  * Common fixture setup for trace tests.  Mounts tracefs if needed and sets a
480  * PID filter.  The caller must create a mount namespace first
481  * (unshare(CLONE_NEWNS) + mount(MS_REC | MS_PRIVATE)) to isolate the tracefs
482  * mount; the trace buffer, per-event enable flags, and PID filter are global
483  * kernel state, scoped to the test by the PID filter.
484  *
485  * Returns 0 on success, -errno on failure (caller should SKIP).
486  */
487 static int __maybe_unused tracefs_fixture_setup(void)
488 {
489 	int ret;
490 
491 	ret = tracefs_setup();
492 	if (ret)
493 		return ret;
494 
495 	return tracefs_set_pid_filter(getpid());
496 }
497 
498 static void __maybe_unused tracefs_fixture_teardown(void)
499 {
500 	tracefs_clear_pid_filter();
501 }
502 
503 /*
504  * Temporarily raises CAP_SYS_ADMIN effective capability, calls @func, then
505  * drops the capability.  Returns the value from @func, or -EPERM if the
506  * capability manipulation fails.
507  */
508 static int __maybe_unused tracefs_priv_call(int (*func)(void))
509 {
510 	const cap_value_t admin = CAP_SYS_ADMIN;
511 	cap_t cap_p;
512 	int ret;
513 
514 	cap_p = cap_get_proc();
515 	if (!cap_p)
516 		return -EPERM;
517 
518 	if (cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_SET) ||
519 	    cap_set_proc(cap_p)) {
520 		cap_free(cap_p);
521 		return -EPERM;
522 	}
523 
524 	ret = func();
525 
526 	cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_CLEAR);
527 	cap_set_proc(cap_p);
528 	cap_free(cap_p);
529 	return ret;
530 }
531 
532 /* Read the trace buffer with elevated privileges.  Returns NULL on failure. */
533 static char __maybe_unused *tracefs_read_buf(void)
534 {
535 	/* Cannot use tracefs_priv_call() because the return type is char *. */
536 	cap_t cap_p;
537 	char *buf;
538 	const cap_value_t admin = CAP_SYS_ADMIN;
539 
540 	cap_p = cap_get_proc();
541 	if (!cap_p)
542 		return NULL;
543 
544 	if (cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_SET) ||
545 	    cap_set_proc(cap_p)) {
546 		cap_free(cap_p);
547 		return NULL;
548 	}
549 
550 	buf = tracefs_read_trace();
551 
552 	cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_CLEAR);
553 	cap_set_proc(cap_p);
554 	cap_free(cap_p);
555 	return buf;
556 }
557 
558 /* Clear the trace buffer with elevated privileges.  Returns 0 on success. */
559 static int __maybe_unused tracefs_clear_buf(void)
560 {
561 	return tracefs_priv_call(tracefs_clear);
562 }
563 
564 /*
565  * Forks a child that creates a Landlock sandbox and performs an FS access.  The
566  * parent waits for the child, then reads the trace buffer.
567  *
568  * Requires common.h and wrappers.h to be included before trace.h.
569  */
570 static void __maybe_unused sandbox_child_fs_access(
571 	struct __test_metadata *const _metadata, const char *rule_path,
572 	__u64 handled_access, __u64 allowed_access, const char *access_path)
573 {
574 	pid_t pid;
575 	int status;
576 
577 	pid = fork();
578 	ASSERT_LE(0, pid);
579 
580 	if (pid == 0) {
581 		struct landlock_ruleset_attr ruleset_attr = {
582 			.handled_access_fs = handled_access,
583 		};
584 		struct landlock_path_beneath_attr path_beneath = {
585 			.allowed_access = allowed_access,
586 		};
587 		int ruleset_fd, fd;
588 
589 		ruleset_fd = landlock_create_ruleset(&ruleset_attr,
590 						     sizeof(ruleset_attr), 0);
591 		if (ruleset_fd < 0)
592 			_exit(1);
593 
594 		path_beneath.parent_fd =
595 			open(rule_path, O_PATH | O_DIRECTORY | O_CLOEXEC);
596 		if (path_beneath.parent_fd < 0) {
597 			close(ruleset_fd);
598 			_exit(1);
599 		}
600 
601 		if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
602 				      &path_beneath, 0)) {
603 			close(path_beneath.parent_fd);
604 			close(ruleset_fd);
605 			_exit(1);
606 		}
607 		close(path_beneath.parent_fd);
608 
609 		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
610 		if (landlock_restrict_self(ruleset_fd, 0)) {
611 			close(ruleset_fd);
612 			_exit(1);
613 		}
614 		close(ruleset_fd);
615 
616 		fd = open(access_path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
617 		if (fd >= 0)
618 			close(fd);
619 
620 		_exit(0);
621 	}
622 
623 	ASSERT_EQ(pid, waitpid(pid, &status, 0));
624 	ASSERT_TRUE(WIFEXITED(status));
625 	EXPECT_EQ(0, WEXITSTATUS(status));
626 }
627 
628 /*
629  * Forks a child that creates a Landlock sandbox allowing execute+read_dir for
630  * /usr and execute-only for ".", then execs ./true.  The true binary opens "."
631  * on startup, triggering a read_dir denial with same_exec=0.  The parent waits
632  * for the child to exit.
633  */
634 static void __maybe_unused sandbox_child_exec_true(
635 	struct __test_metadata *const _metadata, __u32 restrict_flags)
636 {
637 	pid_t pid;
638 	int status;
639 
640 	pid = fork();
641 	ASSERT_LE(0, pid);
642 
643 	if (pid == 0) {
644 		struct landlock_ruleset_attr attr = {
645 			.handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR |
646 					     LANDLOCK_ACCESS_FS_EXECUTE,
647 		};
648 		struct landlock_path_beneath_attr path_beneath = {
649 			.allowed_access = LANDLOCK_ACCESS_FS_EXECUTE |
650 					  LANDLOCK_ACCESS_FS_READ_DIR,
651 		};
652 		int ruleset_fd;
653 
654 		ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
655 		if (ruleset_fd < 0)
656 			_exit(1);
657 
658 		path_beneath.parent_fd =
659 			open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
660 		if (path_beneath.parent_fd >= 0) {
661 			landlock_add_rule(ruleset_fd,
662 					  LANDLOCK_RULE_PATH_BENEATH,
663 					  &path_beneath, 0);
664 			close(path_beneath.parent_fd);
665 		}
666 
667 		path_beneath.allowed_access = LANDLOCK_ACCESS_FS_EXECUTE;
668 		path_beneath.parent_fd =
669 			open(".", O_PATH | O_DIRECTORY | O_CLOEXEC);
670 		if (path_beneath.parent_fd >= 0) {
671 			landlock_add_rule(ruleset_fd,
672 					  LANDLOCK_RULE_PATH_BENEATH,
673 					  &path_beneath, 0);
674 			close(path_beneath.parent_fd);
675 		}
676 
677 		prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
678 		if (landlock_restrict_self(ruleset_fd, restrict_flags))
679 			_exit(1);
680 		close(ruleset_fd);
681 
682 		execl("./true", "./true", NULL);
683 		_exit(1);
684 	}
685 
686 	ASSERT_EQ(pid, waitpid(pid, &status, 0));
687 	ASSERT_TRUE(WIFEXITED(status));
688 	EXPECT_EQ(0, WEXITSTATUS(status));
689 }
690