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