]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/test/test-execute.c
ci: re-enable uefi secure boot
[thirdparty/systemd.git] / src / test / test-execute.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
281e05b6 2
6553db60 3#include <fnmatch.h>
8e091ec4 4#include <linux/prctl.h>
ff4ca461 5#include <stdio.h>
fa34123c 6#include <stdlib.h>
4e032f65 7#include <sys/mount.h>
70d7aea5 8#include <sys/prctl.h>
4f18ff2e 9#include <unistd.h>
281e05b6 10
42867dfe
YW
11#include "sd-event.h"
12
fa34123c 13#include "argv-util.h"
3ebd5986 14#include "build-path.h"
b7856f92 15#include "capability-util.h"
8c35c10d 16#include "copy.h"
1cf40697 17#include "cpu-set-util.h"
42867dfe 18#include "dropin.h"
b4891260 19#include "errno-list.h"
fa34123c 20#include "extract-word.h"
42867dfe 21#include "fd-util.h"
03bd70dd 22#include "fileio.h"
f4f15635 23#include "fs-util.h"
f4f15635 24#include "manager.h"
281e05b6 25#include "mkdir.h"
4e032f65 26#include "mount-util.h"
ff4ca461 27#include "path-util.h"
42867dfe 28#include "process-util.h"
c6878637 29#include "rm-rf.h"
83f12b27 30#include "seccomp-util.h"
57b7a260 31#include "service.h"
42867dfe 32#include "signal-util.h"
34b86909 33#include "stat-util.h"
1cf40697 34#include "static-destruct.h"
fa34123c 35#include "strv.h"
70aece81 36#include "sysctl-util.h"
cc100a5a 37#include "tests.h"
f4f15635 38#include "unit.h"
57c2efa0 39#include "user-util.h"
4dd4cb8f 40#include "virt.h"
281e05b6 41
4e032f65
YW
42#define PRIVATE_UNIT_DIR "/run/test-execute-unit-dir"
43
42867dfe 44static char *user_runtime_unit_dir = NULL;
5f00dc4d 45static bool can_unshare;
8a87a16b 46static bool have_net_dummy;
76808638 47static bool have_netns;
b6349ffd 48static unsigned n_ran_tests = 0;
b7172f34 49
42867dfe
YW
50STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
51
281e05b6
RC
52typedef void (*test_function_t)(Manager *m);
53
c3ab2c38
LP
54static int cld_dumped_to_killed(int code) {
55 /* Depending on the system, seccomp version, … some signals might result in dumping, others in plain
56 * killing. Let's ignore the difference here, and map both cases to CLD_KILLED */
57 return code == CLD_DUMPED ? CLD_KILLED : code;
58}
59
f0d76134
YW
60_noreturn_
61static int time_handler(sd_event_source *s, uint64_t usec, void *userdata) {
62 Unit *unit = ASSERT_PTR(userdata);
63 int r;
64
65 log_error("Test timeout when testing %s", unit->id);
0f23564a 66 r = unit_kill(unit, KILL_ALL, /* subgroup= */ NULL, SIGKILL, SI_USER, /* value= */ 0, /* ret_error= */ NULL);
f0d76134
YW
67 if (r < 0)
68 log_error_errno(r, "Failed to kill %s, ignoring: %m", unit->id);
69
70 abort();
71}
72
31cd5f63 73static void wait_for_service_finish(Manager *m, Unit *unit) {
f0d76134 74 Service *service = SERVICE(ASSERT_PTR(unit));
8adb3d63 75 usec_t timeout = 2 * USEC_PER_MINUTE;
281e05b6 76
26d79ab8 77 ASSERT_NOT_NULL(m);
281e05b6 78
75c8b980
FS
79 /* Bump the timeout when running in plain QEMU, as some more involved tests might start hitting the
80 * default 2m timeout (like exec-dynamicuser-statedir.service) */
81 if (detect_virtualization() == VIRTUALIZATION_QEMU)
82 timeout *= 2;
83
281e05b6
RC
84 printf("%s\n", unit->id);
85 exec_context_dump(&service->exec_context, stdout, "\t");
f0d76134
YW
86
87 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
88 ASSERT_OK(sd_event_add_time_relative(m->event, &s, CLOCK_MONOTONIC, timeout, 0, time_handler, unit));
89
90 /* Here, sd_event_loop() cannot be used, as the sd_event object will be reused in the next test case. */
91 while (!IN_SET(service->state, SERVICE_DEAD, SERVICE_FAILED))
92 ASSERT_OK(sd_event_run(m->event, 100 * USEC_PER_MSEC));
31cd5f63
AZ
93}
94
fe65d692
ZJS
95static void check_main_result(const char *file, unsigned line, const char *func,
96 Manager *m, Unit *unit, int status_expected, int code_expected) {
31cd5f63
AZ
97 Service *service = NULL;
98
26d79ab8
DDM
99 ASSERT_NOT_NULL(m);
100 ASSERT_NOT_NULL(unit);
31cd5f63
AZ
101
102 wait_for_service_finish(m, unit);
103
104 service = SERVICE(unit);
281e05b6 105 exec_status_dump(&service->main_exec_status, stdout, "\t");
18f8c5d4 106
c3ab2c38 107 if (cld_dumped_to_killed(service->main_exec_status.code) != cld_dumped_to_killed(code_expected)) {
aa272751
YW
108 log_error("%s:%u:%s %s: can_unshare=%s: exit code %d, expected %d",
109 file, line, func, unit->id, yes_no(can_unshare),
6aed6a11
ZJS
110 service->main_exec_status.code, code_expected);
111 abort();
18f8c5d4
LP
112 }
113
114 if (service->main_exec_status.status != status_expected) {
aa272751
YW
115 log_error("%s:%u:%s: %s: can_unshare=%s: exit status %d, expected %d",
116 file, line, func, unit->id, yes_no(can_unshare),
18f8c5d4
LP
117 service->main_exec_status.status, status_expected);
118 abort();
6aed6a11 119 }
281e05b6
RC
120}
121
fe65d692
ZJS
122static void check_service_result(const char *file, unsigned line, const char *func,
123 Manager *m, Unit *unit, ServiceResult result_expected) {
31cd5f63
AZ
124 Service *service = NULL;
125
26d79ab8
DDM
126 ASSERT_NOT_NULL(m);
127 ASSERT_NOT_NULL(unit);
31cd5f63
AZ
128
129 wait_for_service_finish(m, unit);
130
131 service = SERVICE(unit);
132
133 if (service->result != result_expected) {
aa272751
YW
134 log_error("%s:%u:%s: %s: can_unshare=%s: service end result %s, expected %s",
135 file, line, func, unit->id, yes_no(can_unshare),
31cd5f63
AZ
136 service_result_to_string(service->result),
137 service_result_to_string(result_expected));
138 abort();
139 }
140}
141
57c2efa0
YW
142static bool check_nobody_user_and_group(void) {
143 static int cache = -1;
144 struct passwd *p;
145 struct group *g;
146
147 if (cache >= 0)
148 return !!cache;
149
150 if (!synthesize_nobody())
151 goto invalid;
152
153 p = getpwnam(NOBODY_USER_NAME);
154 if (!p ||
155 !streq(p->pw_name, NOBODY_USER_NAME) ||
156 p->pw_uid != UID_NOBODY ||
157 p->pw_gid != GID_NOBODY)
158 goto invalid;
159
160 p = getpwuid(UID_NOBODY);
161 if (!p ||
162 !streq(p->pw_name, NOBODY_USER_NAME) ||
163 p->pw_uid != UID_NOBODY ||
164 p->pw_gid != GID_NOBODY)
165 goto invalid;
166
167 g = getgrnam(NOBODY_GROUP_NAME);
168 if (!g ||
169 !streq(g->gr_name, NOBODY_GROUP_NAME) ||
170 g->gr_gid != GID_NOBODY)
171 goto invalid;
172
173 g = getgrgid(GID_NOBODY);
174 if (!g ||
175 !streq(g->gr_name, NOBODY_GROUP_NAME) ||
176 g->gr_gid != GID_NOBODY)
177 goto invalid;
178
179 cache = 1;
180 return true;
181
182invalid:
183 cache = 0;
184 return false;
185}
186
9f82d685
YW
187static bool check_user_has_group_with_same_name(const char *name) {
188 struct passwd *p;
189 struct group *g;
190
26d79ab8 191 ASSERT_NOT_NULL(name);
9f82d685
YW
192
193 p = getpwnam(name);
194 if (!p ||
195 !streq(p->pw_name, name))
196 return false;
197
198 g = getgrgid(p->pw_gid);
199 if (!g ||
200 !streq(g->gr_name, name))
201 return false;
202
203 return true;
204}
205
6086d2da 206static bool is_inaccessible_available(void) {
6086d2da 207 FOREACH_STRING(p,
5980d463
ZJS
208 "/run/systemd/inaccessible/reg",
209 "/run/systemd/inaccessible/dir",
210 "/run/systemd/inaccessible/chr",
211 "/run/systemd/inaccessible/blk",
212 "/run/systemd/inaccessible/fifo",
213 "/run/systemd/inaccessible/sock")
6086d2da
DP
214 if (access(p, F_OK) < 0)
215 return false;
6086d2da
DP
216
217 return true;
218}
219
fc6172b1
RP
220static void start_parent_slices(Unit *unit) {
221 Unit *slice;
222
223 slice = UNIT_GET_SLICE(unit);
224 if (slice) {
225 start_parent_slices(slice);
ea64d550 226 ASSERT_OK_OR(unit_start(slice, NULL), -EALREADY);
fc6172b1
RP
227 }
228}
229
70aece81
NR
230static bool apparmor_restrict_unprivileged_userns(void) {
231 _cleanup_free_ char *v = NULL;
232 int r;
233
234 /* If kernel.apparmor_restrict_unprivileged_userns=1, then we cannot
235 * use unprivileged user namespaces. */
236 r = sysctl_read("kernel/apparmor_restrict_unprivileged_userns", &v);
237 if (r < 0) {
238 if (r != -ENOENT)
239 log_debug_errno(r, "Failed to read kernel.apparmor_restrict_unprivileged_userns sysctl, ignoring: %m");
240
241 return false;
242 }
243
244 return streq(v, "1");
245}
246
d0c6136f
NR
247static bool have_userns_privileges(void) {
248 pid_t pid;
249 int r;
250
70aece81
NR
251 if (apparmor_restrict_unprivileged_userns())
252 return false;
253
d0c6136f
NR
254 r = safe_fork("(sd-test-check-userns)",
255 FORK_RESET_SIGNALS |
256 FORK_CLOSE_ALL_FDS |
257 FORK_DEATHSIG_SIGKILL,
258 &pid);
26d79ab8 259 ASSERT_OK(r);
d0c6136f
NR
260 if (r == 0) {
261 /* Keep CAP_SYS_ADMIN if we have it to ensure we give an
262 * accurate result to the caller. Some kernels have a
263 * kernel.unprivileged_userns_clone sysctl which can be
264 * configured to make CLONE_NEWUSER require CAP_SYS_ADMIN.
265 * Additionally, AppArmor may restrict unprivileged user
266 * namespace creation. */
267 r = capability_bounding_set_drop(UINT64_C(1) << CAP_SYS_ADMIN, /* right_now = */ true);
268 if (r < 0) {
269 log_debug_errno(r, "Failed to drop capabilities: %m");
270 _exit(2);
271 }
272
273 r = RET_NERRNO(unshare(CLONE_NEWUSER));
274 if (r < 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
275 log_debug_errno(r, "Failed to create user namespace: %m");
276
277 _exit(r >= 0 ? EXIT_SUCCESS : ERRNO_IS_NEG_PRIVILEGE(r) ? EXIT_FAILURE : 2);
278 }
279
280 /* The exit code records the result of the check:
281 * EXIT_SUCCESS => we can use user namespaces
282 * EXIT_FAILURE => we can NOT use user namespaces
283 * 2 => some other error occurred */
284 r = wait_for_terminate_and_check("(sd-test-check-userns)", pid, 0);
285 if (!IN_SET(r, EXIT_SUCCESS, EXIT_FAILURE))
286 log_debug("Failed to check if user namespaces can be used, assuming not.");
287
288 return r == EXIT_SUCCESS;
289}
290
fe65d692
ZJS
291static void _test(const char *file, unsigned line, const char *func,
292 Manager *m, const char *unit_name, int status_expected, int code_expected) {
281e05b6
RC
293 Unit *unit;
294
26d79ab8 295 ASSERT_NOT_NULL(unit_name);
281e05b6 296
26d79ab8 297 ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit));
fc6172b1
RP
298 /* We need to start the slices as well otherwise the slice cgroups might be pruned
299 * in on_cgroup_empty_event. */
300 start_parent_slices(unit);
26d79ab8 301 ASSERT_OK(unit_start(unit, NULL));
fe65d692 302 check_main_result(file, line, func, m, unit, status_expected, code_expected);
b6349ffd
LB
303
304 ++n_ran_tests;
31cd5f63 305}
fe65d692
ZJS
306#define test(m, unit_name, status_expected, code_expected) \
307 _test(PROJECT_FILE, __LINE__, __func__, m, unit_name, status_expected, code_expected)
31cd5f63 308
fe65d692
ZJS
309static void _test_service(const char *file, unsigned line, const char *func,
310 Manager *m, const char *unit_name, ServiceResult result_expected) {
31cd5f63
AZ
311 Unit *unit;
312
26d79ab8 313 ASSERT_NOT_NULL(unit_name);
31cd5f63 314
26d79ab8
DDM
315 ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit));
316 ASSERT_OK(unit_start(unit, NULL));
fe65d692 317 check_service_result(file, line, func, m, unit, result_expected);
281e05b6 318}
fe65d692
ZJS
319#define test_service(m, unit_name, result_expected) \
320 _test_service(PROJECT_FILE, __LINE__, __func__, m, unit_name, result_expected)
281e05b6 321
f0e018e7 322static void test_exec_bindpaths(Manager *m) {
26d79ab8
DDM
323 ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths", 0755));
324 ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths", 0755));
d053b72b 325
fe65d692 326 test(m, "exec-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
d053b72b 327
f0e018e7
YW
328 (void) rm_rf("/tmp/test-exec-bindpaths", REMOVE_ROOT|REMOVE_PHYSICAL);
329 (void) rm_rf("/tmp/test-exec-bindreadonlypaths", REMOVE_ROOT|REMOVE_PHYSICAL);
d053b72b
YW
330}
331
4e79aeaa 332static void test_exec_cpuaffinity(Manager *m) {
296fe3d5 333 _cleanup_(cpu_set_done) CPUSet c = {};
4e79aeaa 334
26d79ab8
DDM
335 ASSERT_OK(cpu_set_realloc(&c, 8192)); /* just allocate the maximum possible size */
336 ASSERT_OK_ERRNO(sched_getaffinity(0, c.allocated, c.set));
4e79aeaa 337
167a776d 338 if (!CPU_ISSET_S(0, c.allocated, c.set)) {
4e79aeaa
YW
339 log_notice("Cannot use CPU 0, skipping %s", __func__);
340 return;
341 }
342
fe65d692
ZJS
343 test(m, "exec-cpuaffinity1.service", 0, CLD_EXITED);
344 test(m, "exec-cpuaffinity2.service", 0, CLD_EXITED);
4e79aeaa 345
167a776d
ZJS
346 if (!CPU_ISSET_S(1, c.allocated, c.set) ||
347 !CPU_ISSET_S(2, c.allocated, c.set)) {
4e79aeaa
YW
348 log_notice("Cannot use CPU 1 or 2, skipping remaining tests in %s", __func__);
349 return;
350 }
351
fe65d692 352 test(m, "exec-cpuaffinity3.service", 0, CLD_EXITED);
4e79aeaa
YW
353}
354
b7cca6cc
YW
355static void test_exec_credentials(Manager *m) {
356 test(m, "exec-set-credential.service", 0, CLD_EXITED);
c443f692
YW
357 test(m, "exec-load-credential.service", 0, CLD_EXITED);
358 test(m, "exec-credentials-dir-specifier.service", 0, CLD_EXITED);
b7cca6cc
YW
359}
360
281e05b6 361static void test_exec_workingdirectory(Manager *m) {
26d79ab8 362 ASSERT_OK(mkdir_p("/tmp/test-exec_workingdirectory", 0755));
281e05b6 363
fe65d692
ZJS
364 test(m, "exec-workingdirectory.service", 0, CLD_EXITED);
365 test(m, "exec-workingdirectory-trailing-dot.service", 0, CLD_EXITED);
281e05b6 366
c6878637 367 (void) rm_rf("/tmp/test-exec_workingdirectory", REMOVE_ROOT|REMOVE_PHYSICAL);
281e05b6
RC
368}
369
8c35c10d 370static void test_exec_execsearchpath(Manager *m) {
26d79ab8 371 ASSERT_OK(mkdir_p("/tmp/test-exec_execsearchpath", 0755));
8c35c10d 372
26d79ab8 373 ASSERT_OK(copy_file("/bin/ls", "/tmp/test-exec_execsearchpath/ls_temp", 0, 0777, COPY_REPLACE));
8c35c10d 374
375 test(m, "exec-execsearchpath.service", 0, CLD_EXITED);
376
26d79ab8 377 ASSERT_OK(rm_rf("/tmp/test-exec_execsearchpath", REMOVE_ROOT|REMOVE_PHYSICAL));
8c35c10d 378
379 test(m, "exec-execsearchpath.service", EXIT_EXEC, CLD_EXITED);
380}
381
382static void test_exec_execsearchpath_specifier(Manager *m) {
383 test(m, "exec-execsearchpath-unit-specifier.service", 0, CLD_EXITED);
384}
385
386static void test_exec_execsearchpath_environment(Manager *m) {
387 test(m, "exec-execsearchpath-environment.service", 0, CLD_EXITED);
388 test(m, "exec-execsearchpath-environment-path-set.service", 0, CLD_EXITED);
389}
390
391static void test_exec_execsearchpath_environment_files(Manager *m) {
392 static const char path_not_set[] =
393 "VAR1='word1 word2'\n"
394 "VAR2=word3 \n"
395 "# comment1\n"
396 "\n"
397 "; comment2\n"
398 " ; # comment3\n"
399 "line without an equal\n"
400 "VAR3='$word 5 6'\n"
401 "VAR4='new\nline'\n"
402 "VAR5=password\\with\\backslashes";
403
404 static const char path_set[] =
405 "VAR1='word1 word2'\n"
406 "VAR2=word3 \n"
407 "# comment1\n"
408 "\n"
409 "; comment2\n"
410 " ; # comment3\n"
411 "line without an equal\n"
412 "VAR3='$word 5 6'\n"
413 "VAR4='new\nline'\n"
414 "VAR5=password\\with\\backslashes\n"
415 "PATH=/usr";
416
417 int r;
418
419 r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile.conf", path_not_set, WRITE_STRING_FILE_CREATE);
26d79ab8 420 ASSERT_OK(r);
8c35c10d 421
422 test(m, "exec-execsearchpath-environmentfile.service", 0, CLD_EXITED);
423
424 (void) unlink("/tmp/test-exec_environmentfile.conf");
425
8c35c10d 426 r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile-set.conf", path_set, WRITE_STRING_FILE_CREATE);
26d79ab8 427 ASSERT_OK(r);
8c35c10d 428
429 test(m, "exec-execsearchpath-environmentfile-set.service", 0, CLD_EXITED);
430
431 (void) unlink("/tmp/test-exec_environmentfile-set.conf");
432}
433
434static void test_exec_execsearchpath_passenvironment(Manager *m) {
26d79ab8
DDM
435 ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
436 ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
437 ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
438 ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
439 ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
8c35c10d 440
441 test(m, "exec-execsearchpath-passenvironment.service", 0, CLD_EXITED);
442
26d79ab8 443 ASSERT_OK_ERRNO(setenv("PATH", "/usr", 1));
8c35c10d 444 test(m, "exec-execsearchpath-passenvironment-set.service", 0, CLD_EXITED);
445
26d79ab8
DDM
446 ASSERT_OK_ERRNO(unsetenv("VAR1"));
447 ASSERT_OK_ERRNO(unsetenv("VAR2"));
448 ASSERT_OK_ERRNO(unsetenv("VAR3"));
449 ASSERT_OK_ERRNO(unsetenv("VAR4"));
450 ASSERT_OK_ERRNO(unsetenv("VAR5"));
451 ASSERT_OK_ERRNO(unsetenv("PATH"));
8c35c10d 452}
453
281e05b6 454static void test_exec_personality(Manager *m) {
281e05b6 455#if defined(__x86_64__)
fe65d692 456 test(m, "exec-personality-x86-64.service", 0, CLD_EXITED);
7517f51e 457
1b0cc135
LB
458#elif defined(__s390x__)
459 test(m, "exec-personality-s390x.service", 0, CLD_EXITED);
460
7517f51e 461#elif defined(__s390__)
fe65d692 462 test(m, "exec-personality-s390.service", 0, CLD_EXITED);
7517f51e 463
12591863
JS
464#elif defined(__powerpc64__)
465# if __BYTE_ORDER == __BIG_ENDIAN
fe65d692 466 test(m, "exec-personality-ppc64.service", 0, CLD_EXITED);
12591863 467# else
fe65d692 468 test(m, "exec-personality-ppc64le.service", 0, CLD_EXITED);
12591863
JS
469# endif
470
471#elif defined(__aarch64__)
fe65d692 472 test(m, "exec-personality-aarch64.service", 0, CLD_EXITED);
12591863 473
5798eb4c 474#elif defined(__i386__)
fe65d692 475 test(m, "exec-personality-x86.service", 0, CLD_EXITED);
f106a639 476#elif defined(__loongarch_lp64)
646b0112 477 test(m, "exec-personality-loongarch64.service", 0, CLD_EXITED);
f0e018e7
YW
478#else
479 log_notice("Unknown personality, skipping %s", __func__);
281e05b6
RC
480#endif
481}
482
483static void test_exec_ignoresigpipe(Manager *m) {
fe65d692
ZJS
484 test(m, "exec-ignoresigpipe-yes.service", 0, CLD_EXITED);
485 test(m, "exec-ignoresigpipe-no.service", SIGPIPE, CLD_KILLED);
281e05b6
RC
486}
487
488static void test_exec_privatetmp(Manager *m) {
26d79ab8 489 ASSERT_OK(touch("/tmp/test-exec_privatetmp"));
281e05b6 490
d0c6136f
NR
491 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
492 test(m, "exec-privatetmp-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
493 test(m, "exec-privatetmp-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
3e320dc6 494
c4f79e09
MY
495 (void) unlink("/tmp/test-exec_privatetmp_disconnected");
496 test(m, "exec-privatetmp-disconnected-nodefaultdeps-nor-sandboxing.service", 0, CLD_EXITED);
497 ASSERT_OK_ERRNO(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
498
3e320dc6
YW
499 FOREACH_STRING(s,
500 "exec-privatetmp-disconnected.service",
501 "exec-privatetmp-disconnected-defaultdependencies-no.service",
502 "exec-privatetmp-disconnected-requires-mounts-for-var.service",
503 "exec-privatetmp-disconnected-wants-mounts-for-var.service",
504 "exec-privatetmp-disconnected-after-and-requires-for-var.service",
505 "exec-privatetmp-disconnected-after-and-wants-for-var.service") {
506 (void) unlink("/tmp/test-exec_privatetmp_disconnected");
507 (void) unlink("/var/tmp/test-exec_privatetmp_disconnected");
508 test(m, s, can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
509 ASSERT_FAIL(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
510 ASSERT_FAIL(access("/var/tmp/test-exec_privatetmp_disconnected", F_OK));
511 }
d0c6136f
NR
512 }
513
fe65d692 514 test(m, "exec-privatetmp-no.service", 0, CLD_EXITED);
281e05b6 515
5000cea8 516 (void) unlink("/tmp/test-exec_privatetmp");
281e05b6
RC
517}
518
519static void test_exec_privatedevices(Manager *m) {
f0e018e7
YW
520 int r;
521
4dd4cb8f 522 if (detect_container() > 0) {
f0e018e7 523 log_notice("Testing in container, skipping %s", __func__);
4dd4cb8f
SM
524 return;
525 }
6086d2da 526 if (!is_inaccessible_available()) {
f0e018e7 527 log_notice("Testing without inaccessible, skipping %s", __func__);
6086d2da
DP
528 return;
529 }
530
d0c6136f
NR
531 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
532 test(m, "exec-privatedevices-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
533 if (access("/dev/kmsg", F_OK) >= 0)
534 test(m, "exec-privatedevices-bind.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
535 test(m, "exec-privatedevices-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
536 test(m, "exec-privatedevices-yes-with-group.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
537 }
538
fe65d692 539 test(m, "exec-privatedevices-no.service", 0, CLD_EXITED);
6086d2da 540
0608ba98
ZJS
541 /* We use capsh to test if the capabilities are
542 * properly set, so be sure that it exists */
f7bc0c32 543 r = find_executable("capsh", NULL);
0608ba98 544 if (r < 0) {
5cd33ccc 545 log_notice_errno(r, "Could not find capsh binary, skipping remaining tests in %s: %m", __func__);
6086d2da
DP
546 return;
547 }
548
d0c6136f
NR
549 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
550 test(m, "exec-privatedevices-yes-capability-mknod.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
551 test(m, "exec-privatedevices-yes-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
552 }
553
adeff822 554 test(m, "exec-privatedevices-no-capability-mknod.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
adeff822 555 test(m, "exec-privatedevices-no-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
615a1f4b
DH
556}
557
7e46b29b 558static void test_exec_protecthome(Manager *m) {
9ca58284
ZJS
559 if (!can_unshare) {
560 log_notice("Cannot reliably unshare, skipping %s", __func__);
561 return;
562 }
563
fe65d692 564 test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
7e46b29b
YW
565}
566
4982dbcc 567static void test_exec_protectkernelmodules(Manager *m) {
0608ba98
ZJS
568 int r;
569
3ae33295 570 if (detect_container() > 0) {
f0e018e7 571 log_notice("Testing in container, skipping %s", __func__);
3ae33295
DH
572 return;
573 }
6086d2da 574 if (!is_inaccessible_available()) {
f0e018e7 575 log_notice("Testing without inaccessible, skipping %s", __func__);
6086d2da
DP
576 return;
577 }
3ae33295 578
f7bc0c32 579 r = find_executable("capsh", NULL);
0608ba98 580 if (r < 0) {
5cd33ccc 581 log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
0608ba98
ZJS
582 return;
583 }
584
adeff822 585 test(m, "exec-protectkernelmodules-no-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
d0c6136f
NR
586
587 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
588 test(m, "exec-protectkernelmodules-yes-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
589 test(m, "exec-protectkernelmodules-yes-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
590 }
3ae33295
DH
591}
592
f78b36f0 593static void test_exec_readonlypaths(Manager *m) {
34b86909 594
d0c6136f
NR
595 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
596 test(m, "exec-readonlypaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
f0e018e7
YW
597
598 if (path_is_read_only_fs("/var") > 0) {
599 log_notice("Directory /var is readonly, skipping remaining tests in %s", __func__);
34b86909 600 return;
f0e018e7 601 }
34b86909 602
6ef721cb 603 test(m, "exec-readonlypaths.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
fe65d692 604 test(m, "exec-readonlypaths-with-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
6ef721cb 605 test(m, "exec-readonlypaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
cdfbd1fb
DH
606}
607
608static void test_exec_readwritepaths(Manager *m) {
34b86909 609
f0e018e7
YW
610 if (path_is_read_only_fs("/") > 0) {
611 log_notice("Root directory is readonly, skipping %s", __func__);
34b86909 612 return;
f0e018e7 613 }
34b86909 614
6ef721cb 615 test(m, "exec-readwritepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
cdfbd1fb
DH
616}
617
618static void test_exec_inaccessiblepaths(Manager *m) {
34b86909 619
f0e018e7
YW
620 if (!is_inaccessible_available()) {
621 log_notice("Testing without inaccessible, skipping %s", __func__);
34b86909 622 return;
f0e018e7 623 }
34b86909 624
d0c6136f
NR
625 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
626 test(m, "exec-inaccessiblepaths-sys.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
f78b36f0 627
f0e018e7
YW
628 if (path_is_read_only_fs("/") > 0) {
629 log_notice("Root directory is readonly, skipping remaining tests in %s", __func__);
af4af186
EV
630 return;
631 }
632
6ef721cb 633 test(m, "exec-inaccessiblepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
c090d74d
TR
634}
635
4dc76eb7 636#if !HAS_FEATURE_ADDRESS_SANITIZER
42867dfe
YW
637static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
638 char **result = userdata;
639 char buf[4096];
640 ssize_t l;
641
26d79ab8
DDM
642 ASSERT_NOT_NULL(s);
643 ASSERT_GT(fd, 0);
42867dfe
YW
644
645 l = read(fd, buf, sizeof(buf) - 1);
646 if (l < 0) {
647 if (errno == EAGAIN)
648 goto reenable;
649
650 return 0;
651 }
652 if (l == 0)
653 return 0;
654
655 buf[l] = '\0';
656 if (result)
26d79ab8 657 ASSERT_NOT_NULL(strextend(result, buf));
42867dfe
YW
658 else
659 log_error("ldd: %s", buf);
660
661reenable:
662 /* Re-enable the event source if we did not encounter EOF */
26d79ab8 663 ASSERT_OK(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT));
42867dfe
YW
664 return 0;
665}
666
667static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
668 pid_t *pid = userdata;
669
26d79ab8 670 ASSERT_NOT_NULL(pid);
42867dfe
YW
671
672 (void) kill(*pid, SIGKILL);
673
674 return 1;
675}
676
677static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
678 int ret = -EIO;
679
26d79ab8 680 ASSERT_NOT_NULL(si);
42867dfe
YW
681
682 if (si->si_code == CLD_EXITED)
683 ret = si->si_status;
684
685 sd_event_exit(sd_event_source_get_event(s), ret);
686 return 1;
687}
688
689static int find_libraries(const char *exec, char ***ret) {
690 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
691 _cleanup_(sd_event_source_unrefp) sd_event_source *sigchld_source = NULL;
692 _cleanup_(sd_event_source_unrefp) sd_event_source *stdout_source = NULL;
693 _cleanup_(sd_event_source_unrefp) sd_event_source *stderr_source = NULL;
71136404 694 _cleanup_close_pair_ int outpipe[2] = EBADF_PAIR, errpipe[2] = EBADF_PAIR;
42867dfe
YW
695 _cleanup_strv_free_ char **libraries = NULL;
696 _cleanup_free_ char *result = NULL;
697 pid_t pid;
698 int r;
699
26d79ab8
DDM
700 ASSERT_NOT_NULL(exec);
701 ASSERT_NOT_NULL(ret);
42867dfe 702
26d79ab8 703 ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD));
42867dfe 704
26d79ab8
DDM
705 ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
706 ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
42867dfe 707
0c2aedb4
YW
708 r = safe_fork_full("(spawn-ldd)",
709 (int[]) { -EBADF, outpipe[1], errpipe[1] },
710 NULL, 0,
e9ccae31 711 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_LOG, &pid);
26d79ab8 712 ASSERT_OK(r);
42867dfe 713 if (r == 0) {
42867dfe
YW
714 execlp("ldd", "ldd", exec, NULL);
715 _exit(EXIT_FAILURE);
716 }
717
718 outpipe[1] = safe_close(outpipe[1]);
719 errpipe[1] = safe_close(errpipe[1]);
720
26d79ab8 721 ASSERT_OK(sd_event_new(&e));
42867dfe 722
26d79ab8
DDM
723 ASSERT_OK(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC,
724 10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pid));
725 ASSERT_OK(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result));
726 ASSERT_OK(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT));
727 ASSERT_OK(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL));
728 ASSERT_OK(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT));
729 ASSERT_OK(sd_event_add_child(e, &sigchld_source, pid, WEXITED, on_spawn_sigchld, NULL));
42867dfe 730 /* SIGCHLD should be processed after IO is complete */
26d79ab8 731 ASSERT_OK(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1));
42867dfe 732
26d79ab8 733 ASSERT_OK(sd_event_loop(e));
42867dfe
YW
734
735 _cleanup_strv_free_ char **v = NULL;
26d79ab8 736 ASSERT_OK(strv_split_newlines_full(&v, result, 0));
42867dfe 737
42867dfe
YW
738 STRV_FOREACH(q, v) {
739 _cleanup_free_ char *word = NULL;
740 const char *p = *q;
741
742 r = extract_first_word(&p, &word, NULL, 0);
26d79ab8 743 ASSERT_OK(r);
42867dfe
YW
744 if (r == 0)
745 continue;
746
747 if (path_is_absolute(word)) {
26d79ab8 748 ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
42867dfe
YW
749 continue;
750 }
751
752 word = mfree(word);
753 r = extract_first_word(&p, &word, NULL, 0);
26d79ab8 754 ASSERT_OK(r);
42867dfe
YW
755 if (r == 0)
756 continue;
757
758 if (!streq_ptr(word, "=>"))
759 continue;
760
761 word = mfree(word);
762 r = extract_first_word(&p, &word, NULL, 0);
26d79ab8 763 ASSERT_OK(r);
42867dfe
YW
764 if (r == 0)
765 continue;
766
767 if (path_is_absolute(word)) {
26d79ab8 768 ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
42867dfe
YW
769 continue;
770 }
771 }
772
773 *ret = TAKE_PTR(libraries);
774 return 0;
775}
4dc76eb7 776#endif
42867dfe
YW
777
778static void test_exec_mount_apivfs(Manager *m) {
4dc76eb7 779#if !HAS_FEATURE_ADDRESS_SANITIZER
42867dfe
YW
780 _cleanup_free_ char *fullpath_touch = NULL, *fullpath_test = NULL, *data = NULL;
781 _cleanup_strv_free_ char **libraries = NULL, **libraries_test = NULL;
782 int r;
783
26d79ab8 784 ASSERT_NOT_NULL(user_runtime_unit_dir);
42867dfe 785
9f452259
YW
786 r = find_executable("ldd", NULL);
787 if (r < 0) {
788 log_notice_errno(r, "Skipping %s, could not find 'ldd' command: %m", __func__);
789 return;
790 }
42867dfe
YW
791 r = find_executable("touch", &fullpath_touch);
792 if (r < 0) {
793 log_notice_errno(r, "Skipping %s, could not find 'touch' command: %m", __func__);
794 return;
795 }
796 r = find_executable("test", &fullpath_test);
797 if (r < 0) {
798 log_notice_errno(r, "Skipping %s, could not find 'test' command: %m", __func__);
799 return;
800 }
801
d0c6136f
NR
802 if (MANAGER_IS_USER(m) && !have_userns_privileges())
803 return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
804
26d79ab8
DDM
805 ASSERT_OK(find_libraries(fullpath_touch, &libraries));
806 ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
807 ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
42867dfe 808
26d79ab8 809 ASSERT_NOT_NULL(strextend(&data, "[Service]\n"));
278e3adf
YW
810 ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")));
811 ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")));
812 ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")));
813 ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")));
42867dfe 814
42867dfe 815 STRV_FOREACH(p, libraries)
278e3adf 816 ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
42867dfe 817
26d79ab8 818 ASSERT_OK(write_drop_in(user_runtime_unit_dir, "exec-mount-apivfs-no.service", 10, "bind-mount", data));
42867dfe 819
26d79ab8 820 ASSERT_OK(mkdir_p("/tmp/test-exec-mount-apivfs-no/root", 0755));
42867dfe 821
6ef721cb 822 test(m, "exec-mount-apivfs-no.service", can_unshare || !MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
42867dfe
YW
823
824 (void) rm_rf("/tmp/test-exec-mount-apivfs-no/root", REMOVE_ROOT|REMOVE_PHYSICAL);
4dc76eb7 825#endif
42867dfe
YW
826}
827
ddc155b2
TM
828static void test_exec_noexecpaths(Manager *m) {
829
d0c6136f
NR
830 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
831 test(m, "exec-noexecpaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
832 else
833 return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
ddc155b2
TM
834}
835
4cac89bd
YW
836static void test_exec_temporaryfilesystem(Manager *m) {
837
fe65d692
ZJS
838 test(m, "exec-temporaryfilesystem-options.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
839 test(m, "exec-temporaryfilesystem-ro.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
840 test(m, "exec-temporaryfilesystem-rw.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
841 test(m, "exec-temporaryfilesystem-usr.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
4cac89bd
YW
842}
843
281e05b6 844static void test_exec_systemcallfilter(Manager *m) {
51e26d23 845#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
738c74d7
YW
846 int r;
847
f0e018e7
YW
848 if (!is_seccomp_available()) {
849 log_notice("Seccomp not available, skipping %s", __func__);
83f12b27 850 return;
f0e018e7
YW
851 }
852
956a9f00
YW
853 test(m, "exec-systemcallfilter-writing-handoff-timestamp.service", 0, CLD_EXITED);
854
fe65d692
ZJS
855 test(m, "exec-systemcallfilter-not-failing.service", 0, CLD_EXITED);
856 test(m, "exec-systemcallfilter-not-failing2.service", 0, CLD_EXITED);
e975a945 857 test(m, "exec-systemcallfilter-not-failing3.service", 0, CLD_EXITED);
fe65d692
ZJS
858 test(m, "exec-systemcallfilter-failing.service", SIGSYS, CLD_KILLED);
859 test(m, "exec-systemcallfilter-failing2.service", SIGSYS, CLD_KILLED);
e975a945 860 test(m, "exec-systemcallfilter-failing3.service", SIGSYS, CLD_KILLED);
738c74d7 861
f7bc0c32 862 r = find_executable("python3", NULL);
738c74d7
YW
863 if (r < 0) {
864 log_notice_errno(r, "Skipping remaining tests in %s, could not find python3 binary: %m", __func__);
865 return;
866 }
867
fe65d692
ZJS
868 test(m, "exec-systemcallfilter-with-errno-name.service", errno_from_name("EILSEQ"), CLD_EXITED);
869 test(m, "exec-systemcallfilter-with-errno-number.service", 255, CLD_EXITED);
870 test(m, "exec-systemcallfilter-with-errno-multi.service", errno_from_name("EILSEQ"), CLD_EXITED);
a62f651b 871 test(m, "exec-systemcallfilter-with-errno-in-allow-list.service", errno_from_name("EILSEQ"), CLD_EXITED);
fe65d692
ZJS
872 test(m, "exec-systemcallfilter-override-error-action.service", SIGSYS, CLD_KILLED);
873 test(m, "exec-systemcallfilter-override-error-action2.service", errno_from_name("EILSEQ"), CLD_EXITED);
e720cebf
ILG
874
875 test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
876 test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
877
878 r = find_executable("capsh", NULL);
879 if (r < 0) {
880 log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
881 return;
882 }
883
884 test(m, "exec-systemcallfilter-nonewprivileges-bounding1.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
885 test(m, "exec-systemcallfilter-nonewprivileges-bounding2.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
281e05b6
RC
886#endif
887}
888
889static void test_exec_systemcallerrornumber(Manager *m) {
51e26d23 890#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
738c74d7
YW
891 int r;
892
f0e018e7
YW
893 if (!is_seccomp_available()) {
894 log_notice("Seccomp not available, skipping %s", __func__);
7a18854f 895 return;
f0e018e7
YW
896 }
897
f7bc0c32 898 r = find_executable("python3", NULL);
738c74d7
YW
899 if (r < 0) {
900 log_notice_errno(r, "Skipping %s, could not find python3 binary: %m", __func__);
901 return;
902 }
903
fe65d692
ZJS
904 test(m, "exec-systemcallerrornumber-name.service", errno_from_name("EACCES"), CLD_EXITED);
905 test(m, "exec-systemcallerrornumber-number.service", 255, CLD_EXITED);
281e05b6
RC
906#endif
907}
908
f0e018e7 909static void test_exec_restrictnamespaces(Manager *m) {
349cc4a5 910#if HAVE_SECCOMP
f0e018e7
YW
911 if (!is_seccomp_available()) {
912 log_notice("Seccomp not available, skipping %s", __func__);
97e60383 913 return;
f0e018e7 914 }
97e60383 915
fe65d692
ZJS
916 test(m, "exec-restrictnamespaces-no.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
917 test(m, "exec-restrictnamespaces-yes.service", 1, CLD_EXITED);
918 test(m, "exec-restrictnamespaces-mnt.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
919 test(m, "exec-restrictnamespaces-mnt-deny-list.service", 1, CLD_EXITED);
920 test(m, "exec-restrictnamespaces-merge-and.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
921 test(m, "exec-restrictnamespaces-merge-or.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
922 test(m, "exec-restrictnamespaces-merge-all.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
97e60383
DH
923#endif
924}
925
f0e018e7 926static void test_exec_systemcallfilter_system(Manager *m) {
4967da2d
FS
927/* Skip this particular test case when running under ASan, as
928 * LSan intermittently segfaults when accessing memory right
929 * after the test finishes. Generally, ASan & LSan don't like
930 * the seccomp stuff.
931 */
932#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
f0e018e7
YW
933 if (!is_seccomp_available()) {
934 log_notice("Seccomp not available, skipping %s", __func__);
83f12b27 935 return;
f0e018e7 936 }
57c2efa0 937
4e032f65 938 test(m, "exec-systemcallfilter-system-user.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
69b07407 939
57c2efa0 940 if (!check_nobody_user_and_group()) {
5cd33ccc 941 log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
57c2efa0
YW
942 return;
943 }
944
69b07407 945 if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
5cd33ccc 946 log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
69b07407
YW
947 return;
948 }
949
4e032f65 950 test(m, "exec-systemcallfilter-system-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
19c0b0b9
RC
951#endif
952}
953
281e05b6 954static void test_exec_user(Manager *m) {
4e032f65 955 test(m, "exec-user.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
69b07407 956
57c2efa0 957 if (!check_nobody_user_and_group()) {
5cd33ccc 958 log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
57c2efa0
YW
959 return;
960 }
961
69b07407 962 if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
5cd33ccc 963 log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
69b07407
YW
964 return;
965 }
966
4e032f65 967 test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
281e05b6
RC
968}
969
970static void test_exec_group(Manager *m) {
4e032f65 971 test(m, "exec-group.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
69b07407 972
57c2efa0 973 if (!check_nobody_user_and_group()) {
5cd33ccc 974 log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
57c2efa0
YW
975 return;
976 }
977
69b07407 978 if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
5cd33ccc 979 log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
69b07407
YW
980 return;
981 }
982
4e032f65 983 test(m, "exec-group-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
281e05b6
RC
984}
985
f0e018e7 986static void test_exec_supplementarygroups(Manager *m) {
4e032f65
YW
987 int status = MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP;
988 test(m, "exec-supplementarygroups.service", status, CLD_EXITED);
989 test(m, "exec-supplementarygroups-single-group.service", status, CLD_EXITED);
990 test(m, "exec-supplementarygroups-single-group-user.service", status, CLD_EXITED);
991 test(m, "exec-supplementarygroups-multiple-groups-default-group-user.service", status, CLD_EXITED);
992 test(m, "exec-supplementarygroups-multiple-groups-withgid.service", status, CLD_EXITED);
993 test(m, "exec-supplementarygroups-multiple-groups-withuid.service", status, CLD_EXITED);
86b838ea
DH
994}
995
cced2b98
ZJS
996static char* private_directory_bad(Manager *m) {
997 /* This mirrors setup_exec_directory(). */
998
999 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
1000 _cleanup_free_ char *p = NULL;
1001 struct stat st;
1002
278e3adf 1003 ASSERT_NOT_NULL((p = path_join(m->prefix[dt], "private")));
cced2b98
ZJS
1004
1005 if (stat(p, &st) >= 0 &&
1006 (st.st_mode & (S_IRWXG|S_IRWXO)))
1007 return TAKE_PTR(p);
1008 }
1009
1010 return NULL;
1011}
1012
f0e018e7 1013static void test_exec_dynamicuser(Manager *m) {
52d8ba71
MY
1014 if (MANAGER_IS_USER(m)) {
1015 log_notice("Skipping %s for user manager", __func__);
1016 return;
1017 }
1018
cced2b98
ZJS
1019 _cleanup_free_ char *bad = private_directory_bad(m);
1020 if (bad) {
1021 log_warning("%s: %s has bad permissions, skipping test.", __func__, bad);
1022 return;
1023 }
b7172f34 1024
d1b74295
FS
1025 if (strstr_ptr(ci_environment(), "github-actions")) {
1026 log_notice("%s: skipping test on GH Actions because of systemd/systemd#10337", __func__);
1027 return;
1028 }
1029
52d8ba71 1030 int status = can_unshare ? 0 : EXIT_NAMESPACE;
4e032f65
YW
1031
1032 test(m, "exec-dynamicuser-fixeduser.service", status, CLD_EXITED);
9f82d685 1033 if (check_user_has_group_with_same_name("adm"))
4e032f65 1034 test(m, "exec-dynamicuser-fixeduser-adm.service", status, CLD_EXITED);
9f82d685 1035 if (check_user_has_group_with_same_name("games"))
4e032f65
YW
1036 test(m, "exec-dynamicuser-fixeduser-games.service", status, CLD_EXITED);
1037 test(m, "exec-dynamicuser-fixeduser-one-supplementarygroup.service", status, CLD_EXITED);
1038 test(m, "exec-dynamicuser-supplementarygroups.service", status, CLD_EXITED);
1039 test(m, "exec-dynamicuser-statedir.service", status, CLD_EXITED);
028f3a7f 1040
f5939651 1041 (void) rm_rf("/var/lib/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
1c587309
YW
1042 (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
1043 (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
f5939651
TM
1044 (void) rm_rf("/var/lib/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
1045 (void) rm_rf("/var/lib/private/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
1c587309
YW
1046 (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
1047 (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
f5939651 1048 (void) rm_rf("/var/lib/private/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
1c587309 1049
fe65d692 1050 test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
4e032f65 1051 test(m, "exec-dynamicuser-statedir-migrate-step2.service", status, CLD_EXITED);
fe65d692 1052 test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
1c587309 1053
028f3a7f
YW
1054 (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
1055 (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
1056 (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
1057 (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
e4c01fe6 1058
4e032f65
YW
1059 test(m, "exec-dynamicuser-runtimedirectory1.service", status, CLD_EXITED);
1060 test(m, "exec-dynamicuser-runtimedirectory2.service", status, CLD_EXITED);
1061 test(m, "exec-dynamicuser-runtimedirectory3.service", status, CLD_EXITED);
2b9ac11e
DH
1062}
1063
281e05b6 1064static void test_exec_environment(Manager *m) {
fe65d692
ZJS
1065 test(m, "exec-environment-no-substitute.service", 0, CLD_EXITED);
1066 test(m, "exec-environment.service", 0, CLD_EXITED);
1067 test(m, "exec-environment-multiple.service", 0, CLD_EXITED);
1068 test(m, "exec-environment-empty.service", 0, CLD_EXITED);
281e05b6
RC
1069}
1070
03bd70dd
RC
1071static void test_exec_environmentfile(Manager *m) {
1072 static const char e[] =
1073 "VAR1='word1 word2'\n"
1074 "VAR2=word3 \n"
1075 "# comment1\n"
1076 "\n"
1077 "; comment2\n"
1078 " ; # comment3\n"
1079 "line without an equal\n"
9b796f35 1080 "VAR3='$word 5 6'\n"
b6887d7a
JH
1081 "VAR4='new\nline'\n"
1082 "VAR5=password\\with\\backslashes";
03bd70dd
RC
1083 int r;
1084
1085 r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE);
26d79ab8 1086 ASSERT_OK(r);
03bd70dd 1087
fe65d692 1088 test(m, "exec-environmentfile.service", 0, CLD_EXITED);
03bd70dd 1089
f0e018e7 1090 (void) unlink("/tmp/test-exec_environmentfile.conf");
03bd70dd
RC
1091}
1092
4c80d201 1093static void test_exec_passenvironment(Manager *m) {
e1abca2e
FB
1094 /* test-execute runs under MANAGER_USER which, by default, forwards all
1095 * variables present in the environment, but only those that are
1096 * present _at the time it is created_!
1097 *
1098 * So these PassEnvironment checks are still expected to work, since we
1099 * are ensuring the variables are not present at manager creation (they
1100 * are unset explicitly in main) and are only set here.
1101 *
1102 * This is still a good approximation of how a test for MANAGER_SYSTEM
1103 * would work.
1104 */
26d79ab8
DDM
1105 ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
1106 ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
1107 ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
1108 ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
1109 ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
fe65d692
ZJS
1110 test(m, "exec-passenvironment.service", 0, CLD_EXITED);
1111 test(m, "exec-passenvironment-repeated.service", 0, CLD_EXITED);
1112 test(m, "exec-passenvironment-empty.service", 0, CLD_EXITED);
26d79ab8
DDM
1113 ASSERT_OK_ERRNO(unsetenv("VAR1"));
1114 ASSERT_OK_ERRNO(unsetenv("VAR2"));
1115 ASSERT_OK_ERRNO(unsetenv("VAR3"));
1116 ASSERT_OK_ERRNO(unsetenv("VAR4"));
1117 ASSERT_OK_ERRNO(unsetenv("VAR5"));
fe65d692 1118 test(m, "exec-passenvironment-absent.service", 0, CLD_EXITED);
4c80d201
FB
1119}
1120
27c5347c 1121static void test_exec_umask(Manager *m) {
d0c6136f
NR
1122 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
1123 test(m, "exec-umask-default.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
1124 test(m, "exec-umask-0177.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
1125 } else
1126 return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
27c5347c
RC
1127}
1128
cc3ddc85 1129static void test_exec_runtimedirectory(Manager *m) {
4e032f65 1130 (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
fe65d692 1131 test(m, "exec-runtimedirectory.service", 0, CLD_EXITED);
4e032f65
YW
1132 (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
1133
fe65d692 1134 test(m, "exec-runtimedirectory-mode.service", 0, CLD_EXITED);
4e032f65 1135 test(m, "exec-runtimedirectory-owner.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
57c2efa0
YW
1136
1137 if (!check_nobody_user_and_group()) {
5cd33ccc 1138 log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
69b07407
YW
1139 return;
1140 }
1141
1142 if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
5cd33ccc 1143 log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
57c2efa0
YW
1144 return;
1145 }
1146
4e032f65 1147 test(m, "exec-runtimedirectory-owner-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
ff4ca461
RC
1148}
1149
1150static void test_exec_capabilityboundingset(Manager *m) {
1151 int r;
1152
f7bc0c32 1153 r = find_executable("capsh", NULL);
ff4ca461 1154 if (r < 0) {
5cd33ccc 1155 log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
ff4ca461
RC
1156 return;
1157 }
1158
b7856f92
YW
1159 if (have_effective_cap(CAP_CHOWN) <= 0 ||
1160 have_effective_cap(CAP_FOWNER) <= 0 ||
1161 have_effective_cap(CAP_KILL) <= 0) {
1162 log_notice("Skipping %s, this process does not have enough capabilities", __func__);
1163 return;
1164 }
1165
fe65d692
ZJS
1166 test(m, "exec-capabilityboundingset-simple.service", 0, CLD_EXITED);
1167 test(m, "exec-capabilityboundingset-reset.service", 0, CLD_EXITED);
1168 test(m, "exec-capabilityboundingset-merge.service", 0, CLD_EXITED);
1169 test(m, "exec-capabilityboundingset-invert.service", 0, CLD_EXITED);
cc3ddc85
RC
1170}
1171
5008da1e 1172static void test_exec_basic(Manager *m) {
d0c6136f
NR
1173 if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
1174 test(m, "exec-basic.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
1175 else
1176 return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
5008da1e
ZJS
1177}
1178
b6dc25ee 1179static void test_exec_ambientcapabilities(Manager *m) {
70d7aea5
IP
1180 int r;
1181
1182 /* Check if the kernel has support for ambient capabilities. Run
1183 * the tests only if that's the case. Clearing all ambient
1184 * capabilities is fine, since we are expecting them to be unset
1185 * in the first place for the tests. */
1186 r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0);
f0e018e7 1187 if (r < 0 && IN_SET(errno, EINVAL, EOPNOTSUPP, ENOSYS)) {
5cd33ccc 1188 log_notice("Skipping %s, the kernel does not support ambient capabilities", __func__);
f0e018e7
YW
1189 return;
1190 }
1191
e5ba1d32 1192 if (have_effective_cap(CAP_CHOWN) <= 0 ||
b7856f92
YW
1193 have_effective_cap(CAP_NET_RAW) <= 0) {
1194 log_notice("Skipping %s, this process does not have enough capabilities", __func__);
1195 return;
1196 }
1197
fe65d692
ZJS
1198 test(m, "exec-ambientcapabilities.service", 0, CLD_EXITED);
1199 test(m, "exec-ambientcapabilities-merge.service", 0, CLD_EXITED);
69b07407 1200
f4a35f2a
LB
1201 if (have_effective_cap(CAP_SETUID) > 0)
1202 test(m, "exec-ambientcapabilities-dynuser.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
1203
57c2efa0 1204 if (!check_nobody_user_and_group()) {
5cd33ccc 1205 log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
69b07407
YW
1206 return;
1207 }
1208
1209 if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
5cd33ccc 1210 log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
57c2efa0
YW
1211 return;
1212 }
1213
fe65d692
ZJS
1214 test(m, "exec-ambientcapabilities-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
1215 test(m, "exec-ambientcapabilities-merge-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
70d7aea5
IP
1216}
1217
63447f11 1218static void test_exec_privatenetwork(Manager *m) {
6ef721cb 1219 int r;
63447f11 1220
8a87a16b
MK
1221 if (!have_net_dummy)
1222 return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
1223
d0c6136f
NR
1224 if (MANAGER_IS_USER(m) && !have_userns_privileges())
1225 return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
1226
f7bc0c32 1227 r = find_executable("ip", NULL);
63447f11 1228 if (r < 0) {
5cd33ccc 1229 log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
63447f11
RC
1230 return;
1231 }
1232
6ef721cb
LB
1233 test(m, "exec-privatenetwork-yes-privatemounts-no.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_FAILURE, CLD_EXITED);
1234 test(m, "exec-privatenetwork-yes-privatemounts-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_NAMESPACE, CLD_EXITED);
63447f11
RC
1235}
1236
600ed5c2
YW
1237static void test_exec_networknamespacepath(Manager *m) {
1238 int r;
1239
8a87a16b
MK
1240 if (!have_net_dummy)
1241 return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
1242
76808638
NR
1243 if (!have_netns)
1244 return (void)log_notice("Skipping %s, network namespace not available", __func__);
1245
d0c6136f
NR
1246 if (MANAGER_IS_USER(m) && !have_userns_privileges())
1247 return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
1248
600ed5c2
YW
1249 r = find_executable("ip", NULL);
1250 if (r < 0) {
1251 log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
1252 return;
1253 }
1254
1255 test(m, "exec-networknamespacepath-privatemounts-no.service", MANAGER_IS_SYSTEM(m) ? EXIT_SUCCESS : EXIT_FAILURE, CLD_EXITED);
6ef721cb 1256 test(m, "exec-networknamespacepath-privatemounts-yes.service", can_unshare ? EXIT_SUCCESS : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
600ed5c2
YW
1257}
1258
c388dfea 1259static void test_exec_oomscoreadjust(Manager *m) {
fe65d692 1260 test(m, "exec-oomscoreadjust-positive.service", 0, CLD_EXITED);
642d1a6d
YW
1261
1262 if (detect_container() > 0) {
1263 log_notice("Testing in container, skipping remaining tests in %s", __func__);
1264 return;
1265 }
4e032f65 1266 test(m, "exec-oomscoreadjust-negative.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
c388dfea
RC
1267}
1268
a6226758 1269static void test_exec_ioschedulingclass(Manager *m) {
fe65d692
ZJS
1270 test(m, "exec-ioschedulingclass-none.service", 0, CLD_EXITED);
1271 test(m, "exec-ioschedulingclass-idle.service", 0, CLD_EXITED);
1272 test(m, "exec-ioschedulingclass-best-effort.service", 0, CLD_EXITED);
642d1a6d
YW
1273
1274 if (detect_container() > 0) {
1275 log_notice("Testing in container, skipping remaining tests in %s", __func__);
1276 return;
1277 }
4e032f65 1278 test(m, "exec-ioschedulingclass-realtime.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_IOPRIO, CLD_EXITED);
a6226758
RC
1279}
1280
f0e018e7 1281static void test_exec_unsetenvironment(Manager *m) {
fe65d692 1282 test(m, "exec-unsetenvironment.service", 0, CLD_EXITED);
42cc99d5
LP
1283}
1284
9672b583 1285static void test_exec_specifier(Manager *m) {
adeff822 1286 test(m, "exec-specifier.service", 0, CLD_EXITED);
4e032f65
YW
1287 if (MANAGER_IS_SYSTEM(m))
1288 test(m, "exec-specifier-system.service", 0, CLD_EXITED);
1289 else
1290 test(m, "exec-specifier-user.service", 0, CLD_EXITED);
adeff822 1291 test(m, "exec-specifier@foo-bar.service", 0, CLD_EXITED);
fe65d692 1292 test(m, "exec-specifier-interpolation.service", 0, CLD_EXITED);
9672b583
LP
1293}
1294
f0e018e7 1295static void test_exec_standardinput(Manager *m) {
fe65d692
ZJS
1296 test(m, "exec-standardinput-data.service", 0, CLD_EXITED);
1297 test(m, "exec-standardinput-file.service", 0, CLD_EXITED);
b3a82648
FS
1298
1299 ExecOutput saved = m->defaults.std_output;
1300 m->defaults.std_output = EXEC_OUTPUT_NULL;
fe65d692 1301 test(m, "exec-standardinput-file-cat.service", 0, CLD_EXITED);
b3a82648 1302 m->defaults.std_output = saved;
666d7877
LP
1303}
1304
566b7d23 1305static void test_exec_standardoutput(Manager *m) {
fe65d692 1306 test(m, "exec-standardoutput-file.service", 0, CLD_EXITED);
566b7d23
ZD
1307}
1308
1309static void test_exec_standardoutput_append(Manager *m) {
fe65d692 1310 test(m, "exec-standardoutput-append.service", 0, CLD_EXITED);
566b7d23
ZD
1311}
1312
8d7dab1f
LW
1313static void test_exec_standardoutput_truncate(Manager *m) {
1314 test(m, "exec-standardoutput-truncate.service", 0, CLD_EXITED);
1315}
1316
31cd5f63 1317static void test_exec_condition(Manager *m) {
fe65d692
ZJS
1318 test_service(m, "exec-condition-failed.service", SERVICE_FAILURE_EXIT_CODE);
1319 test_service(m, "exec-condition-skip.service", SERVICE_SKIP_CONDITION);
31cd5f63
AZ
1320}
1321
875afa02 1322static void test_exec_umask_namespace(Manager *m) {
bfd67106
YW
1323 /* exec-specifier-credentials-dir.service creates /run/credentials and enables implicit
1324 * InaccessiblePath= for the directory for all later services with mount namespace. */
1325 if (!is_inaccessible_available()) {
1326 log_notice("Testing without inaccessible, skipping %s", __func__);
1327 return;
1328 }
4e032f65 1329 test(m, "exec-umask-namespace.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NAMESPACE : EXIT_GROUP, CLD_EXITED);
875afa02
LP
1330}
1331
9efb9631
ZJS
1332typedef struct test_entry {
1333 test_function_t f;
1334 const char *name;
1335} test_entry;
1336
1337#define entry(x) {x, #x}
1338
4870133b 1339static void run_tests(RuntimeScope scope, char **patterns) {
4e032f65
YW
1340 _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL;
1341 _cleanup_free_ char *unit_paths = NULL;
c70cac54 1342 _cleanup_(manager_freep) Manager *m = NULL;
791a84ad 1343 usec_t start, finish;
19c0b0b9
RC
1344 int r;
1345
4e032f65 1346 static const test_entry tests[] = {
9efb9631
ZJS
1347 entry(test_exec_basic),
1348 entry(test_exec_ambientcapabilities),
1349 entry(test_exec_bindpaths),
1350 entry(test_exec_capabilityboundingset),
31cd5f63 1351 entry(test_exec_condition),
9efb9631 1352 entry(test_exec_cpuaffinity),
b7cca6cc 1353 entry(test_exec_credentials),
4e032f65 1354 entry(test_exec_dynamicuser),
9efb9631
ZJS
1355 entry(test_exec_environment),
1356 entry(test_exec_environmentfile),
4e032f65
YW
1357 entry(test_exec_execsearchpath),
1358 entry(test_exec_execsearchpath_environment),
1359 entry(test_exec_execsearchpath_environment_files),
1360 entry(test_exec_execsearchpath_passenvironment),
1361 entry(test_exec_execsearchpath_specifier),
9efb9631
ZJS
1362 entry(test_exec_group),
1363 entry(test_exec_ignoresigpipe),
1364 entry(test_exec_inaccessiblepaths),
1365 entry(test_exec_ioschedulingclass),
42867dfe 1366 entry(test_exec_mount_apivfs),
600ed5c2 1367 entry(test_exec_networknamespacepath),
ddc155b2 1368 entry(test_exec_noexecpaths),
9efb9631
ZJS
1369 entry(test_exec_oomscoreadjust),
1370 entry(test_exec_passenvironment),
1371 entry(test_exec_personality),
1372 entry(test_exec_privatedevices),
1373 entry(test_exec_privatenetwork),
1374 entry(test_exec_privatetmp),
1375 entry(test_exec_protecthome),
1376 entry(test_exec_protectkernelmodules),
1377 entry(test_exec_readonlypaths),
1378 entry(test_exec_readwritepaths),
1379 entry(test_exec_restrictnamespaces),
1380 entry(test_exec_runtimedirectory),
4e032f65 1381 entry(test_exec_specifier),
9efb9631
ZJS
1382 entry(test_exec_standardinput),
1383 entry(test_exec_standardoutput),
1384 entry(test_exec_standardoutput_append),
8d7dab1f 1385 entry(test_exec_standardoutput_truncate),
9efb9631
ZJS
1386 entry(test_exec_supplementarygroups),
1387 entry(test_exec_systemcallerrornumber),
1388 entry(test_exec_systemcallfilter),
4e032f65 1389 entry(test_exec_systemcallfilter_system),
9efb9631
ZJS
1390 entry(test_exec_temporaryfilesystem),
1391 entry(test_exec_umask),
4e032f65 1392 entry(test_exec_umask_namespace),
9efb9631
ZJS
1393 entry(test_exec_unsetenvironment),
1394 entry(test_exec_user),
1395 entry(test_exec_workingdirectory),
9efb9631 1396 {},
19c0b0b9 1397 };
176ceb2c 1398
26d79ab8
DDM
1399 ASSERT_OK_ERRNO(unsetenv("USER"));
1400 ASSERT_OK_ERRNO(unsetenv("LOGNAME"));
1401 ASSERT_OK_ERRNO(unsetenv("SHELL"));
1402 ASSERT_OK_ERRNO(unsetenv("HOME"));
1403 ASSERT_OK_ERRNO(unsetenv("TMPDIR"));
2482f88d 1404
4e032f65
YW
1405 /* Unset VARx, especially, VAR1, VAR2 and VAR3, which are used in the PassEnvironment test cases,
1406 * otherwise (and if they are present in the environment), `manager_default_environment` will copy
1407 * them into the default environment which is passed to each created job, which will make the tests
1408 * that expect those not to be present to fail. */
26d79ab8
DDM
1409 ASSERT_OK_ERRNO(unsetenv("VAR1"));
1410 ASSERT_OK_ERRNO(unsetenv("VAR2"));
1411 ASSERT_OK_ERRNO(unsetenv("VAR3"));
1412 ASSERT_OK_ERRNO(unsetenv("VAR4"));
1413 ASSERT_OK_ERRNO(unsetenv("VAR5"));
34b59770 1414
278e3adf
YW
1415 ASSERT_NOT_NULL((runtime_dir = setup_fake_runtime_dir()));
1416 ASSERT_NOT_NULL((user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")));
1417 ASSERT_NOT_NULL((unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)));
6c8ade30 1418 ASSERT_OK(setenv_unit_path(unit_paths));
281e05b6 1419
026dfd60
LP
1420 /* Write credential for test-execute-load-credential to the fake runtime dir, too */
1421 _cleanup_free_ char *j = ASSERT_PTR(path_join(runtime_dir, "credstore/test-execute.load-credential"));
1422 ASSERT_OK(write_string_file(j, "foo", WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755));
1423
4e032f65
YW
1424 r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m);
1425 if (manager_errno_skip_test(r))
1426 return (void) log_tests_skipped_errno(r, "manager_new");
26d79ab8 1427 ASSERT_OK(r);
4e032f65 1428
b3a82648 1429 m->defaults.std_output = EXEC_OUTPUT_INHERIT; /* don't rely on host journald */
26d79ab8 1430 ASSERT_OK(manager_startup(m, NULL, NULL, NULL));
4e032f65
YW
1431
1432 /* Uncomment below if you want to make debugging logs stored to journal. */
1433 //manager_override_log_target(m, LOG_TARGET_AUTO);
1434 //manager_override_log_level(m, LOG_DEBUG);
1435
791a84ad
LB
1436 /* Measure and print the time that it takes to run tests, excluding startup of the manager object,
1437 * to try and measure latency of spawning services */
b6349ffd 1438 n_ran_tests = 0;
791a84ad
LB
1439 start = now(CLOCK_MONOTONIC);
1440
4e032f65 1441 for (const test_entry *test = tests; test->f; test++)
66c2a2e4
LP
1442 if (strv_fnmatch_or_empty(patterns, test->name, FNM_NOESCAPE)) {
1443 log_info("Starting %s.", test->name);
4e032f65 1444 test->f(m);
66c2a2e4 1445 } else
4e032f65 1446 log_info("Skipping %s because it does not match any pattern.", test->name);
791a84ad
LB
1447
1448 finish = now(CLOCK_MONOTONIC);
1449
b6349ffd
LB
1450 log_info("ran %u tests with %s manager + unshare=%s in: %s",
1451 n_ran_tests,
791a84ad
LB
1452 scope == RUNTIME_SCOPE_SYSTEM ? "system" : "user",
1453 yes_no(can_unshare),
1454 FORMAT_TIMESPAN(finish - start, USEC_PER_MSEC));
4e032f65
YW
1455}
1456
1457static int prepare_ns(const char *process_name) {
1458 int r;
1459
1460 r = safe_fork(process_name,
1461 FORK_RESET_SIGNALS |
1462 FORK_CLOSE_ALL_FDS |
e9ccae31 1463 FORK_DEATHSIG_SIGTERM |
4e032f65
YW
1464 FORK_WAIT |
1465 FORK_REOPEN_LOG |
1466 FORK_LOG |
1467 FORK_NEW_MOUNTNS |
1468 FORK_MOUNTNS_SLAVE,
1469 NULL);
26d79ab8 1470 ASSERT_OK(r);
4e032f65 1471 if (r == 0) {
3ebd5986 1472 _cleanup_free_ char *unit_dir = NULL, *build_dir = NULL, *build_dir_mount = NULL;
4e032f65 1473
561a3786
DDM
1474 const char *coverage = getenv("COVERAGE_BUILD_DIR");
1475 if (!coverage)
1476 /* Make "/" read-only. */
1477 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL));
4e032f65
YW
1478
1479 /* Creating a new user namespace in the above means all MS_SHARED mounts become MS_SLAVE.
1480 * Let's put them back to MS_SHARED here, since that's what we want as defaults. (This will
1481 * not reconnect propagation, but simply create new peer groups for all our mounts). */
26d79ab8 1482 ASSERT_OK(mount_follow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_SHARED|MS_REC, NULL));
4e032f65 1483
26d79ab8
DDM
1484 ASSERT_OK(mkdir_p(PRIVATE_UNIT_DIR, 0755));
1485 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", PRIVATE_UNIT_DIR, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
3ebd5986 1486 /* Mark our test "playground" as MS_SLAVE, so we can MS_MOVE mounts underneath it. */
26d79ab8 1487 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, PRIVATE_UNIT_DIR, NULL, MS_SLAVE, NULL));
e1abca2e 1488
4e032f65 1489 /* Copy unit files to make them accessible even when unprivileged. */
26d79ab8
DDM
1490 ASSERT_OK(get_testdata_dir("test-execute/", &unit_dir));
1491 ASSERT_OK(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY));
b7172f34 1492
c109cff9 1493 /* Mount tmpfs on the following directories to make not StateDirectory= or friends disturb the host. */
ea64d550 1494 ASSERT_OK_OR(get_build_exec_dir(&build_dir), -ENOEXEC);
3ebd5986
FS
1495
1496 if (build_dir) {
1497 /* Account for a build directory being in one of the soon-to-be-tmpfs directories. If we
1498 * overmount it with an empty tmpfs, manager_new() will pin the wrong systemd-executor binary,
1499 * which can then lead to unexpected (and painful to debug) test fails. */
26d79ab8 1500 ASSERT_OK_ERRNO(access(build_dir, F_OK));
278e3adf 1501 ASSERT_NOT_NULL((build_dir_mount = path_join(PRIVATE_UNIT_DIR, "build_dir")));
26d79ab8
DDM
1502 ASSERT_OK(mkdir_p(build_dir_mount, 0755));
1503 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir, build_dir_mount, NULL, MS_BIND, NULL));
3ebd5986
FS
1504 }
1505
c109cff9 1506 FOREACH_STRING(p, "/dev/shm", "/root", "/tmp", "/var/tmp", "/var/lib")
26d79ab8 1507 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
c109cff9 1508
3ebd5986 1509 if (build_dir_mount) {
ea64d550 1510 int k;
3ebd5986 1511
ea64d550
ZJS
1512 ASSERT_OK_OR(k = RET_NERRNO(access(build_dir, F_OK)), -ENOENT);
1513
1514 if (k == -ENOENT) {
3ebd5986
FS
1515 /* The build directory got overmounted by tmpfs, so let's use the "backup" bind mount to
1516 * bring it back. */
26d79ab8
DDM
1517 ASSERT_OK(mkdir_p(build_dir, 0755));
1518 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir_mount, build_dir, NULL, MS_MOVE, NULL));
3ebd5986
FS
1519 }
1520 }
1521
4e032f65
YW
1522 /* Prepare credstore like tmpfiles.d/credstore.conf for LoadCredential= tests. */
1523 FOREACH_STRING(p, "/run/credstore", "/run/credstore.encrypted") {
c443f692
YW
1524 ASSERT_OK(mkdir_p(p, 0700));
1525 ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0700"));
4e032f65 1526 }
b7cca6cc 1527
26d79ab8 1528 ASSERT_OK(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE));
4e032f65
YW
1529 }
1530
1531 return r;
1532}
1533
1534TEST(run_tests_root) {
1535 _cleanup_strv_free_ char **filters = NULL;
1536
1537 if (!have_namespaces())
1538 return (void) log_tests_skipped("unshare() is disabled");
1539
1540 /* safe_fork() clears saved_argv in the child process. Let's copy it. */
278e3adf 1541 ASSERT_NOT_NULL((filters = strv_copy(strv_skip(saved_argv, 1))));
4e032f65
YW
1542
1543 if (prepare_ns("(test-execute-root)") == 0) {
1544 can_unshare = true;
4870133b 1545 run_tests(RUNTIME_SCOPE_SYSTEM, filters);
4e032f65
YW
1546 _exit(EXIT_SUCCESS);
1547 }
1548}
1549
1550TEST(run_tests_without_unshare) {
1551 if (!have_namespaces()) {
1552 /* unshare() is already filtered. */
1553 can_unshare = false;
4870133b 1554 run_tests(RUNTIME_SCOPE_SYSTEM, strv_skip(saved_argv, 1));
4e032f65
YW
1555 return;
1556 }
b7172f34
YW
1557
1558#if HAVE_SECCOMP
4e032f65
YW
1559 _cleanup_strv_free_ char **filters = NULL;
1560 int r;
1561
b7172f34 1562 /* The following tests are for 1beab8b0d0ff2d7d1436b52d4a0c3d56dc908962. */
4e032f65
YW
1563 if (!is_seccomp_available())
1564 return (void) log_tests_skipped("Seccomp not available, cannot run unshare() filtered tests");
1565
1566 /* safe_fork() clears saved_argv in the child process. Let's copy it. */
278e3adf 1567 ASSERT_NOT_NULL((filters = strv_copy(strv_skip(saved_argv, 1))));
b7172f34 1568
4e032f65
YW
1569 if (prepare_ns("(test-execute-without-unshare)") == 0) {
1570 _cleanup_hashmap_free_ Hashmap *s = NULL;
b7172f34 1571
4e032f65 1572 r = seccomp_syscall_resolve_name("unshare");
26d79ab8
DDM
1573 ASSERT_NE(r, __NR_SCMP_ERROR);
1574 ASSERT_OK(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1)));
1575 ASSERT_OK(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true));
b7172f34 1576
4e032f65 1577 /* Check unshare() is actually filtered. */
26d79ab8 1578 ASSERT_ERROR_ERRNO(unshare(CLONE_NEWNS), EOPNOTSUPP);
281e05b6 1579
4e032f65 1580 can_unshare = false;
4870133b 1581 run_tests(RUNTIME_SCOPE_SYSTEM, filters);
4e032f65
YW
1582 _exit(EXIT_SUCCESS);
1583 }
b7172f34 1584#else
4e032f65
YW
1585 log_tests_skipped("Built without seccomp support, cannot run unshare() filtered tests");
1586#endif
1587}
1588
1589TEST(run_tests_unprivileged) {
1590 _cleanup_strv_free_ char **filters = NULL;
1591
1592 if (!have_namespaces())
1593 return (void) log_tests_skipped("unshare() is disabled");
1594
1595 /* safe_fork() clears saved_argv in the child process. Let's copy it. */
278e3adf 1596 ASSERT_NOT_NULL((filters = strv_copy(strv_skip(saved_argv, 1))));
4e032f65
YW
1597
1598 if (prepare_ns("(test-execute-unprivileged)") == 0) {
26d79ab8 1599 ASSERT_OK(capability_bounding_set_drop(0, /* right_now = */ true));
4e032f65
YW
1600
1601 can_unshare = false;
4870133b 1602 run_tests(RUNTIME_SCOPE_USER, filters);
4e032f65
YW
1603 _exit(EXIT_SUCCESS);
1604 }
1605}
1606
1607static int intro(void) {
1608#if HAS_FEATURE_ADDRESS_SANITIZER
1609 if (strstr_ptr(ci_environment(), "travis") || strstr_ptr(ci_environment(), "github-actions"))
1610 return log_tests_skipped("Running on Travis CI/GH Actions under ASan, see https://github.com/systemd/systemd/issues/10696");
b7172f34 1611#endif
4e032f65
YW
1612 /* It is needed otherwise cgroup creation fails */
1613 if (geteuid() != 0 || have_effective_cap(CAP_SYS_ADMIN) <= 0)
1614 return log_tests_skipped("not privileged");
1615
1616 if (enter_cgroup_subroot(NULL) == -ENOMEDIUM)
1617 return log_tests_skipped("cgroupfs not available");
1618
1619 if (path_is_read_only_fs("/sys") > 0)
1620 return log_tests_skipped("/sys is mounted read-only");
1621
1622 /* Create dummy network interface for testing PrivateNetwork=yes */
8a87a16b 1623 have_net_dummy = system("ip link add dummy-test-exec type dummy") == 0;
4e032f65 1624
8a87a16b
MK
1625 if (have_net_dummy) {
1626 /* Create a network namespace and a dummy interface in it for NetworkNamespacePath= */
76808638
NR
1627 have_netns = system("ip netns add test-execute-netns") == 0;
1628 have_netns = have_netns && system("ip netns exec test-execute-netns ip link add dummy-test-ns type dummy") == 0;
8a87a16b 1629 }
600ed5c2 1630
4e032f65 1631 return EXIT_SUCCESS;
281e05b6 1632}
4e032f65
YW
1633
1634static int outro(void) {
8a87a16b
MK
1635 if (have_net_dummy) {
1636 (void) system("ip link del dummy-test-exec");
1637 (void) system("ip netns del test-execute-netns");
1638 }
1639
4e032f65
YW
1640 (void) rmdir(PRIVATE_UNIT_DIR);
1641
1642 return EXIT_SUCCESS;
1643}
1644
1645DEFINE_TEST_MAIN_FULL(LOG_DEBUG, intro, outro);