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