• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 19315930715

12 Nov 2025 11:39PM UTC coverage: 72.251% (-0.2%) from 72.412%
19315930715

push

github

bluca
mkosi: update debian commit reference to efdd7a637

* efdd7a6377 Install new file for upstream build
* 9ebdc6099e d/rules: enable 10-systemd-logind-root-ignore-inhibitors.rules.example on Ubuntu
* 1255cc7663 initramfs-tools: only skip chzdev rules if zdev_early=0
* 4675b281ee d/t/boot-and-services: skip apparmor test on armhf
* 214d6e37b2 d/t/boot-and-services: run transient unit to check syslog messages
* f4e196aa26 d/t/boot-and-services: tweak test_rsyslog regex
* dbd366a43e Install new files for upstream build
* bb7f8ef532 Install new files for upstream build
* efa7cee8a7 Install new file for upstream build
* 95aa1d1685 Install new file for upstream build
* b770f0f01b kernel-install: skip 55-initrd.install when an initrd generator is configured
* af8d1e3134 Update changelog for 258.1-2 release
* 2d0e73cd14 d/libnss-systemd.postinst: Ensure module is enabled for all four databases

306471 of 424176 relevant lines covered (72.25%)

1239443.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

1.35
/src/test/test-execute.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <fnmatch.h>
4
#include <stdio.h>
5
#include <stdlib.h>
6
#include <sys/mount.h>
7
#include <sys/prctl.h>
8
#include <unistd.h>
9

10
#include "sd-event.h"
11

12
#include "argv-util.h"
13
#include "build-path.h"
14
#include "capability-util.h"
15
#include "copy.h"
16
#include "cpu-set-util.h"
17
#include "dropin.h"
18
#include "errno-list.h"
19
#include "extract-word.h"
20
#include "fd-util.h"
21
#include "fileio.h"
22
#include "fs-util.h"
23
#include "manager.h"
24
#include "mkdir.h"
25
#include "mount-util.h"
26
#include "path-util.h"
27
#include "process-util.h"
28
#include "rm-rf.h"
29
#include "seccomp-util.h"
30
#include "service.h"
31
#include "signal-util.h"
32
#include "stat-util.h"
33
#include "static-destruct.h"
34
#include "strv.h"
35
#include "sysctl-util.h"
36
#include "tests.h"
37
#include "unit.h"
38
#include "user-util.h"
39
#include "virt.h"
40

41
#define PRIVATE_UNIT_DIR "/run/test-execute-unit-dir"
42

43
static char *user_runtime_unit_dir = NULL;
44
static bool can_unshare;
45
static bool have_net_dummy;
46
static bool have_netns;
47
static unsigned n_ran_tests = 0;
48

49
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
1✔
50

51
typedef void (*test_function_t)(Manager *m);
52

53
static int cld_dumped_to_killed(int code) {
×
54
        /* Depending on the system, seccomp version, … some signals might result in dumping, others in plain
55
         * killing. Let's ignore the difference here, and map both cases to CLD_KILLED */
56
        return code == CLD_DUMPED ? CLD_KILLED : code;
×
57
}
58

59
_noreturn_
60
static int time_handler(sd_event_source *s, uint64_t usec, void *userdata) {
×
61
        Unit *unit = ASSERT_PTR(userdata);
×
62
        int r;
×
63

64
        log_error("Test timeout when testing %s", unit->id);
×
65
        r = unit_kill(unit, KILL_ALL, /* subgroup= */ NULL, SIGKILL, SI_USER, /* value= */ 0, /* ret_error= */ NULL);
×
66
        if (r < 0)
×
67
                log_error_errno(r, "Failed to kill %s, ignoring: %m", unit->id);
×
68

69
        abort();
×
70
}
71

72
static void wait_for_service_finish(Manager *m, Unit *unit) {
×
73
        Service *service = SERVICE(ASSERT_PTR(unit));
×
74
        usec_t timeout = 2 * USEC_PER_MINUTE;
×
75

76
        ASSERT_NOT_NULL(m);
×
77

78
        /* Bump the timeout when running in plain QEMU, as some more involved tests might start hitting the
79
         * default 2m timeout (like exec-dynamicuser-statedir.service) */
80
        if (detect_virtualization() == VIRTUALIZATION_QEMU)
×
81
                timeout *= 2;
×
82

83
        printf("%s\n", unit->id);
×
84
        exec_context_dump(&service->exec_context, stdout, "\t");
×
85

86
        _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
×
87
        ASSERT_OK(sd_event_add_time_relative(m->event, &s, CLOCK_MONOTONIC, timeout, 0, time_handler, unit));
×
88

89
        /* Here, sd_event_loop() cannot be used, as the sd_event object will be reused in the next test case. */
90
        while (!IN_SET(service->state, SERVICE_DEAD, SERVICE_FAILED))
×
91
                ASSERT_OK(sd_event_run(m->event, 100 * USEC_PER_MSEC));
×
92
}
×
93

94
static void check_main_result(const char *file, unsigned line, const char *func,
×
95
                              Manager *m, Unit *unit, int status_expected, int code_expected) {
96
        Service *service = NULL;
×
97

98
        ASSERT_NOT_NULL(m);
×
99
        ASSERT_NOT_NULL(unit);
×
100

101
        wait_for_service_finish(m, unit);
×
102

103
        service = SERVICE(unit);
×
104
        exec_status_dump(&service->main_exec_status, stdout, "\t");
×
105

106
        if (cld_dumped_to_killed(service->main_exec_status.code) != cld_dumped_to_killed(code_expected)) {
×
107
                log_error("%s:%u:%s %s: can_unshare=%s: exit code %d, expected %d",
×
108
                          file, line, func, unit->id, yes_no(can_unshare),
109
                          service->main_exec_status.code, code_expected);
110
                abort();
×
111
        }
112

113
        if (service->main_exec_status.status != status_expected) {
×
114
                log_error("%s:%u:%s: %s: can_unshare=%s: exit status %d, expected %d",
×
115
                          file, line, func, unit->id, yes_no(can_unshare),
116
                          service->main_exec_status.status, status_expected);
117
                abort();
×
118
        }
119
}
×
120

121
static void check_service_result(const char *file, unsigned line, const char *func,
×
122
                                 Manager *m, Unit *unit, ServiceResult result_expected) {
123
        Service *service = NULL;
×
124

125
        ASSERT_NOT_NULL(m);
×
126
        ASSERT_NOT_NULL(unit);
×
127

128
        wait_for_service_finish(m, unit);
×
129

130
        service = SERVICE(unit);
×
131

132
        if (service->result != result_expected) {
×
133
                log_error("%s:%u:%s: %s: can_unshare=%s: service end result %s, expected %s",
×
134
                          file, line, func, unit->id, yes_no(can_unshare),
135
                          service_result_to_string(service->result),
136
                          service_result_to_string(result_expected));
137
                abort();
×
138
        }
139
}
×
140

141
static bool check_nobody_user_and_group(void) {
×
142
        static int cache = -1;
×
143
        struct passwd *p;
×
144
        struct group *g;
×
145

146
        if (cache >= 0)
×
147
                return !!cache;
×
148

149
        if (!synthesize_nobody())
×
150
                goto invalid;
×
151

152
        p = getpwnam(NOBODY_USER_NAME);
×
153
        if (!p ||
×
154
            !streq(p->pw_name, NOBODY_USER_NAME) ||
×
155
            p->pw_uid != UID_NOBODY ||
×
156
            p->pw_gid != GID_NOBODY)
×
157
                goto invalid;
×
158

159
        p = getpwuid(UID_NOBODY);
×
160
        if (!p ||
×
161
            !streq(p->pw_name, NOBODY_USER_NAME) ||
×
162
            p->pw_uid != UID_NOBODY ||
×
163
            p->pw_gid != GID_NOBODY)
×
164
                goto invalid;
×
165

166
        g = getgrnam(NOBODY_GROUP_NAME);
×
167
        if (!g ||
×
168
            !streq(g->gr_name, NOBODY_GROUP_NAME) ||
×
169
            g->gr_gid != GID_NOBODY)
×
170
                goto invalid;
×
171

172
        g = getgrgid(GID_NOBODY);
×
173
        if (!g ||
×
174
            !streq(g->gr_name, NOBODY_GROUP_NAME) ||
×
175
            g->gr_gid != GID_NOBODY)
×
176
                goto invalid;
×
177

178
        cache = 1;
×
179
        return true;
×
180

181
invalid:
×
182
        cache = 0;
×
183
        return false;
×
184
}
185

186
static bool check_user_has_group_with_same_name(const char *name) {
×
187
        struct passwd *p;
×
188
        struct group *g;
×
189

190
        ASSERT_NOT_NULL(name);
×
191

192
        p = getpwnam(name);
×
193
        if (!p ||
×
194
            !streq(p->pw_name, name))
×
195
                return false;
196

197
        g = getgrgid(p->pw_gid);
×
198
        if (!g ||
×
199
            !streq(g->gr_name, name))
×
200
                return false;
×
201

202
        return true;
203
}
204

205
static bool is_inaccessible_available(void) {
×
206
        FOREACH_STRING(p,
×
207
                       "/run/systemd/inaccessible/reg",
208
                       "/run/systemd/inaccessible/dir",
209
                       "/run/systemd/inaccessible/chr",
210
                       "/run/systemd/inaccessible/blk",
211
                       "/run/systemd/inaccessible/fifo",
212
                       "/run/systemd/inaccessible/sock")
213
                if (access(p, F_OK) < 0)
×
214
                        return false;
×
215

216
        return true;
×
217
}
218

219
static void start_parent_slices(Unit *unit) {
×
220
        Unit *slice;
×
221

222
        slice = UNIT_GET_SLICE(unit);
×
223
        if (slice) {
×
224
                start_parent_slices(slice);
×
225
                ASSERT_OK_OR(unit_start(slice, NULL), -EALREADY);
×
226
        }
227
}
×
228

229
static bool apparmor_restrict_unprivileged_userns(void) {
×
230
        _cleanup_free_ char *v = NULL;
×
231
        int r;
×
232

233
        /* If kernel.apparmor_restrict_unprivileged_userns=1, then we cannot
234
         * use unprivileged user namespaces. */
235
        r = sysctl_read("kernel/apparmor_restrict_unprivileged_userns", &v);
×
236
        if (r < 0) {
×
237
                if (r != -ENOENT)
×
238
                        log_debug_errno(r, "Failed to read kernel.apparmor_restrict_unprivileged_userns sysctl, ignoring: %m");
×
239

240
                return false;
×
241
        }
242

243
        return streq(v, "1");
×
244
}
245

246
static bool have_userns_privileges(void) {
×
247
        pid_t pid;
×
248
        int r;
×
249

250
        if (apparmor_restrict_unprivileged_userns())
×
251
                return false;
×
252

253
        r = safe_fork("(sd-test-check-userns)",
×
254
                      FORK_RESET_SIGNALS |
255
                      FORK_CLOSE_ALL_FDS |
256
                      FORK_DEATHSIG_SIGKILL,
257
                      &pid);
258
        ASSERT_OK(r);
×
259
        if (r == 0) {
×
260
                /* Keep CAP_SYS_ADMIN if we have it to ensure we give an
261
                 * accurate result to the caller. Some kernels have a
262
                 * kernel.unprivileged_userns_clone sysctl which can be
263
                 * configured to make CLONE_NEWUSER require CAP_SYS_ADMIN.
264
                 * Additionally, AppArmor may restrict unprivileged user
265
                 * namespace creation. */
266
                r = capability_bounding_set_drop(UINT64_C(1) << CAP_SYS_ADMIN, /* right_now = */ true);
×
267
                if (r < 0) {
×
268
                        log_debug_errno(r, "Failed to drop capabilities: %m");
×
269
                        _exit(2);
×
270
                }
271

272
                r = RET_NERRNO(unshare(CLONE_NEWUSER));
×
273
                if (r < 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
×
274
                        log_debug_errno(r, "Failed to create user namespace: %m");
×
275

276
                _exit(r >= 0 ? EXIT_SUCCESS : ERRNO_IS_NEG_PRIVILEGE(r) ? EXIT_FAILURE : 2);
×
277
        }
278

279
        /* The exit code records the result of the check:
280
         *  EXIT_SUCCESS => we can use user namespaces
281
         *  EXIT_FAILURE => we can NOT use user namespaces
282
         *  2            => some other error occurred */
283
        r = wait_for_terminate_and_check("(sd-test-check-userns)", pid, 0);
×
284
        if (!IN_SET(r, EXIT_SUCCESS, EXIT_FAILURE))
×
285
                log_debug("Failed to check if user namespaces can be used, assuming not.");
×
286

287
        return r == EXIT_SUCCESS;
×
288
}
289

290
static void _test(const char *file, unsigned line, const char *func,
×
291
                  Manager *m, const char *unit_name, int status_expected, int code_expected) {
292
        Unit *unit;
×
293

294
        ASSERT_NOT_NULL(unit_name);
×
295

296
        ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit));
×
297
        /* We need to start the slices as well otherwise the slice cgroups might be pruned
298
         * in on_cgroup_empty_event. */
299
        start_parent_slices(unit);
×
300
        ASSERT_OK(unit_start(unit, NULL));
×
301
        check_main_result(file, line, func, m, unit, status_expected, code_expected);
×
302

303
        ++n_ran_tests;
×
304
}
×
305
#define test(m, unit_name, status_expected, code_expected) \
306
        _test(PROJECT_FILE, __LINE__, __func__, m, unit_name, status_expected, code_expected)
307

308
static void _test_service(const char *file, unsigned line, const char *func,
×
309
                          Manager *m, const char *unit_name, ServiceResult result_expected) {
310
        Unit *unit;
×
311

312
        ASSERT_NOT_NULL(unit_name);
×
313

314
        ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit));
×
315
        ASSERT_OK(unit_start(unit, NULL));
×
316
        check_service_result(file, line, func, m, unit, result_expected);
×
317
}
×
318
#define test_service(m, unit_name, result_expected) \
319
        _test_service(PROJECT_FILE, __LINE__, __func__, m, unit_name, result_expected)
320

321
static void test_exec_bindpaths(Manager *m) {
×
322
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths", 0755));
×
323
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths", 0755));
×
324

325
        test(m, "exec-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
326

327
        (void) rm_rf("/tmp/test-exec-bindpaths", REMOVE_ROOT|REMOVE_PHYSICAL);
×
328
        (void) rm_rf("/tmp/test-exec-bindreadonlypaths", REMOVE_ROOT|REMOVE_PHYSICAL);
×
329
}
×
330

331
static void test_exec_cpuaffinity(Manager *m) {
×
332
        _cleanup_(cpu_set_done) CPUSet c = {};
×
333

334
        ASSERT_OK(cpu_set_realloc(&c, 8192)); /* just allocate the maximum possible size */
×
335
        ASSERT_OK_ERRNO(sched_getaffinity(0, c.allocated, c.set));
×
336

337
        if (!CPU_ISSET_S(0, c.allocated, c.set)) {
×
338
                log_notice("Cannot use CPU 0, skipping %s", __func__);
×
339
                return;
×
340
        }
341

342
        test(m, "exec-cpuaffinity1.service", 0, CLD_EXITED);
×
343
        test(m, "exec-cpuaffinity2.service", 0, CLD_EXITED);
×
344

345
        if (!CPU_ISSET_S(1, c.allocated, c.set) ||
×
346
            !CPU_ISSET_S(2, c.allocated, c.set)) {
×
347
                log_notice("Cannot use CPU 1 or 2, skipping remaining tests in %s", __func__);
×
348
                return;
×
349
        }
350

351
        test(m, "exec-cpuaffinity3.service", 0, CLD_EXITED);
×
352
}
353

354
static void test_exec_credentials(Manager *m) {
×
355
        test(m, "exec-set-credential.service", 0, CLD_EXITED);
×
356
        test(m, "exec-load-credential.service", 0, CLD_EXITED);
×
357
        test(m, "exec-credentials-dir-specifier.service", 0, CLD_EXITED);
×
358
}
×
359

360
static void test_exec_workingdirectory(Manager *m) {
×
361
        ASSERT_OK(mkdir_p("/tmp/test-exec_workingdirectory", 0755));
×
362

363
        test(m, "exec-workingdirectory.service", 0, CLD_EXITED);
×
364
        test(m, "exec-workingdirectory-trailing-dot.service", 0, CLD_EXITED);
×
365

366
        (void) rm_rf("/tmp/test-exec_workingdirectory", REMOVE_ROOT|REMOVE_PHYSICAL);
×
367
}
×
368

369
static void test_exec_execsearchpath(Manager *m) {
×
370
        ASSERT_OK(mkdir_p("/tmp/test-exec_execsearchpath", 0755));
×
371

372
        ASSERT_OK(copy_file("/bin/ls", "/tmp/test-exec_execsearchpath/ls_temp", 0,  0777, COPY_REPLACE));
×
373

374
        test(m, "exec-execsearchpath.service", 0, CLD_EXITED);
×
375

376
        ASSERT_OK(rm_rf("/tmp/test-exec_execsearchpath", REMOVE_ROOT|REMOVE_PHYSICAL));
×
377

378
        test(m, "exec-execsearchpath.service", EXIT_EXEC, CLD_EXITED);
×
379
}
×
380

381
static void test_exec_execsearchpath_specifier(Manager *m) {
×
382
        test(m, "exec-execsearchpath-unit-specifier.service", 0, CLD_EXITED);
×
383
}
×
384

385
static void test_exec_execsearchpath_environment(Manager *m) {
×
386
        test(m, "exec-execsearchpath-environment.service", 0, CLD_EXITED);
×
387
        test(m, "exec-execsearchpath-environment-path-set.service", 0, CLD_EXITED);
×
388
}
×
389

390
static void test_exec_execsearchpath_environment_files(Manager *m) {
×
391
        static const char path_not_set[] =
×
392
                "VAR1='word1 word2'\n"
393
                "VAR2=word3 \n"
394
                "# comment1\n"
395
                "\n"
396
                "; comment2\n"
397
                " ; # comment3\n"
398
                "line without an equal\n"
399
                "VAR3='$word 5 6'\n"
400
                "VAR4='new\nline'\n"
401
                "VAR5=password\\with\\backslashes";
402

403
        static const char path_set[] =
×
404
                "VAR1='word1 word2'\n"
405
                "VAR2=word3 \n"
406
                "# comment1\n"
407
                "\n"
408
                "; comment2\n"
409
                " ; # comment3\n"
410
                "line without an equal\n"
411
                "VAR3='$word 5 6'\n"
412
                "VAR4='new\nline'\n"
413
                "VAR5=password\\with\\backslashes\n"
414
                "PATH=/usr";
415

416
        int r;
×
417

418
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile.conf", path_not_set, WRITE_STRING_FILE_CREATE);
×
419
        ASSERT_OK(r);
×
420

421
        test(m, "exec-execsearchpath-environmentfile.service", 0, CLD_EXITED);
×
422

423
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
424

425
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile-set.conf", path_set, WRITE_STRING_FILE_CREATE);
×
426
        ASSERT_OK(r);
×
427

428
        test(m, "exec-execsearchpath-environmentfile-set.service", 0, CLD_EXITED);
×
429

430
        (void) unlink("/tmp/test-exec_environmentfile-set.conf");
×
431
}
×
432

433
static void test_exec_execsearchpath_passenvironment(Manager *m) {
×
434
        ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
×
435
        ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
×
436
        ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
×
437
        ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
×
438
        ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
×
439

440
        test(m, "exec-execsearchpath-passenvironment.service", 0, CLD_EXITED);
×
441

442
        ASSERT_OK_ERRNO(setenv("PATH", "/usr", 1));
×
443
        test(m, "exec-execsearchpath-passenvironment-set.service", 0, CLD_EXITED);
×
444

445
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
446
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
447
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
448
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
449
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
450
        ASSERT_OK_ERRNO(unsetenv("PATH"));
×
451
}
×
452

453
static void test_exec_personality(Manager *m) {
×
454
#if defined(__x86_64__)
455
        test(m, "exec-personality-x86-64.service", 0, CLD_EXITED);
×
456

457
#elif defined(__s390x__)
458
        test(m, "exec-personality-s390x.service", 0, CLD_EXITED);
459

460
#elif defined(__s390__)
461
        test(m, "exec-personality-s390.service", 0, CLD_EXITED);
462

463
#elif defined(__powerpc64__)
464
#  if __BYTE_ORDER == __BIG_ENDIAN
465
        test(m, "exec-personality-ppc64.service", 0, CLD_EXITED);
466
#  else
467
        test(m, "exec-personality-ppc64le.service", 0, CLD_EXITED);
468
#  endif
469

470
#elif defined(__aarch64__)
471
        test(m, "exec-personality-aarch64.service", 0, CLD_EXITED);
472

473
#elif defined(__i386__)
474
        test(m, "exec-personality-x86.service", 0, CLD_EXITED);
475
#elif defined(__loongarch_lp64)
476
        test(m, "exec-personality-loongarch64.service", 0, CLD_EXITED);
477
#else
478
        log_notice("Unknown personality, skipping %s", __func__);
479
#endif
480
}
×
481

482
static void test_exec_ignoresigpipe(Manager *m) {
×
483
        test(m, "exec-ignoresigpipe-yes.service", 0, CLD_EXITED);
×
484
        test(m, "exec-ignoresigpipe-no.service", SIGPIPE, CLD_KILLED);
×
485
}
×
486

487
static void test_exec_privatetmp(Manager *m) {
×
488
        ASSERT_OK(touch("/tmp/test-exec_privatetmp"));
×
489

490
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
491
                test(m, "exec-privatetmp-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
492
                test(m, "exec-privatetmp-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
493

494
                (void) unlink("/tmp/test-exec_privatetmp_disconnected");
×
495
                test(m, "exec-privatetmp-disconnected-nodefaultdeps-nor-sandboxing.service", 0, CLD_EXITED);
×
496
                ASSERT_OK_ERRNO(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
×
497

498
                FOREACH_STRING(s,
×
499
                               "exec-privatetmp-disconnected.service",
500
                               "exec-privatetmp-disconnected-defaultdependencies-no.service",
501
                               "exec-privatetmp-disconnected-requires-mounts-for-var.service",
502
                               "exec-privatetmp-disconnected-wants-mounts-for-var.service",
503
                               "exec-privatetmp-disconnected-after-and-requires-for-var.service",
504
                               "exec-privatetmp-disconnected-after-and-wants-for-var.service") {
505
                        (void) unlink("/tmp/test-exec_privatetmp_disconnected");
×
506
                        (void) unlink("/var/tmp/test-exec_privatetmp_disconnected");
×
507
                        test(m, s, can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
508
                        ASSERT_FAIL(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
×
509
                        ASSERT_FAIL(access("/var/tmp/test-exec_privatetmp_disconnected", F_OK));
×
510
                }
511
        }
512

513
        test(m, "exec-privatetmp-no.service", 0, CLD_EXITED);
×
514

515
        (void) unlink("/tmp/test-exec_privatetmp");
×
516
}
×
517

518
static void test_exec_privatedevices(Manager *m) {
×
519
        int r;
×
520

521
        if (detect_container() > 0) {
×
522
                log_notice("Testing in container, skipping %s", __func__);
×
523
                return;
×
524
        }
525
        if (!is_inaccessible_available()) {
×
526
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
527
                return;
×
528
        }
529

530
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
531
                test(m, "exec-privatedevices-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
532
                if (access("/dev/kmsg", F_OK) >= 0)
×
533
                        test(m, "exec-privatedevices-bind.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
534
                test(m, "exec-privatedevices-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
535
                test(m, "exec-privatedevices-yes-with-group.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
536
        }
537

538
        test(m, "exec-privatedevices-no.service", 0, CLD_EXITED);
×
539

540
        /* We use capsh to test if the capabilities are
541
         * properly set, so be sure that it exists */
542
        r = find_executable("capsh", NULL);
×
543
        if (r < 0) {
×
544
                log_notice_errno(r, "Could not find capsh binary, skipping remaining tests in %s: %m", __func__);
×
545
                return;
×
546
        }
547

548
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
549
                test(m, "exec-privatedevices-yes-capability-mknod.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
550
                test(m, "exec-privatedevices-yes-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
551
        }
552

553
        test(m, "exec-privatedevices-no-capability-mknod.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
554
        test(m, "exec-privatedevices-no-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
555
}
556

557
static void test_exec_protecthome(Manager *m) {
×
558
        if (!can_unshare) {
×
559
                log_notice("Cannot reliably unshare, skipping %s", __func__);
×
560
                return;
×
561
        }
562

563
        test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
×
564
}
565

566
static void test_exec_protectkernelmodules(Manager *m) {
×
567
        int r;
×
568

569
        if (detect_container() > 0) {
×
570
                log_notice("Testing in container, skipping %s", __func__);
×
571
                return;
×
572
        }
573
        if (!is_inaccessible_available()) {
×
574
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
575
                return;
×
576
        }
577

578
        r = find_executable("capsh", NULL);
×
579
        if (r < 0) {
×
580
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
581
                return;
×
582
        }
583

584
        test(m, "exec-protectkernelmodules-no-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
585

586
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
587
                test(m, "exec-protectkernelmodules-yes-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
588
                test(m, "exec-protectkernelmodules-yes-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
589
        }
590
}
591

592
static void test_exec_readonlypaths(Manager *m) {
×
593

594
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
595
                test(m, "exec-readonlypaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
596

597
        if (path_is_read_only_fs("/var") > 0) {
×
598
                log_notice("Directory /var is readonly, skipping remaining tests in %s", __func__);
×
599
                return;
×
600
        }
601

602
        test(m, "exec-readonlypaths.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
603
        test(m, "exec-readonlypaths-with-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
604
        test(m, "exec-readonlypaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
605
}
606

607
static void test_exec_readwritepaths(Manager *m) {
×
608

609
        if (path_is_read_only_fs("/") > 0) {
×
610
                log_notice("Root directory is readonly, skipping %s", __func__);
×
611
                return;
×
612
        }
613

614
        test(m, "exec-readwritepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
615
}
616

617
static void test_exec_inaccessiblepaths(Manager *m) {
×
618

619
        if (!is_inaccessible_available()) {
×
620
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
621
                return;
×
622
        }
623

624
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
625
                test(m, "exec-inaccessiblepaths-sys.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
626

627
        if (path_is_read_only_fs("/") > 0) {
×
628
                log_notice("Root directory is readonly, skipping remaining tests in %s", __func__);
×
629
                return;
×
630
        }
631

632
        test(m, "exec-inaccessiblepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
633
}
634

635
#if !HAS_FEATURE_ADDRESS_SANITIZER
636
static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
×
637
        char **result = userdata;
×
638
        char buf[4096];
×
639
        ssize_t l;
×
640

641
        ASSERT_NOT_NULL(s);
×
642
        ASSERT_GT(fd, 0);
×
643

644
        l = read(fd, buf, sizeof(buf) - 1);
×
645
        if (l < 0) {
×
646
                if (errno == EAGAIN)
×
647
                        goto reenable;
×
648

649
                return 0;
×
650
        }
651
        if (l == 0)
×
652
                return 0;
653

654
        buf[l] = '\0';
×
655
        if (result)
×
656
                ASSERT_NOT_NULL(strextend(result, buf));
×
657
        else
658
                log_error("ldd: %s", buf);
×
659

660
reenable:
×
661
        /* Re-enable the event source if we did not encounter EOF */
662
        ASSERT_OK(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT));
×
663
        return 0;
664
}
665

666
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
×
667
        pid_t *pid = userdata;
×
668

669
        ASSERT_NOT_NULL(pid);
×
670

671
        (void) kill(*pid, SIGKILL);
×
672

673
        return 1;
×
674
}
675

676
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
×
677
        int ret = -EIO;
×
678

679
        ASSERT_NOT_NULL(si);
×
680

681
        if (si->si_code == CLD_EXITED)
×
682
                ret = si->si_status;
×
683

684
        sd_event_exit(sd_event_source_get_event(s), ret);
×
685
        return 1;
×
686
}
687

688
static int find_libraries(const char *exec, char ***ret) {
×
689
        _cleanup_(sd_event_unrefp) sd_event *e = NULL;
×
690
        _cleanup_(sd_event_source_unrefp) sd_event_source *sigchld_source = NULL;
×
691
        _cleanup_(sd_event_source_unrefp) sd_event_source *stdout_source = NULL;
×
692
        _cleanup_(sd_event_source_unrefp) sd_event_source *stderr_source = NULL;
×
693
        _cleanup_close_pair_ int outpipe[2] = EBADF_PAIR, errpipe[2] = EBADF_PAIR;
×
694
        _cleanup_strv_free_ char **libraries = NULL;
×
695
        _cleanup_free_ char *result = NULL;
×
696
        pid_t pid;
×
697
        int r;
×
698

699
        ASSERT_NOT_NULL(exec);
×
700
        ASSERT_NOT_NULL(ret);
×
701

702
        ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD));
×
703

704
        ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
×
705
        ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
×
706

707
        r = safe_fork_full("(spawn-ldd)",
×
708
                           (int[]) { -EBADF, outpipe[1], errpipe[1] },
×
709
                           NULL, 0,
710
                           FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_LOG, &pid);
711
        ASSERT_OK(r);
×
712
        if (r == 0) {
×
713
                execlp("ldd", "ldd", exec, NULL);
×
714
                _exit(EXIT_FAILURE);
×
715
        }
716

717
        outpipe[1] = safe_close(outpipe[1]);
×
718
        errpipe[1] = safe_close(errpipe[1]);
×
719

720
        ASSERT_OK(sd_event_new(&e));
×
721

722
        ASSERT_OK(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC,
×
723
                                             10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pid));
724
        ASSERT_OK(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result));
×
725
        ASSERT_OK(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT));
×
726
        ASSERT_OK(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL));
×
727
        ASSERT_OK(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT));
×
728
        ASSERT_OK(sd_event_add_child(e, &sigchld_source, pid, WEXITED, on_spawn_sigchld, NULL));
×
729
        /* SIGCHLD should be processed after IO is complete */
730
        ASSERT_OK(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1));
×
731

732
        ASSERT_OK(sd_event_loop(e));
×
733

734
        _cleanup_strv_free_ char **v = NULL;
×
735
        ASSERT_OK(strv_split_newlines_full(&v, result, 0));
×
736

737
        STRV_FOREACH(q, v) {
×
738
                _cleanup_free_ char *word = NULL;
×
739
                const char *p = *q;
×
740

741
                r = extract_first_word(&p, &word, NULL, 0);
×
742
                ASSERT_OK(r);
×
743
                if (r == 0)
×
744
                        continue;
×
745

746
                if (path_is_absolute(word)) {
×
747
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
748
                        continue;
×
749
                }
750

751
                word = mfree(word);
×
752
                r = extract_first_word(&p, &word, NULL, 0);
×
753
                ASSERT_OK(r);
×
754
                if (r == 0)
×
755
                        continue;
×
756

757
                if (!streq_ptr(word, "=>"))
×
758
                        continue;
×
759

760
                word = mfree(word);
×
761
                r = extract_first_word(&p, &word, NULL, 0);
×
762
                ASSERT_OK(r);
×
763
                if (r == 0)
×
764
                        continue;
×
765

766
                if (path_is_absolute(word)) {
×
767
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
768
                        continue;
×
769
                }
770
        }
771

772
        *ret = TAKE_PTR(libraries);
×
773
        return 0;
×
774
}
775
#endif
776

777
static void test_exec_mount_apivfs(Manager *m) {
×
778
#if !HAS_FEATURE_ADDRESS_SANITIZER
779
        _cleanup_free_ char *fullpath_touch = NULL, *fullpath_test = NULL, *data = NULL;
×
780
        _cleanup_strv_free_ char **libraries = NULL, **libraries_test = NULL;
×
781
        int r;
×
782

783
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
784

785
        r = find_executable("ldd", NULL);
×
786
        if (r < 0) {
×
787
                log_notice_errno(r, "Skipping %s, could not find 'ldd' command: %m", __func__);
×
788
                return;
×
789
        }
790
        r = find_executable("touch", &fullpath_touch);
×
791
        if (r < 0) {
×
792
                log_notice_errno(r, "Skipping %s, could not find 'touch' command: %m", __func__);
×
793
                return;
×
794
        }
795
        r = find_executable("test", &fullpath_test);
×
796
        if (r < 0) {
×
797
                log_notice_errno(r, "Skipping %s, could not find 'test' command: %m", __func__);
×
798
                return;
×
799
        }
800

801
        if (MANAGER_IS_USER(m) && !have_userns_privileges())
×
802
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
803

804
        ASSERT_OK(find_libraries(fullpath_touch, &libraries));
×
805
        ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
×
806
        ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
×
807

808
        ASSERT_NOT_NULL(strextend(&data, "[Service]\n"));
×
809
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")));
×
810
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")));
×
811
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")));
×
812
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")));
×
813

814
        STRV_FOREACH(p, libraries)
×
815
                ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
×
816

817
        ASSERT_OK(write_drop_in(user_runtime_unit_dir, "exec-mount-apivfs-no.service", 10, "bind-mount", data));
×
818

819
        ASSERT_OK(mkdir_p("/tmp/test-exec-mount-apivfs-no/root", 0755));
×
820

821
        test(m, "exec-mount-apivfs-no.service", can_unshare || !MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
822

823
        (void) rm_rf("/tmp/test-exec-mount-apivfs-no/root", REMOVE_ROOT|REMOVE_PHYSICAL);
×
824
#endif
825
}
826

827
static void test_exec_noexecpaths(Manager *m) {
×
828

829
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
830
                test(m, "exec-noexecpaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
831
        else
832
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
833
}
834

835
static void test_exec_temporaryfilesystem(Manager *m) {
×
836

837
        test(m, "exec-temporaryfilesystem-options.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
838
        test(m, "exec-temporaryfilesystem-ro.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
839
        test(m, "exec-temporaryfilesystem-rw.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
840
        test(m, "exec-temporaryfilesystem-usr.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
841
}
×
842

843
static void test_exec_systemcallfilter(Manager *m) {
×
844
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
845
        int r;
×
846

847
        if (!is_seccomp_available()) {
×
848
                log_notice("Seccomp not available, skipping %s", __func__);
×
849
                return;
×
850
        }
851

852
        test(m, "exec-systemcallfilter-writing-handoff-timestamp.service", 0, CLD_EXITED);
×
853

854
        test(m, "exec-systemcallfilter-not-failing.service", 0, CLD_EXITED);
×
855
        test(m, "exec-systemcallfilter-not-failing2.service", 0, CLD_EXITED);
×
856
        test(m, "exec-systemcallfilter-not-failing3.service", 0, CLD_EXITED);
×
857
        test(m, "exec-systemcallfilter-failing.service", SIGSYS, CLD_KILLED);
×
858
        test(m, "exec-systemcallfilter-failing2.service", SIGSYS, CLD_KILLED);
×
859
        test(m, "exec-systemcallfilter-failing3.service", SIGSYS, CLD_KILLED);
×
860

861
        r = find_executable("python3", NULL);
×
862
        if (r < 0) {
×
863
                log_notice_errno(r, "Skipping remaining tests in %s, could not find python3 binary: %m", __func__);
×
864
                return;
×
865
        }
866

867
        test(m, "exec-systemcallfilter-with-errno-name.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
868
        test(m, "exec-systemcallfilter-with-errno-number.service", 255, CLD_EXITED);
×
869
        test(m, "exec-systemcallfilter-with-errno-multi.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
870
        test(m, "exec-systemcallfilter-with-errno-in-allow-list.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
871
        test(m, "exec-systemcallfilter-override-error-action.service", SIGSYS, CLD_KILLED);
×
872
        test(m, "exec-systemcallfilter-override-error-action2.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
873

874
        test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
875
        test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
876

877
        r = find_executable("capsh", NULL);
×
878
        if (r < 0) {
×
879
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
880
                return;
×
881
        }
882

883
        test(m, "exec-systemcallfilter-nonewprivileges-bounding1.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
884
        test(m, "exec-systemcallfilter-nonewprivileges-bounding2.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
885
#endif
886
}
887

888
static void test_exec_systemcallerrornumber(Manager *m) {
×
889
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
890
        int r;
×
891

892
        if (!is_seccomp_available()) {
×
893
                log_notice("Seccomp not available, skipping %s", __func__);
×
894
                return;
×
895
        }
896

897
        r = find_executable("python3", NULL);
×
898
        if (r < 0) {
×
899
                log_notice_errno(r, "Skipping %s, could not find python3 binary: %m", __func__);
×
900
                return;
×
901
        }
902

903
        test(m, "exec-systemcallerrornumber-name.service", errno_from_name("EACCES"), CLD_EXITED);
×
904
        test(m, "exec-systemcallerrornumber-number.service", 255, CLD_EXITED);
×
905
#endif
906
}
907

908
static void test_exec_restrictnamespaces(Manager *m) {
×
909
#if HAVE_SECCOMP
910
        if (!is_seccomp_available()) {
×
911
                log_notice("Seccomp not available, skipping %s", __func__);
×
912
                return;
×
913
        }
914

915
        test(m, "exec-restrictnamespaces-no.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
916
        test(m, "exec-restrictnamespaces-yes.service", 1, CLD_EXITED);
×
917
        test(m, "exec-restrictnamespaces-mnt.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
918
        test(m, "exec-restrictnamespaces-mnt-deny-list.service", 1, CLD_EXITED);
×
919
        test(m, "exec-restrictnamespaces-merge-and.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
920
        test(m, "exec-restrictnamespaces-merge-or.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
921
        test(m, "exec-restrictnamespaces-merge-all.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
922
#endif
923
}
924

925
static void test_exec_systemcallfilter_system(Manager *m) {
×
926
/* Skip this particular test case when running under ASan, as
927
 * LSan intermittently segfaults when accessing memory right
928
 * after the test finishes. Generally, ASan & LSan don't like
929
 * the seccomp stuff.
930
 */
931
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
932
        if (!is_seccomp_available()) {
×
933
                log_notice("Seccomp not available, skipping %s", __func__);
×
934
                return;
×
935
        }
936

937
        test(m, "exec-systemcallfilter-system-user.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
938

939
        if (!check_nobody_user_and_group()) {
×
940
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
941
                return;
×
942
        }
943

944
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
945
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
946
                return;
×
947
        }
948

949
        test(m, "exec-systemcallfilter-system-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
950
#endif
951
}
952

953
static void test_exec_user(Manager *m) {
×
954
        test(m, "exec-user.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
955

956
        if (!check_nobody_user_and_group()) {
×
957
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
958
                return;
×
959
        }
960

961
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
962
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
963
                return;
×
964
        }
965

966
        test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
967
}
968

969
static void test_exec_group(Manager *m) {
×
970
        test(m, "exec-group.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
971

972
        if (!check_nobody_user_and_group()) {
×
973
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
974
                return;
×
975
        }
976

977
        if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
×
978
                log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
×
979
                return;
×
980
        }
981

982
        test(m, "exec-group-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
983
}
984

985
static void test_exec_supplementarygroups(Manager *m) {
×
986
        int status = MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP;
×
987
        test(m, "exec-supplementarygroups.service", status, CLD_EXITED);
×
988
        test(m, "exec-supplementarygroups-single-group.service", status, CLD_EXITED);
×
989
        test(m, "exec-supplementarygroups-single-group-user.service", status, CLD_EXITED);
×
990
        test(m, "exec-supplementarygroups-multiple-groups-default-group-user.service", status, CLD_EXITED);
×
991
        test(m, "exec-supplementarygroups-multiple-groups-withgid.service", status, CLD_EXITED);
×
992
        test(m, "exec-supplementarygroups-multiple-groups-withuid.service", status, CLD_EXITED);
×
993
}
×
994

995
static char* private_directory_bad(Manager *m) {
×
996
        /* This mirrors setup_exec_directory(). */
997

998
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
×
999
                _cleanup_free_ char *p = NULL;
×
1000
                struct stat st;
×
1001

1002
                ASSERT_NOT_NULL((p = path_join(m->prefix[dt], "private")));
×
1003

1004
                if (stat(p, &st) >= 0 &&
×
1005
                    (st.st_mode & (S_IRWXG|S_IRWXO)))
×
1006
                        return TAKE_PTR(p);
×
1007
        }
1008

1009
        return NULL;
1010
}
1011

1012
static void test_exec_dynamicuser(Manager *m) {
×
1013
        if (MANAGER_IS_USER(m)) {
×
1014
                log_notice("Skipping %s for user manager", __func__);
×
1015
                return;
×
1016
        }
1017

1018
        _cleanup_free_ char *bad = private_directory_bad(m);
×
1019
        if (bad) {
×
1020
                log_warning("%s: %s has bad permissions, skipping test.", __func__, bad);
×
1021
                return;
×
1022
        }
1023

1024
        if (strstr_ptr(ci_environment(), "github-actions")) {
×
1025
                log_notice("%s: skipping test on GH Actions because of systemd/systemd#10337", __func__);
×
1026
                return;
×
1027
        }
1028

1029
        int status = can_unshare ? 0 : EXIT_NAMESPACE;
×
1030

1031
        test(m, "exec-dynamicuser-fixeduser.service", status, CLD_EXITED);
×
1032
        if (check_user_has_group_with_same_name("adm"))
×
1033
                test(m, "exec-dynamicuser-fixeduser-adm.service", status, CLD_EXITED);
×
1034
        if (check_user_has_group_with_same_name("games"))
×
1035
                test(m, "exec-dynamicuser-fixeduser-games.service", status, CLD_EXITED);
×
1036
        test(m, "exec-dynamicuser-fixeduser-one-supplementarygroup.service", status, CLD_EXITED);
×
1037
        test(m, "exec-dynamicuser-supplementarygroups.service", status, CLD_EXITED);
×
1038
        test(m, "exec-dynamicuser-statedir.service", status, CLD_EXITED);
×
1039

1040
        (void) rm_rf("/var/lib/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1041
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1042
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1043
        (void) rm_rf("/var/lib/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1044
        (void) rm_rf("/var/lib/private/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1045
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1046
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1047
        (void) rm_rf("/var/lib/private/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1048

1049
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1050
        test(m, "exec-dynamicuser-statedir-migrate-step2.service", status, CLD_EXITED);
×
1051
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1052

1053
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1054
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1055
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1056
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1057

1058
        test(m, "exec-dynamicuser-runtimedirectory1.service", status, CLD_EXITED);
×
1059
        test(m, "exec-dynamicuser-runtimedirectory2.service", status, CLD_EXITED);
×
1060
        test(m, "exec-dynamicuser-runtimedirectory3.service", status, CLD_EXITED);
×
1061
}
1062

1063
static void test_exec_environment(Manager *m) {
×
1064
        test(m, "exec-environment-no-substitute.service", 0, CLD_EXITED);
×
1065
        test(m, "exec-environment.service", 0, CLD_EXITED);
×
1066
        test(m, "exec-environment-multiple.service", 0, CLD_EXITED);
×
1067
        test(m, "exec-environment-empty.service", 0, CLD_EXITED);
×
1068
}
×
1069

1070
static void test_exec_environmentfile(Manager *m) {
×
1071
        static const char e[] =
×
1072
                "VAR1='word1 word2'\n"
1073
                "VAR2=word3 \n"
1074
                "# comment1\n"
1075
                "\n"
1076
                "; comment2\n"
1077
                " ; # comment3\n"
1078
                "line without an equal\n"
1079
                "VAR3='$word 5 6'\n"
1080
                "VAR4='new\nline'\n"
1081
                "VAR5=password\\with\\backslashes";
1082
        int r;
×
1083

1084
        r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE);
×
1085
        ASSERT_OK(r);
×
1086

1087
        test(m, "exec-environmentfile.service", 0, CLD_EXITED);
×
1088

1089
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
1090
}
×
1091

1092
static void test_exec_passenvironment(Manager *m) {
×
1093
        /* test-execute runs under MANAGER_USER which, by default, forwards all
1094
         * variables present in the environment, but only those that are
1095
         * present _at the time it is created_!
1096
         *
1097
         * So these PassEnvironment checks are still expected to work, since we
1098
         * are ensuring the variables are not present at manager creation (they
1099
         * are unset explicitly in main) and are only set here.
1100
         *
1101
         * This is still a good approximation of how a test for MANAGER_SYSTEM
1102
         * would work.
1103
         */
1104
        ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
×
1105
        ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
×
1106
        ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
×
1107
        ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
×
1108
        ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
×
1109
        test(m, "exec-passenvironment.service", 0, CLD_EXITED);
×
1110
        test(m, "exec-passenvironment-repeated.service", 0, CLD_EXITED);
×
1111
        test(m, "exec-passenvironment-empty.service", 0, CLD_EXITED);
×
1112
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
1113
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
1114
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
1115
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
1116
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
1117
        test(m, "exec-passenvironment-absent.service", 0, CLD_EXITED);
×
1118
}
×
1119

1120
static void test_exec_umask(Manager *m) {
×
1121
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
1122
                test(m, "exec-umask-default.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1123
                test(m, "exec-umask-0177.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1124
        } else
1125
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1126
}
1127

1128
static void test_exec_runtimedirectory(Manager *m) {
×
1129
        (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1130
        test(m, "exec-runtimedirectory.service", 0, CLD_EXITED);
×
1131
        (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1132

1133
        test(m, "exec-runtimedirectory-mode.service", 0, CLD_EXITED);
×
1134
        test(m, "exec-runtimedirectory-owner.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1135

1136
        if (!check_nobody_user_and_group()) {
×
1137
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
1138
                return;
×
1139
        }
1140

1141
        if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
×
1142
                log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
×
1143
                return;
×
1144
        }
1145

1146
        test(m, "exec-runtimedirectory-owner-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1147
}
1148

1149
static void test_exec_capabilityboundingset(Manager *m) {
×
1150
        int r;
×
1151

1152
        r = find_executable("capsh", NULL);
×
1153
        if (r < 0) {
×
1154
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
1155
                return;
×
1156
        }
1157

1158
        if (have_effective_cap(CAP_CHOWN) <= 0 ||
×
1159
            have_effective_cap(CAP_FOWNER) <= 0 ||
×
1160
            have_effective_cap(CAP_KILL) <= 0) {
×
1161
                log_notice("Skipping %s, this process does not have enough capabilities", __func__);
×
1162
                return;
×
1163
        }
1164

1165
        test(m, "exec-capabilityboundingset-simple.service", 0, CLD_EXITED);
×
1166
        test(m, "exec-capabilityboundingset-reset.service", 0, CLD_EXITED);
×
1167
        test(m, "exec-capabilityboundingset-merge.service", 0, CLD_EXITED);
×
1168
        test(m, "exec-capabilityboundingset-invert.service", 0, CLD_EXITED);
×
1169
}
1170

1171
static void test_exec_basic(Manager *m) {
×
1172
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
1173
                test(m, "exec-basic.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1174
        else
1175
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1176
}
1177

1178
static void test_exec_ambientcapabilities(Manager *m) {
×
1179
        int r;
×
1180

1181
        /* Check if the kernel has support for ambient capabilities. Run
1182
         * the tests only if that's the case. Clearing all ambient
1183
         * capabilities is fine, since we are expecting them to be unset
1184
         * in the first place for the tests. */
1185
        r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0);
×
1186
        if (r < 0 && IN_SET(errno, EINVAL, EOPNOTSUPP, ENOSYS)) {
×
1187
                log_notice("Skipping %s, the kernel does not support ambient capabilities", __func__);
×
1188
                return;
×
1189
        }
1190

1191
        if (have_effective_cap(CAP_CHOWN) <= 0 ||
×
1192
            have_effective_cap(CAP_NET_RAW) <= 0) {
×
1193
                log_notice("Skipping %s, this process does not have enough capabilities", __func__);
×
1194
                return;
×
1195
        }
1196

1197
        test(m, "exec-ambientcapabilities.service", 0, CLD_EXITED);
×
1198
        test(m, "exec-ambientcapabilities-merge.service", 0, CLD_EXITED);
×
1199

1200
        if (have_effective_cap(CAP_SETUID) > 0)
×
1201
                test(m, "exec-ambientcapabilities-dynuser.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1202

1203
        if (!check_nobody_user_and_group()) {
×
1204
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
1205
                return;
×
1206
        }
1207

1208
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
1209
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
1210
                return;
×
1211
        }
1212

1213
        test(m, "exec-ambientcapabilities-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1214
        test(m, "exec-ambientcapabilities-merge-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1215
}
1216

1217
static void test_exec_privatenetwork(Manager *m) {
×
1218
        int r;
×
1219

1220
        if (!have_net_dummy)
×
1221
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1222

1223
        if (MANAGER_IS_USER(m) && !have_userns_privileges())
×
1224
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1225

1226
        r = find_executable("ip", NULL);
×
1227
        if (r < 0) {
×
1228
                log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
×
1229
                return;
×
1230
        }
1231

1232
        test(m, "exec-privatenetwork-yes-privatemounts-no.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_FAILURE, CLD_EXITED);
×
1233
        test(m, "exec-privatenetwork-yes-privatemounts-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_NAMESPACE, CLD_EXITED);
×
1234
}
1235

1236
static void test_exec_networknamespacepath(Manager *m) {
×
1237
        int r;
×
1238

1239
        if (!have_net_dummy)
×
1240
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1241

1242
        if (!have_netns)
×
1243
                return (void)log_notice("Skipping %s, network namespace not available", __func__);
×
1244

1245
        if (MANAGER_IS_USER(m) && !have_userns_privileges())
×
1246
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1247

1248
        r = find_executable("ip", NULL);
×
1249
        if (r < 0) {
×
1250
                log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
×
1251
                return;
×
1252
        }
1253

1254
        test(m, "exec-networknamespacepath-privatemounts-no.service", MANAGER_IS_SYSTEM(m) ? EXIT_SUCCESS : EXIT_FAILURE, CLD_EXITED);
×
1255
        test(m, "exec-networknamespacepath-privatemounts-yes.service", can_unshare ? EXIT_SUCCESS : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
1256
}
1257

1258
static void test_exec_oomscoreadjust(Manager *m) {
×
1259
        test(m, "exec-oomscoreadjust-positive.service", 0, CLD_EXITED);
×
1260

1261
        if (detect_container() > 0) {
×
1262
                log_notice("Testing in container, skipping remaining tests in %s", __func__);
×
1263
                return;
×
1264
        }
1265
        test(m, "exec-oomscoreadjust-negative.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
1266
}
1267

1268
static void test_exec_ioschedulingclass(Manager *m) {
×
1269
        test(m, "exec-ioschedulingclass-none.service", 0, CLD_EXITED);
×
1270
        test(m, "exec-ioschedulingclass-idle.service", 0, CLD_EXITED);
×
1271
        test(m, "exec-ioschedulingclass-best-effort.service", 0, CLD_EXITED);
×
1272

1273
        if (detect_container() > 0) {
×
1274
                log_notice("Testing in container, skipping remaining tests in %s", __func__);
×
1275
                return;
×
1276
        }
1277
        test(m, "exec-ioschedulingclass-realtime.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_IOPRIO, CLD_EXITED);
×
1278
}
1279

1280
static void test_exec_unsetenvironment(Manager *m) {
×
1281
        test(m, "exec-unsetenvironment.service", 0, CLD_EXITED);
×
1282
}
×
1283

1284
static void test_exec_specifier(Manager *m) {
×
1285
        test(m, "exec-specifier.service", 0, CLD_EXITED);
×
1286
        if (MANAGER_IS_SYSTEM(m))
×
1287
                test(m, "exec-specifier-system.service", 0, CLD_EXITED);
×
1288
        else
1289
                test(m, "exec-specifier-user.service", 0, CLD_EXITED);
×
1290
        test(m, "exec-specifier@foo-bar.service", 0, CLD_EXITED);
×
1291
        test(m, "exec-specifier-interpolation.service", 0, CLD_EXITED);
×
1292
}
×
1293

1294
static void test_exec_standardinput(Manager *m) {
×
1295
        test(m, "exec-standardinput-data.service", 0, CLD_EXITED);
×
1296
        test(m, "exec-standardinput-file.service", 0, CLD_EXITED);
×
1297

1298
        ExecOutput saved = m->defaults.std_output;
×
1299
        m->defaults.std_output = EXEC_OUTPUT_NULL;
×
1300
        test(m, "exec-standardinput-file-cat.service", 0, CLD_EXITED);
×
1301
        m->defaults.std_output = saved;
×
1302
}
×
1303

1304
static void test_exec_standardoutput(Manager *m) {
×
1305
        test(m, "exec-standardoutput-file.service", 0, CLD_EXITED);
×
1306
}
×
1307

1308
static void test_exec_standardoutput_append(Manager *m) {
×
1309
        test(m, "exec-standardoutput-append.service", 0, CLD_EXITED);
×
1310
}
×
1311

1312
static void test_exec_standardoutput_truncate(Manager *m) {
×
1313
        test(m, "exec-standardoutput-truncate.service", 0, CLD_EXITED);
×
1314
}
×
1315

1316
static void test_exec_condition(Manager *m) {
×
1317
        test_service(m, "exec-condition-failed.service", SERVICE_FAILURE_EXIT_CODE);
×
1318
        test_service(m, "exec-condition-skip.service", SERVICE_SKIP_CONDITION);
×
1319
}
×
1320

1321
static void test_exec_umask_namespace(Manager *m) {
×
1322
        /* exec-specifier-credentials-dir.service creates /run/credentials and enables implicit
1323
         * InaccessiblePath= for the directory for all later services with mount namespace. */
1324
        if (!is_inaccessible_available()) {
×
1325
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
1326
                return;
×
1327
        }
1328
        test(m, "exec-umask-namespace.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NAMESPACE : EXIT_GROUP, CLD_EXITED);
×
1329
}
1330

1331
typedef struct test_entry {
1332
        test_function_t f;
1333
        const char *name;
1334
} test_entry;
1335

1336
#define entry(x) {x, #x}
1337

1338
static void run_tests(RuntimeScope scope, char **patterns) {
×
1339
        _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL;
×
1340
        _cleanup_free_ char *unit_paths = NULL;
×
1341
        _cleanup_(manager_freep) Manager *m = NULL;
×
1342
        usec_t start, finish;
×
1343
        int r;
×
1344

1345
        static const test_entry tests[] = {
×
1346
                entry(test_exec_basic),
1347
                entry(test_exec_ambientcapabilities),
1348
                entry(test_exec_bindpaths),
1349
                entry(test_exec_capabilityboundingset),
1350
                entry(test_exec_condition),
1351
                entry(test_exec_cpuaffinity),
1352
                entry(test_exec_credentials),
1353
                entry(test_exec_dynamicuser),
1354
                entry(test_exec_environment),
1355
                entry(test_exec_environmentfile),
1356
                entry(test_exec_execsearchpath),
1357
                entry(test_exec_execsearchpath_environment),
1358
                entry(test_exec_execsearchpath_environment_files),
1359
                entry(test_exec_execsearchpath_passenvironment),
1360
                entry(test_exec_execsearchpath_specifier),
1361
                entry(test_exec_group),
1362
                entry(test_exec_ignoresigpipe),
1363
                entry(test_exec_inaccessiblepaths),
1364
                entry(test_exec_ioschedulingclass),
1365
                entry(test_exec_mount_apivfs),
1366
                entry(test_exec_networknamespacepath),
1367
                entry(test_exec_noexecpaths),
1368
                entry(test_exec_oomscoreadjust),
1369
                entry(test_exec_passenvironment),
1370
                entry(test_exec_personality),
1371
                entry(test_exec_privatedevices),
1372
                entry(test_exec_privatenetwork),
1373
                entry(test_exec_privatetmp),
1374
                entry(test_exec_protecthome),
1375
                entry(test_exec_protectkernelmodules),
1376
                entry(test_exec_readonlypaths),
1377
                entry(test_exec_readwritepaths),
1378
                entry(test_exec_restrictnamespaces),
1379
                entry(test_exec_runtimedirectory),
1380
                entry(test_exec_specifier),
1381
                entry(test_exec_standardinput),
1382
                entry(test_exec_standardoutput),
1383
                entry(test_exec_standardoutput_append),
1384
                entry(test_exec_standardoutput_truncate),
1385
                entry(test_exec_supplementarygroups),
1386
                entry(test_exec_systemcallerrornumber),
1387
                entry(test_exec_systemcallfilter),
1388
                entry(test_exec_systemcallfilter_system),
1389
                entry(test_exec_temporaryfilesystem),
1390
                entry(test_exec_umask),
1391
                entry(test_exec_umask_namespace),
1392
                entry(test_exec_unsetenvironment),
1393
                entry(test_exec_user),
1394
                entry(test_exec_workingdirectory),
1395
                {},
1396
        };
1397

1398
        ASSERT_OK_ERRNO(unsetenv("USER"));
×
1399
        ASSERT_OK_ERRNO(unsetenv("LOGNAME"));
×
1400
        ASSERT_OK_ERRNO(unsetenv("SHELL"));
×
1401
        ASSERT_OK_ERRNO(unsetenv("HOME"));
×
1402
        ASSERT_OK_ERRNO(unsetenv("TMPDIR"));
×
1403

1404
        /* Unset VARx, especially, VAR1, VAR2 and VAR3, which are used in the PassEnvironment test cases,
1405
         * otherwise (and if they are present in the environment), `manager_default_environment` will copy
1406
         * them into the default environment which is passed to each created job, which will make the tests
1407
         * that expect those not to be present to fail. */
1408
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
1409
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
1410
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
1411
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
1412
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
1413

1414
        ASSERT_NOT_NULL((runtime_dir = setup_fake_runtime_dir()));
×
1415
        ASSERT_NOT_NULL((user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")));
×
1416
        ASSERT_NOT_NULL((unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)));
×
1417
        ASSERT_OK(setenv_unit_path(unit_paths));
×
1418

1419
        /* Write credential for test-execute-load-credential to the fake runtime dir, too */
1420
        _cleanup_free_ char *j = ASSERT_PTR(path_join(runtime_dir, "credstore/test-execute.load-credential"));
×
1421
        ASSERT_OK(write_string_file(j, "foo", WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755));
×
1422

1423
        r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m);
×
1424
        if (manager_errno_skip_test(r))
×
1425
                return (void) log_tests_skipped_errno(r, "manager_new");
×
1426
        ASSERT_OK(r);
×
1427

1428
        m->defaults.std_output = EXEC_OUTPUT_INHERIT; /* don't rely on host journald */
×
1429
        ASSERT_OK(manager_startup(m, NULL, NULL, NULL));
×
1430

1431
        /* Uncomment below if you want to make debugging logs stored to journal. */
1432
        //manager_override_log_target(m, LOG_TARGET_AUTO);
1433
        //manager_override_log_level(m, LOG_DEBUG);
1434

1435
        /* Measure and print the time that it takes to run tests, excluding startup of the manager object,
1436
         * to try and measure latency of spawning services */
1437
        n_ran_tests = 0;
×
1438
        start = now(CLOCK_MONOTONIC);
×
1439

1440
        for (const test_entry *test = tests; test->f; test++)
×
1441
                if (strv_fnmatch_or_empty(patterns, test->name, FNM_NOESCAPE)) {
×
1442
                        log_info("Starting %s.", test->name);
×
1443
                        test->f(m);
×
1444
                } else
1445
                        log_info("Skipping %s because it does not match any pattern.", test->name);
×
1446

1447
        finish = now(CLOCK_MONOTONIC);
×
1448

1449
        log_info("ran %u tests with %s manager + unshare=%s in: %s",
×
1450
                 n_ran_tests,
1451
                 scope == RUNTIME_SCOPE_SYSTEM ? "system" : "user",
1452
                 yes_no(can_unshare),
1453
                 FORMAT_TIMESPAN(finish - start, USEC_PER_MSEC));
1454
}
1455

1456
static int prepare_ns(const char *process_name) {
×
1457
        int r;
×
1458

1459
        r = safe_fork(process_name,
×
1460
                      FORK_RESET_SIGNALS |
1461
                      FORK_CLOSE_ALL_FDS |
1462
                      FORK_DEATHSIG_SIGTERM |
1463
                      FORK_WAIT |
1464
                      FORK_REOPEN_LOG |
1465
                      FORK_LOG |
1466
                      FORK_NEW_MOUNTNS |
1467
                      FORK_MOUNTNS_SLAVE,
1468
                      NULL);
1469
        ASSERT_OK(r);
×
1470
        if (r == 0) {
×
1471
                _cleanup_free_ char *unit_dir = NULL, *build_dir = NULL, *build_dir_mount = NULL;
×
1472

1473
                const char *coverage = getenv("COVERAGE_BUILD_DIR");
×
1474
                if (!coverage)
×
1475
                        /* Make "/" read-only. */
1476
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL));
×
1477

1478
                /* Creating a new user namespace in the above means all MS_SHARED mounts become MS_SLAVE.
1479
                 * Let's put them back to MS_SHARED here, since that's what we want as defaults. (This will
1480
                 * not reconnect propagation, but simply create new peer groups for all our mounts). */
1481
                ASSERT_OK(mount_follow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_SHARED|MS_REC, NULL));
×
1482

1483
                ASSERT_OK(mkdir_p(PRIVATE_UNIT_DIR, 0755));
×
1484
                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", PRIVATE_UNIT_DIR, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1485
                /* Mark our test "playground" as MS_SLAVE, so we can MS_MOVE mounts underneath it. */
1486
                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, PRIVATE_UNIT_DIR, NULL, MS_SLAVE, NULL));
×
1487

1488
                /* Copy unit files to make them accessible even when unprivileged. */
1489
                ASSERT_OK(get_testdata_dir("test-execute/", &unit_dir));
×
1490
                ASSERT_OK(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY));
×
1491

1492
                /* Mount tmpfs on the following directories to make not StateDirectory= or friends disturb the host. */
1493
                ASSERT_OK_OR(get_build_exec_dir(&build_dir), -ENOEXEC);
×
1494

1495
                if (build_dir) {
×
1496
                        /* Account for a build directory being in one of the soon-to-be-tmpfs directories. If we
1497
                         * overmount it with an empty tmpfs, manager_new() will pin the wrong systemd-executor binary,
1498
                         * which can then lead to unexpected (and painful to debug) test fails. */
1499
                        ASSERT_OK_ERRNO(access(build_dir, F_OK));
×
1500
                        ASSERT_NOT_NULL((build_dir_mount = path_join(PRIVATE_UNIT_DIR, "build_dir")));
×
1501
                        ASSERT_OK(mkdir_p(build_dir_mount, 0755));
×
1502
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir, build_dir_mount, NULL, MS_BIND, NULL));
×
1503
                }
1504

1505
                FOREACH_STRING(p, "/dev/shm", "/root", "/tmp", "/var/tmp", "/var/lib")
×
1506
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1507

1508
                if (build_dir_mount) {
×
1509
                        int k;
×
1510

1511
                        ASSERT_OK_OR(k = RET_NERRNO(access(build_dir, F_OK)), -ENOENT);
×
1512

1513
                        if (k == -ENOENT) {
×
1514
                                /* The build directory got overmounted by tmpfs, so let's use the "backup" bind mount to
1515
                                 * bring it back. */
1516
                                ASSERT_OK(mkdir_p(build_dir, 0755));
×
1517
                                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir_mount, build_dir, NULL, MS_MOVE, NULL));
×
1518
                        }
1519
                }
1520

1521
                /* Prepare credstore like tmpfiles.d/credstore.conf for LoadCredential= tests. */
1522
                FOREACH_STRING(p, "/run/credstore", "/run/credstore.encrypted") {
×
1523
                        ASSERT_OK(mkdir_p(p, 0700));
×
1524
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0700"));
×
1525
                }
1526

1527
                ASSERT_OK(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE));
×
1528
        }
1529

1530
        return r;
×
1531
}
1532

1533
TEST(run_tests_root) {
×
1534
        _cleanup_strv_free_ char **filters = NULL;
×
1535

1536
        if (!have_namespaces())
×
1537
                return (void) log_tests_skipped("unshare() is disabled");
×
1538

1539
        /* safe_fork() clears saved_argv in the child process. Let's copy it. */
1540
        ASSERT_NOT_NULL((filters = strv_copy(strv_skip(saved_argv, 1))));
×
1541

1542
        if (prepare_ns("(test-execute-root)") == 0) {
×
1543
                can_unshare = true;
×
1544
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1545
                _exit(EXIT_SUCCESS);
×
1546
        }
1547
}
1548

1549
TEST(run_tests_without_unshare) {
×
1550
        if (!have_namespaces()) {
×
1551
                /* unshare() is already filtered. */
1552
                can_unshare = false;
×
1553
                run_tests(RUNTIME_SCOPE_SYSTEM, strv_skip(saved_argv, 1));
×
1554
                return;
×
1555
        }
1556

1557
#if HAVE_SECCOMP
1558
        _cleanup_strv_free_ char **filters = NULL;
×
1559
        int r;
×
1560

1561
        /* The following tests are for 1beab8b0d0ff2d7d1436b52d4a0c3d56dc908962. */
1562
        if (!is_seccomp_available())
×
1563
                return (void) log_tests_skipped("Seccomp not available, cannot run unshare() filtered tests");
×
1564

1565
        /* safe_fork() clears saved_argv in the child process. Let's copy it. */
1566
        ASSERT_NOT_NULL((filters = strv_copy(strv_skip(saved_argv, 1))));
×
1567

1568
        if (prepare_ns("(test-execute-without-unshare)") == 0) {
×
1569
                _cleanup_hashmap_free_ Hashmap *s = NULL;
×
1570

1571
                r = sym_seccomp_syscall_resolve_name("unshare");
×
1572
                ASSERT_NE(r, __NR_SCMP_ERROR);
×
1573
                ASSERT_OK(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1)));
×
1574
                ASSERT_OK(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true));
×
1575

1576
                /* Check unshare() is actually filtered. */
1577
                ASSERT_ERROR_ERRNO(unshare(CLONE_NEWNS), EOPNOTSUPP);
×
1578

1579
                can_unshare = false;
×
1580
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1581
                _exit(EXIT_SUCCESS);
×
1582
        }
1583
#else
1584
        log_tests_skipped("Built without seccomp support, cannot run unshare() filtered tests");
1585
#endif
1586
}
1587

1588
TEST(run_tests_unprivileged) {
×
1589
        _cleanup_strv_free_ char **filters = NULL;
×
1590

1591
        if (!have_namespaces())
×
1592
                return (void) log_tests_skipped("unshare() is disabled");
×
1593

1594
        /* safe_fork() clears saved_argv in the child process. Let's copy it. */
1595
        ASSERT_NOT_NULL((filters = strv_copy(strv_skip(saved_argv, 1))));
×
1596

1597
        if (prepare_ns("(test-execute-unprivileged)") == 0) {
×
1598
                ASSERT_OK(capability_bounding_set_drop(0, /* right_now = */ true));
×
1599

1600
                can_unshare = false;
×
1601
                run_tests(RUNTIME_SCOPE_USER, filters);
×
1602
                _exit(EXIT_SUCCESS);
×
1603
        }
1604
}
1605

1606
static int intro(void) {
1✔
1607
#if HAS_FEATURE_ADDRESS_SANITIZER
1608
        if (strstr_ptr(ci_environment(), "travis") || strstr_ptr(ci_environment(), "github-actions"))
1609
                return log_tests_skipped("Running on Travis CI/GH Actions under ASan, see https://github.com/systemd/systemd/issues/10696");
1610
#endif
1611
        /* It is needed otherwise cgroup creation fails */
1612
        if (geteuid() != 0 || have_effective_cap(CAP_SYS_ADMIN) <= 0)
1✔
1613
                return log_tests_skipped("not privileged");
×
1614

1615
        if (running_in_chroot() > 0)
1✔
1616
                return log_tests_skipped("running in chroot");
×
1617

1618
        if (enter_cgroup_subroot(NULL) == -ENOMEDIUM)
1✔
1619
                return log_tests_skipped("cgroupfs not available");
×
1620

1621
        if (path_is_read_only_fs("/sys") > 0)
1✔
1622
                return log_tests_skipped("/sys is mounted read-only");
1✔
1623

1624
        /* Create dummy network interface for testing PrivateNetwork=yes */
1625
        have_net_dummy = system("ip link add dummy-test-exec type dummy") == 0;
×
1626

1627
        if (have_net_dummy) {
×
1628
                /* Create a network namespace and a dummy interface in it for NetworkNamespacePath= */
1629
                have_netns = system("ip netns add test-execute-netns") == 0;
×
1630
                have_netns = have_netns && system("ip netns exec test-execute-netns ip link add dummy-test-ns type dummy") == 0;
×
1631
        }
1632

1633
        return EXIT_SUCCESS;
1634
}
1635

1636
static int outro(void) {
1✔
1637
        if (have_net_dummy) {
1✔
1638
                (void) system("ip link del dummy-test-exec");
×
1639
                (void) system("ip netns del test-execute-netns");
×
1640
        }
1641

1642
        (void) rmdir(PRIVATE_UNIT_DIR);
1✔
1643

1644
        return EXIT_SUCCESS;
1✔
1645
}
1646

1647
DEFINE_TEST_MAIN_FULL(LOG_DEBUG, intro, outro);
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc