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