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