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

systemd / systemd / 20012523220

07 Dec 2025 11:33PM UTC coverage: 72.656% (+0.1%) from 72.546%
20012523220

push

github

yuwata
import: include unistd.h for pipe2

This is needed for e.g. pipe2 and unlinkat and a build failure
is reproducible when libarchive support is disabled.

309255 of 425645 relevant lines covered (72.66%)

1123501.7 hits per line

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

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

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

11
#include "sd-event.h"
12

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

43
#define PRIVATE_UNIT_DIR "/run/test-execute-unit-dir"
44

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

51
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
1✔
52

53
typedef void (*test_function_t)(Manager *m);
54

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

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

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

71
        abort();
×
72
}
73

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

78
        ASSERT_NOT_NULL(m);
×
79

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

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

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

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

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

100
        ASSERT_NOT_NULL(m);
×
101
        ASSERT_NOT_NULL(unit);
×
102

103
        wait_for_service_finish(m, unit);
×
104

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

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

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

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

127
        ASSERT_NOT_NULL(m);
×
128
        ASSERT_NOT_NULL(unit);
×
129

130
        wait_for_service_finish(m, unit);
×
131

132
        service = SERVICE(unit);
×
133

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

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

148
        if (cache >= 0)
×
149
                return !!cache;
×
150

151
        if (!synthesize_nobody())
×
152
                goto invalid;
×
153

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

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

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

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

180
        cache = 1;
×
181
        return true;
×
182

183
invalid:
×
184
        cache = 0;
×
185
        return false;
×
186
}
187

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

192
        ASSERT_NOT_NULL(name);
×
193

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

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

204
        return true;
205
}
206

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

218
        return true;
×
219
}
220

221
static void start_parent_slices(Unit *unit) {
×
222
        Unit *slice;
×
223

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

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

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

242
                return false;
×
243
        }
244

245
        return streq(v, "1");
×
246
}
247

248
static bool have_userns_privileges(void) {
×
249
        pid_t pid;
×
250
        int r;
×
251

252
        if (apparmor_restrict_unprivileged_userns())
×
253
                return false;
×
254

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

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

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

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

289
        return r == EXIT_SUCCESS;
×
290
}
291

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

296
        ASSERT_NOT_NULL(unit_name);
×
297

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

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

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

314
        ASSERT_NOT_NULL(unit_name);
×
315

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

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

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

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

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

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

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

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

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

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

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

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

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

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

371
static void test_exec_execsearchpath(Manager *m) {
×
372
        int r;
×
373

374
        ASSERT_OK(r = is_symlink("/bin/ls"));
×
375
        if (r > 0)
×
376
                return (void) log_tests_skipped("/bin/ls is a symlink, maybe coreutils is built with --enable-single-binary=symlinks");
×
377

378
        ASSERT_OK(mkdir_p("/tmp/test-exec_execsearchpath", 0755));
×
379

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

382
        test(m, "exec-execsearchpath.service", 0, CLD_EXITED);
×
383

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

386
        test(m, "exec-execsearchpath.service", EXIT_EXEC, CLD_EXITED);
×
387
}
388

389
static void test_exec_execsearchpath_specifier(Manager *m) {
×
390
        test(m, "exec-execsearchpath-unit-specifier.service", 0, CLD_EXITED);
×
391
}
×
392

393
static void test_exec_execsearchpath_environment(Manager *m) {
×
394
        test(m, "exec-execsearchpath-environment.service", 0, CLD_EXITED);
×
395
        test(m, "exec-execsearchpath-environment-path-set.service", 0, CLD_EXITED);
×
396
}
×
397

398
static void test_exec_execsearchpath_environment_files(Manager *m) {
×
399
        static const char path_not_set[] =
×
400
                "VAR1='word1 word2'\n"
401
                "VAR2=word3 \n"
402
                "# comment1\n"
403
                "\n"
404
                "; comment2\n"
405
                " ; # comment3\n"
406
                "line without an equal\n"
407
                "VAR3='$word 5 6'\n"
408
                "VAR4='new\nline'\n"
409
                "VAR5=password\\with\\backslashes";
410

411
        static const char path_set[] =
×
412
                "VAR1='word1 word2'\n"
413
                "VAR2=word3 \n"
414
                "# comment1\n"
415
                "\n"
416
                "; comment2\n"
417
                " ; # comment3\n"
418
                "line without an equal\n"
419
                "VAR3='$word 5 6'\n"
420
                "VAR4='new\nline'\n"
421
                "VAR5=password\\with\\backslashes\n"
422
                "PATH=/usr";
423

424
        int r;
×
425

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

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

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

433
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile-set.conf", path_set, WRITE_STRING_FILE_CREATE);
×
434
        ASSERT_OK(r);
×
435

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

438
        (void) unlink("/tmp/test-exec_environmentfile-set.conf");
×
439
}
×
440

441
static void test_exec_execsearchpath_passenvironment(Manager *m) {
×
442
        ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
×
443
        ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
×
444
        ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
×
445
        ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
×
446
        ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
×
447

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

450
        ASSERT_OK_ERRNO(setenv("PATH", "/usr", 1));
×
451
        test(m, "exec-execsearchpath-passenvironment-set.service", 0, CLD_EXITED);
×
452

453
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
454
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
455
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
456
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
457
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
458
        ASSERT_OK_ERRNO(unsetenv("PATH"));
×
459
}
×
460

461
static void test_exec_personality(Manager *m) {
×
462
#if defined(__x86_64__)
463
        test(m, "exec-personality-x86-64.service", 0, CLD_EXITED);
×
464

465
#elif defined(__s390x__)
466
        test(m, "exec-personality-s390x.service", 0, CLD_EXITED);
467

468
#elif defined(__s390__)
469
        test(m, "exec-personality-s390.service", 0, CLD_EXITED);
470

471
#elif defined(__powerpc64__)
472
#  if __BYTE_ORDER == __BIG_ENDIAN
473
        test(m, "exec-personality-ppc64.service", 0, CLD_EXITED);
474
#  else
475
        test(m, "exec-personality-ppc64le.service", 0, CLD_EXITED);
476
#  endif
477

478
#elif defined(__aarch64__)
479
        test(m, "exec-personality-aarch64.service", 0, CLD_EXITED);
480

481
#elif defined(__i386__)
482
        test(m, "exec-personality-x86.service", 0, CLD_EXITED);
483
#elif defined(__loongarch_lp64)
484
        test(m, "exec-personality-loongarch64.service", 0, CLD_EXITED);
485
#else
486
        log_notice("Unknown personality, skipping %s", __func__);
487
#endif
488
}
×
489

490
static void test_exec_ignoresigpipe(Manager *m) {
×
491
        test(m, "exec-ignoresigpipe-yes.service", 0, CLD_EXITED);
×
492
        test(m, "exec-ignoresigpipe-no.service", SIGPIPE, CLD_KILLED);
×
493
}
×
494

495
static void test_exec_privatetmp(Manager *m) {
×
496
        ASSERT_OK(touch("/tmp/test-exec_privatetmp"));
×
497

498
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
499
                test(m, "exec-privatetmp-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
500
                test(m, "exec-privatetmp-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
501

502
                (void) unlink("/tmp/test-exec_privatetmp_disconnected");
×
503
                test(m, "exec-privatetmp-disconnected-nodefaultdeps-nor-sandboxing.service", 0, CLD_EXITED);
×
504
                ASSERT_OK_ERRNO(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
×
505

506
                FOREACH_STRING(s,
×
507
                               "exec-privatetmp-disconnected.service",
508
                               "exec-privatetmp-disconnected-defaultdependencies-no.service",
509
                               "exec-privatetmp-disconnected-requires-mounts-for-var.service",
510
                               "exec-privatetmp-disconnected-wants-mounts-for-var.service",
511
                               "exec-privatetmp-disconnected-after-and-requires-for-var.service",
512
                               "exec-privatetmp-disconnected-after-and-wants-for-var.service") {
513
                        (void) unlink("/tmp/test-exec_privatetmp_disconnected");
×
514
                        (void) unlink("/var/tmp/test-exec_privatetmp_disconnected");
×
515
                        test(m, s, can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
516
                        ASSERT_FAIL(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
×
517
                        ASSERT_FAIL(access("/var/tmp/test-exec_privatetmp_disconnected", F_OK));
×
518
                }
519
        }
520

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

523
        (void) unlink("/tmp/test-exec_privatetmp");
×
524
}
×
525

526
static void test_exec_privatedevices(Manager *m) {
×
527
        int r;
×
528

529
        if (detect_container() > 0) {
×
530
                log_notice("Testing in container, skipping %s", __func__);
×
531
                return;
×
532
        }
533
        if (!is_inaccessible_available()) {
×
534
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
535
                return;
×
536
        }
537

538
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
539
                test(m, "exec-privatedevices-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
540
                if (access("/dev/kmsg", F_OK) >= 0)
×
541
                        test(m, "exec-privatedevices-bind.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
542
                test(m, "exec-privatedevices-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
543
                test(m, "exec-privatedevices-yes-with-group.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
544
        }
545

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

548
        /* We use capsh to test if the capabilities are
549
         * properly set, so be sure that it exists */
550
        r = find_executable("capsh", NULL);
×
551
        if (r < 0) {
×
552
                log_notice_errno(r, "Could not find capsh binary, skipping remaining tests in %s: %m", __func__);
×
553
                return;
×
554
        }
555

556
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
557
                test(m, "exec-privatedevices-yes-capability-mknod.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
558
                test(m, "exec-privatedevices-yes-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
559
        }
560

561
        test(m, "exec-privatedevices-no-capability-mknod.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
562
        test(m, "exec-privatedevices-no-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
563
}
564

565
static void test_exec_protecthome(Manager *m) {
×
566
        if (!can_unshare) {
×
567
                log_notice("Cannot reliably unshare, skipping %s", __func__);
×
568
                return;
×
569
        }
570

571
        test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
×
572
}
573

574
static void test_exec_protectkernelmodules(Manager *m) {
×
575
        int r;
×
576

577
        if (detect_container() > 0) {
×
578
                log_notice("Testing in container, skipping %s", __func__);
×
579
                return;
×
580
        }
581
        if (!is_inaccessible_available()) {
×
582
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
583
                return;
×
584
        }
585

586
        r = find_executable("capsh", NULL);
×
587
        if (r < 0) {
×
588
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
589
                return;
×
590
        }
591

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

594
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
595
                test(m, "exec-protectkernelmodules-yes-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
596
                test(m, "exec-protectkernelmodules-yes-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
597
        }
598
}
599

600
static void test_exec_readonlypaths(Manager *m) {
×
601

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

605
        if (path_is_read_only_fs("/var") > 0) {
×
606
                log_notice("Directory /var is readonly, skipping remaining tests in %s", __func__);
×
607
                return;
×
608
        }
609

610
        test(m, "exec-readonlypaths.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
611
        test(m, "exec-readonlypaths-with-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
612
        test(m, "exec-readonlypaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
613
}
614

615
static void test_exec_readwritepaths(Manager *m) {
×
616

617
        if (path_is_read_only_fs("/") > 0) {
×
618
                log_notice("Root directory is readonly, skipping %s", __func__);
×
619
                return;
×
620
        }
621

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

625
static void test_exec_inaccessiblepaths(Manager *m) {
×
626

627
        if (!is_inaccessible_available()) {
×
628
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
629
                return;
×
630
        }
631

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

635
        if (path_is_read_only_fs("/") > 0) {
×
636
                log_notice("Root directory is readonly, skipping remaining tests in %s", __func__);
×
637
                return;
×
638
        }
639

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

643
#if !HAS_FEATURE_ADDRESS_SANITIZER
644
static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
×
645
        char **result = userdata;
×
646
        char buf[4096];
×
647
        ssize_t l;
×
648

649
        ASSERT_NOT_NULL(s);
×
650
        ASSERT_GT(fd, 0);
×
651

652
        l = read(fd, buf, sizeof(buf) - 1);
×
653
        if (l < 0) {
×
654
                if (errno == EAGAIN)
×
655
                        goto reenable;
×
656

657
                return 0;
×
658
        }
659
        if (l == 0)
×
660
                return 0;
661

662
        buf[l] = '\0';
×
663
        if (result)
×
664
                ASSERT_NOT_NULL(strextend(result, buf));
×
665
        else
666
                log_error("ldd: %s", buf);
×
667

668
reenable:
×
669
        /* Re-enable the event source if we did not encounter EOF */
670
        ASSERT_OK(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT));
×
671
        return 0;
672
}
673

674
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
×
675
        pid_t *pid = userdata;
×
676

677
        ASSERT_NOT_NULL(pid);
×
678

679
        (void) kill(*pid, SIGKILL);
×
680

681
        return 1;
×
682
}
683

684
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
×
685
        int ret = -EIO;
×
686

687
        ASSERT_NOT_NULL(si);
×
688

689
        if (si->si_code == CLD_EXITED)
×
690
                ret = si->si_status;
×
691

692
        sd_event_exit(sd_event_source_get_event(s), ret);
×
693
        return 1;
×
694
}
695

696
static int find_libraries(const char *exec, char ***ret) {
×
697
        _cleanup_(sd_event_unrefp) sd_event *e = NULL;
×
698
        _cleanup_(sd_event_source_unrefp) sd_event_source *sigchld_source = NULL;
×
699
        _cleanup_(sd_event_source_unrefp) sd_event_source *stdout_source = NULL;
×
700
        _cleanup_(sd_event_source_unrefp) sd_event_source *stderr_source = NULL;
×
701
        _cleanup_close_pair_ int outpipe[2] = EBADF_PAIR, errpipe[2] = EBADF_PAIR;
×
702
        _cleanup_strv_free_ char **libraries = NULL;
×
703
        _cleanup_free_ char *result = NULL;
×
704
        pid_t pid;
×
705
        int r;
×
706

707
        ASSERT_NOT_NULL(exec);
×
708
        ASSERT_NOT_NULL(ret);
×
709

710
        ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD));
×
711

712
        ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
×
713
        ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
×
714

715
        r = safe_fork_full("(spawn-ldd)",
×
716
                           (int[]) { -EBADF, outpipe[1], errpipe[1] },
×
717
                           NULL, 0,
718
                           FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_LOG, &pid);
719
        ASSERT_OK(r);
×
720
        if (r == 0) {
×
721
                execlp("ldd", "ldd", exec, NULL);
×
722
                _exit(EXIT_FAILURE);
×
723
        }
724

725
        outpipe[1] = safe_close(outpipe[1]);
×
726
        errpipe[1] = safe_close(errpipe[1]);
×
727

728
        ASSERT_OK(sd_event_new(&e));
×
729

730
        ASSERT_OK(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC,
×
731
                                             10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pid));
732
        ASSERT_OK(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result));
×
733
        ASSERT_OK(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT));
×
734
        ASSERT_OK(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL));
×
735
        ASSERT_OK(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT));
×
736
        ASSERT_OK(sd_event_add_child(e, &sigchld_source, pid, WEXITED, on_spawn_sigchld, NULL));
×
737
        /* SIGCHLD should be processed after IO is complete */
738
        ASSERT_OK(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1));
×
739

740
        ASSERT_OK(sd_event_loop(e));
×
741

742
        _cleanup_strv_free_ char **v = NULL;
×
743
        ASSERT_OK(strv_split_newlines_full(&v, result, 0));
×
744

745
        STRV_FOREACH(q, v) {
×
746
                _cleanup_free_ char *word = NULL;
×
747
                const char *p = *q;
×
748

749
                r = extract_first_word(&p, &word, NULL, 0);
×
750
                ASSERT_OK(r);
×
751
                if (r == 0)
×
752
                        continue;
×
753

754
                if (path_is_absolute(word)) {
×
755
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
756
                        continue;
×
757
                }
758

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

765
                if (!streq_ptr(word, "=>"))
×
766
                        continue;
×
767

768
                word = mfree(word);
×
769
                r = extract_first_word(&p, &word, NULL, 0);
×
770
                ASSERT_OK(r);
×
771
                if (r == 0)
×
772
                        continue;
×
773

774
                if (path_is_absolute(word)) {
×
775
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
776
                        continue;
×
777
                }
778
        }
779

780
        *ret = TAKE_PTR(libraries);
×
781
        return 0;
×
782
}
783
#endif
784

785
static void test_exec_mount_apivfs(Manager *m) {
×
786
#if !HAS_FEATURE_ADDRESS_SANITIZER
787
        _cleanup_free_ char *fullpath_touch = NULL, *fullpath_test = NULL, *data = NULL;
×
788
        _cleanup_strv_free_ char **libraries = NULL, **libraries_test = NULL;
×
789
        int r;
×
790

791
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
792

793
        r = find_executable("ldd", NULL);
×
794
        if (r < 0) {
×
795
                log_notice_errno(r, "Skipping %s, could not find 'ldd' command: %m", __func__);
×
796
                return;
×
797
        }
798
        r = find_executable("touch", &fullpath_touch);
×
799
        if (r < 0) {
×
800
                log_notice_errno(r, "Skipping %s, could not find 'touch' command: %m", __func__);
×
801
                return;
×
802
        }
803
        r = find_executable("test", &fullpath_test);
×
804
        if (r < 0) {
×
805
                log_notice_errno(r, "Skipping %s, could not find 'test' command: %m", __func__);
×
806
                return;
×
807
        }
808

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

812
        ASSERT_OK(find_libraries(fullpath_touch, &libraries));
×
813
        ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
×
814
        ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
×
815

816
        ASSERT_NOT_NULL(strextend(&data, "[Service]\n"));
×
817
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")));
×
818
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")));
×
819
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")));
×
820
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")));
×
821

822
        STRV_FOREACH(p, libraries)
×
823
                ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
×
824

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

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

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

831
        (void) rm_rf("/tmp/test-exec-mount-apivfs-no/root", REMOVE_ROOT|REMOVE_PHYSICAL);
×
832
#endif
833
}
834

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

837
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
838
                test(m, "exec-noexecpaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
839
        else
840
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
841
}
842

843
static void test_exec_temporaryfilesystem(Manager *m) {
×
844

845
        test(m, "exec-temporaryfilesystem-options.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
846
        test(m, "exec-temporaryfilesystem-ro.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
847
        test(m, "exec-temporaryfilesystem-rw.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
848
        test(m, "exec-temporaryfilesystem-usr.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
849
}
×
850

851
static void test_exec_systemcallfilter(Manager *m) {
×
852
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
853
        int r;
×
854

855
        if (!is_seccomp_available()) {
×
856
                log_notice("Seccomp not available, skipping %s", __func__);
×
857
                return;
×
858
        }
859

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

862
        test(m, "exec-systemcallfilter-not-failing.service", 0, CLD_EXITED);
×
863
        test(m, "exec-systemcallfilter-not-failing2.service", 0, CLD_EXITED);
×
864
        test(m, "exec-systemcallfilter-not-failing3.service", 0, CLD_EXITED);
×
865
        test(m, "exec-systemcallfilter-failing.service", SIGSYS, CLD_KILLED);
×
866
        test(m, "exec-systemcallfilter-failing2.service", SIGSYS, CLD_KILLED);
×
867
        test(m, "exec-systemcallfilter-failing3.service", SIGSYS, CLD_KILLED);
×
868

869
        r = find_executable("python3", NULL);
×
870
        if (r < 0) {
×
871
                log_notice_errno(r, "Skipping remaining tests in %s, could not find python3 binary: %m", __func__);
×
872
                return;
×
873
        }
874

875
        test(m, "exec-systemcallfilter-with-errno-name.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
876
        test(m, "exec-systemcallfilter-with-errno-number.service", 255, CLD_EXITED);
×
877
        test(m, "exec-systemcallfilter-with-errno-multi.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
878
        test(m, "exec-systemcallfilter-with-errno-in-allow-list.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
879
        test(m, "exec-systemcallfilter-override-error-action.service", SIGSYS, CLD_KILLED);
×
880
        test(m, "exec-systemcallfilter-override-error-action2.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
881

882
        test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
883
        test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
884

885
        r = find_executable("capsh", NULL);
×
886
        if (r < 0) {
×
887
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
888
                return;
×
889
        }
890

891
        test(m, "exec-systemcallfilter-nonewprivileges-bounding1.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
892
        test(m, "exec-systemcallfilter-nonewprivileges-bounding2.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
893
#endif
894
}
895

896
static void test_exec_systemcallerrornumber(Manager *m) {
×
897
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
898
        int r;
×
899

900
        if (!is_seccomp_available()) {
×
901
                log_notice("Seccomp not available, skipping %s", __func__);
×
902
                return;
×
903
        }
904

905
        r = find_executable("python3", NULL);
×
906
        if (r < 0) {
×
907
                log_notice_errno(r, "Skipping %s, could not find python3 binary: %m", __func__);
×
908
                return;
×
909
        }
910

911
        test(m, "exec-systemcallerrornumber-name.service", errno_from_name("EACCES"), CLD_EXITED);
×
912
        test(m, "exec-systemcallerrornumber-number.service", 255, CLD_EXITED);
×
913
#endif
914
}
915

916
static void test_exec_restrictnamespaces(Manager *m) {
×
917
#if HAVE_SECCOMP
918
        if (!is_seccomp_available()) {
×
919
                log_notice("Seccomp not available, skipping %s", __func__);
×
920
                return;
×
921
        }
922

923
        test(m, "exec-restrictnamespaces-no.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
924
        test(m, "exec-restrictnamespaces-yes.service", 1, CLD_EXITED);
×
925
        test(m, "exec-restrictnamespaces-mnt.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
926
        test(m, "exec-restrictnamespaces-mnt-deny-list.service", 1, CLD_EXITED);
×
927
        test(m, "exec-restrictnamespaces-merge-and.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
928
        test(m, "exec-restrictnamespaces-merge-or.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
929
        test(m, "exec-restrictnamespaces-merge-all.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
930
#endif
931
}
932

933
static void test_exec_systemcallfilter_system(Manager *m) {
×
934
/* Skip this particular test case when running under ASan, as
935
 * LSan intermittently segfaults when accessing memory right
936
 * after the test finishes. Generally, ASan & LSan don't like
937
 * the seccomp stuff.
938
 */
939
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
940
        if (!is_seccomp_available()) {
×
941
                log_notice("Seccomp not available, skipping %s", __func__);
×
942
                return;
×
943
        }
944

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

947
        if (!check_nobody_user_and_group()) {
×
948
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
949
                return;
×
950
        }
951

952
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
953
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
954
                return;
×
955
        }
956

957
        test(m, "exec-systemcallfilter-system-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
958
#endif
959
}
960

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

964
        if (!check_nobody_user_and_group()) {
×
965
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
966
                return;
×
967
        }
968

969
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
970
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
971
                return;
×
972
        }
973

974
        test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
975
}
976

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

980
        if (!check_nobody_user_and_group()) {
×
981
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
982
                return;
×
983
        }
984

985
        if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
×
986
                log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
×
987
                return;
×
988
        }
989

990
        test(m, "exec-group-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
991
}
992

993
static void test_exec_supplementarygroups(Manager *m) {
×
994
        int status = MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP;
×
995
        test(m, "exec-supplementarygroups.service", status, CLD_EXITED);
×
996
        test(m, "exec-supplementarygroups-single-group.service", status, CLD_EXITED);
×
997
        test(m, "exec-supplementarygroups-single-group-user.service", status, CLD_EXITED);
×
998
        test(m, "exec-supplementarygroups-multiple-groups-default-group-user.service", status, CLD_EXITED);
×
999
        test(m, "exec-supplementarygroups-multiple-groups-withgid.service", status, CLD_EXITED);
×
1000
        test(m, "exec-supplementarygroups-multiple-groups-withuid.service", status, CLD_EXITED);
×
1001
}
×
1002

1003
static char* private_directory_bad(Manager *m) {
×
1004
        /* This mirrors setup_exec_directory(). */
1005

1006
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
×
1007
                _cleanup_free_ char *p = NULL;
×
1008
                struct stat st;
×
1009

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

1012
                if (stat(p, &st) >= 0 &&
×
1013
                    (st.st_mode & (S_IRWXG|S_IRWXO)))
×
1014
                        return TAKE_PTR(p);
×
1015
        }
1016

1017
        return NULL;
1018
}
1019

1020
static void test_exec_dynamicuser(Manager *m) {
×
1021
        if (MANAGER_IS_USER(m)) {
×
1022
                log_notice("Skipping %s for user manager", __func__);
×
1023
                return;
×
1024
        }
1025

1026
        _cleanup_free_ char *bad = private_directory_bad(m);
×
1027
        if (bad) {
×
1028
                log_warning("%s: %s has bad permissions, skipping test.", __func__, bad);
×
1029
                return;
×
1030
        }
1031

1032
        if (strstr_ptr(ci_environment(), "github-actions")) {
×
1033
                log_notice("%s: skipping test on GH Actions because of systemd/systemd#10337", __func__);
×
1034
                return;
×
1035
        }
1036

1037
        int status = can_unshare ? 0 : EXIT_NAMESPACE;
×
1038

1039
        test(m, "exec-dynamicuser-fixeduser.service", status, CLD_EXITED);
×
1040
        if (check_user_has_group_with_same_name("adm"))
×
1041
                test(m, "exec-dynamicuser-fixeduser-adm.service", status, CLD_EXITED);
×
1042
        if (check_user_has_group_with_same_name("games"))
×
1043
                test(m, "exec-dynamicuser-fixeduser-games.service", status, CLD_EXITED);
×
1044
        test(m, "exec-dynamicuser-fixeduser-one-supplementarygroup.service", status, CLD_EXITED);
×
1045
        test(m, "exec-dynamicuser-supplementarygroups.service", status, CLD_EXITED);
×
1046
        test(m, "exec-dynamicuser-statedir.service", status, CLD_EXITED);
×
1047

1048
        (void) rm_rf("/var/lib/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1049
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1050
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1051
        (void) rm_rf("/var/lib/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1052
        (void) rm_rf("/var/lib/private/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1053
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1054
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1055
        (void) rm_rf("/var/lib/private/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1056

1057
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1058
        test(m, "exec-dynamicuser-statedir-migrate-step2.service", status, CLD_EXITED);
×
1059
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1060

1061
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1062
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1063
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1064
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1065

1066
        test(m, "exec-dynamicuser-runtimedirectory1.service", status, CLD_EXITED);
×
1067
        test(m, "exec-dynamicuser-runtimedirectory2.service", status, CLD_EXITED);
×
1068
        test(m, "exec-dynamicuser-runtimedirectory3.service", status, CLD_EXITED);
×
1069
}
1070

1071
static void test_exec_environment(Manager *m) {
×
1072
        test(m, "exec-environment-no-substitute.service", 0, CLD_EXITED);
×
1073
        test(m, "exec-environment.service", 0, CLD_EXITED);
×
1074
        test(m, "exec-environment-multiple.service", 0, CLD_EXITED);
×
1075
        test(m, "exec-environment-empty.service", 0, CLD_EXITED);
×
1076
}
×
1077

1078
static void test_exec_environmentfile(Manager *m) {
×
1079
        static const char e[] =
×
1080
                "VAR1='word1 word2'\n"
1081
                "VAR2=word3 \n"
1082
                "# comment1\n"
1083
                "\n"
1084
                "; comment2\n"
1085
                " ; # comment3\n"
1086
                "line without an equal\n"
1087
                "VAR3='$word 5 6'\n"
1088
                "VAR4='new\nline'\n"
1089
                "VAR5=password\\with\\backslashes";
1090
        int r;
×
1091

1092
        r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE);
×
1093
        ASSERT_OK(r);
×
1094

1095
        test(m, "exec-environmentfile.service", 0, CLD_EXITED);
×
1096

1097
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
1098
}
×
1099

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

1128
static void test_exec_umask(Manager *m) {
×
1129
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
1130
                test(m, "exec-umask-default.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1131
                test(m, "exec-umask-0177.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1132
        } else
1133
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1134
}
1135

1136
static void test_exec_runtimedirectory(Manager *m) {
×
1137
        (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1138
        test(m, "exec-runtimedirectory.service", 0, CLD_EXITED);
×
1139
        (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1140

1141
        test(m, "exec-runtimedirectory-mode.service", 0, CLD_EXITED);
×
1142
        test(m, "exec-runtimedirectory-owner.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1143

1144
        if (!check_nobody_user_and_group()) {
×
1145
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
1146
                return;
×
1147
        }
1148

1149
        if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
×
1150
                log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
×
1151
                return;
×
1152
        }
1153

1154
        test(m, "exec-runtimedirectory-owner-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1155
}
1156

1157
static void test_exec_capabilityboundingset(Manager *m) {
×
1158
        int r;
×
1159

1160
        r = find_executable("capsh", NULL);
×
1161
        if (r < 0) {
×
1162
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
1163
                return;
×
1164
        }
1165

1166
        if (have_effective_cap(CAP_CHOWN) <= 0 ||
×
1167
            have_effective_cap(CAP_FOWNER) <= 0 ||
×
1168
            have_effective_cap(CAP_KILL) <= 0) {
×
1169
                log_notice("Skipping %s, this process does not have enough capabilities", __func__);
×
1170
                return;
×
1171
        }
1172

1173
        test(m, "exec-capabilityboundingset-simple.service", 0, CLD_EXITED);
×
1174
        test(m, "exec-capabilityboundingset-reset.service", 0, CLD_EXITED);
×
1175
        test(m, "exec-capabilityboundingset-merge.service", 0, CLD_EXITED);
×
1176
        test(m, "exec-capabilityboundingset-invert.service", 0, CLD_EXITED);
×
1177
}
1178

1179
static void test_exec_basic(Manager *m) {
×
1180
        if (isempty(gnu_get_libc_version()))
×
1181
                return (void) log_tests_skipped("ConditionVersion=glibc will not pass under musl");
×
1182

1183
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
1184
                test(m, "exec-basic.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1185
        else
1186
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1187
}
1188

1189
static void test_exec_ambientcapabilities(Manager *m) {
×
1190
        int r;
×
1191

1192
        /* Check if the kernel has support for ambient capabilities. Run
1193
         * the tests only if that's the case. Clearing all ambient
1194
         * capabilities is fine, since we are expecting them to be unset
1195
         * in the first place for the tests. */
1196
        r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0);
×
1197
        if (r < 0 && IN_SET(errno, EINVAL, EOPNOTSUPP, ENOSYS)) {
×
1198
                log_notice("Skipping %s, the kernel does not support ambient capabilities", __func__);
×
1199
                return;
×
1200
        }
1201

1202
        if (have_effective_cap(CAP_CHOWN) <= 0 ||
×
1203
            have_effective_cap(CAP_NET_RAW) <= 0) {
×
1204
                log_notice("Skipping %s, this process does not have enough capabilities", __func__);
×
1205
                return;
×
1206
        }
1207

1208
        test(m, "exec-ambientcapabilities.service", 0, CLD_EXITED);
×
1209
        test(m, "exec-ambientcapabilities-merge.service", 0, CLD_EXITED);
×
1210

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

1214
        if (!check_nobody_user_and_group()) {
×
1215
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
1216
                return;
×
1217
        }
1218

1219
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
1220
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
1221
                return;
×
1222
        }
1223

1224
        test(m, "exec-ambientcapabilities-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1225
        test(m, "exec-ambientcapabilities-merge-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1226
}
1227

1228
static void test_exec_privatenetwork(Manager *m) {
×
1229
        int r;
×
1230

1231
        if (!have_net_dummy)
×
1232
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1233

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

1237
        r = find_executable("ip", NULL);
×
1238
        if (r < 0) {
×
1239
                log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
×
1240
                return;
×
1241
        }
1242

1243
        test(m, "exec-privatenetwork-yes-privatemounts-no.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_FAILURE, CLD_EXITED);
×
1244
        test(m, "exec-privatenetwork-yes-privatemounts-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_NAMESPACE, CLD_EXITED);
×
1245
}
1246

1247
static void test_exec_networknamespacepath(Manager *m) {
×
1248
        int r;
×
1249

1250
        if (!have_net_dummy)
×
1251
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1252

1253
        if (!have_netns)
×
1254
                return (void)log_notice("Skipping %s, network namespace not available", __func__);
×
1255

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

1259
        r = find_executable("ip", NULL);
×
1260
        if (r < 0) {
×
1261
                log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
×
1262
                return;
×
1263
        }
1264

1265
        test(m, "exec-networknamespacepath-privatemounts-no.service", MANAGER_IS_SYSTEM(m) ? EXIT_SUCCESS : EXIT_FAILURE, CLD_EXITED);
×
1266
        test(m, "exec-networknamespacepath-privatemounts-yes.service", can_unshare ? EXIT_SUCCESS : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
1267
}
1268

1269
static void test_exec_oomscoreadjust(Manager *m) {
×
1270
        test(m, "exec-oomscoreadjust-positive.service", 0, CLD_EXITED);
×
1271

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

1279
static void test_exec_ioschedulingclass(Manager *m) {
×
1280
        test(m, "exec-ioschedulingclass-none.service", 0, CLD_EXITED);
×
1281
        test(m, "exec-ioschedulingclass-idle.service", 0, CLD_EXITED);
×
1282
        test(m, "exec-ioschedulingclass-best-effort.service", 0, CLD_EXITED);
×
1283

1284
        if (detect_container() > 0) {
×
1285
                log_notice("Testing in container, skipping remaining tests in %s", __func__);
×
1286
                return;
×
1287
        }
1288
        test(m, "exec-ioschedulingclass-realtime.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_IOPRIO, CLD_EXITED);
×
1289
}
1290

1291
static void test_exec_unsetenvironment(Manager *m) {
×
1292
        test(m, "exec-unsetenvironment.service", 0, CLD_EXITED);
×
1293
}
×
1294

1295
static void test_exec_specifier(Manager *m) {
×
1296
        test(m, "exec-specifier.service", 0, CLD_EXITED);
×
1297
        if (MANAGER_IS_SYSTEM(m))
×
1298
                test(m, "exec-specifier-system.service", 0, CLD_EXITED);
×
1299
        else
1300
                test(m, "exec-specifier-user.service", 0, CLD_EXITED);
×
1301
        test(m, "exec-specifier@foo-bar.service", 0, CLD_EXITED);
×
1302
        test(m, "exec-specifier-interpolation.service", 0, CLD_EXITED);
×
1303
}
×
1304

1305
static void test_exec_standardinput(Manager *m) {
×
1306
        test(m, "exec-standardinput-data.service", 0, CLD_EXITED);
×
1307
        test(m, "exec-standardinput-file.service", 0, CLD_EXITED);
×
1308

1309
        ExecOutput saved = m->defaults.std_output;
×
1310
        m->defaults.std_output = EXEC_OUTPUT_NULL;
×
1311
        test(m, "exec-standardinput-file-cat.service", 0, CLD_EXITED);
×
1312
        m->defaults.std_output = saved;
×
1313
}
×
1314

1315
static void test_exec_standardoutput(Manager *m) {
×
1316
        test(m, "exec-standardoutput-file.service", 0, CLD_EXITED);
×
1317
}
×
1318

1319
static void test_exec_standardoutput_append(Manager *m) {
×
1320
        test(m, "exec-standardoutput-append.service", 0, CLD_EXITED);
×
1321
}
×
1322

1323
static void test_exec_standardoutput_truncate(Manager *m) {
×
1324
        test(m, "exec-standardoutput-truncate.service", 0, CLD_EXITED);
×
1325
}
×
1326

1327
static void test_exec_condition(Manager *m) {
×
1328
        test_service(m, "exec-condition-failed.service", SERVICE_FAILURE_EXIT_CODE);
×
1329
        test_service(m, "exec-condition-skip.service", SERVICE_SKIP_CONDITION);
×
1330
}
×
1331

1332
static void test_exec_umask_namespace(Manager *m) {
×
1333
        /* exec-specifier-credentials-dir.service creates /run/credentials and enables implicit
1334
         * InaccessiblePath= for the directory for all later services with mount namespace. */
1335
        if (!is_inaccessible_available()) {
×
1336
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
1337
                return;
×
1338
        }
1339
        test(m, "exec-umask-namespace.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NAMESPACE : EXIT_GROUP, CLD_EXITED);
×
1340
}
1341

1342
typedef struct test_entry {
1343
        test_function_t f;
1344
        const char *name;
1345
} test_entry;
1346

1347
#define entry(x) {x, #x}
1348

1349
static void run_tests(RuntimeScope scope, char **patterns) {
×
1350
        _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL;
×
1351
        _cleanup_free_ char *unit_paths = NULL;
×
1352
        _cleanup_(manager_freep) Manager *m = NULL;
×
1353
        usec_t start, finish;
×
1354
        int r;
×
1355

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

1409
        ASSERT_OK_ERRNO(unsetenv("USER"));
×
1410
        ASSERT_OK_ERRNO(unsetenv("LOGNAME"));
×
1411
        ASSERT_OK_ERRNO(unsetenv("SHELL"));
×
1412
        ASSERT_OK_ERRNO(unsetenv("HOME"));
×
1413
        ASSERT_OK_ERRNO(unsetenv("TMPDIR"));
×
1414

1415
        /* Unset VARx, especially, VAR1, VAR2 and VAR3, which are used in the PassEnvironment test cases,
1416
         * otherwise (and if they are present in the environment), `manager_default_environment` will copy
1417
         * them into the default environment which is passed to each created job, which will make the tests
1418
         * that expect those not to be present to fail. */
1419
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
1420
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
1421
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
1422
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
1423
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
1424

1425
        ASSERT_NOT_NULL((runtime_dir = setup_fake_runtime_dir()));
×
1426
        ASSERT_NOT_NULL((user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")));
×
1427
        ASSERT_NOT_NULL((unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)));
×
1428
        ASSERT_OK(setenv_unit_path(unit_paths));
×
1429

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

1434
        r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m);
×
1435
        if (manager_errno_skip_test(r))
×
1436
                return (void) log_tests_skipped_errno(r, "manager_new");
×
1437
        ASSERT_OK(r);
×
1438

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

1442
        /* Uncomment below if you want to make debugging logs stored to journal. */
1443
        //manager_override_log_target(m, LOG_TARGET_AUTO);
1444
        //manager_override_log_level(m, LOG_DEBUG);
1445

1446
        /* Measure and print the time that it takes to run tests, excluding startup of the manager object,
1447
         * to try and measure latency of spawning services */
1448
        n_ran_tests = 0;
×
1449
        start = now(CLOCK_MONOTONIC);
×
1450

1451
        for (const test_entry *test = tests; test->f; test++)
×
1452
                if (strv_fnmatch_or_empty(patterns, test->name, FNM_NOESCAPE)) {
×
1453
                        log_info("Starting %s.", test->name);
×
1454
                        test->f(m);
×
1455
                } else
1456
                        log_info("Skipping %s because it does not match any pattern.", test->name);
×
1457

1458
        finish = now(CLOCK_MONOTONIC);
×
1459

1460
        log_info("ran %u tests with %s manager + unshare=%s in: %s",
×
1461
                 n_ran_tests,
1462
                 scope == RUNTIME_SCOPE_SYSTEM ? "system" : "user",
1463
                 yes_no(can_unshare),
1464
                 FORMAT_TIMESPAN(finish - start, USEC_PER_MSEC));
1465
}
1466

1467
static int prepare_ns(const char *process_name) {
×
1468
        int r;
×
1469

1470
        r = safe_fork(process_name,
×
1471
                      FORK_RESET_SIGNALS |
1472
                      FORK_CLOSE_ALL_FDS |
1473
                      FORK_DEATHSIG_SIGTERM |
1474
                      FORK_WAIT |
1475
                      FORK_REOPEN_LOG |
1476
                      FORK_LOG |
1477
                      FORK_NEW_MOUNTNS |
1478
                      FORK_MOUNTNS_SLAVE,
1479
                      NULL);
1480
        ASSERT_OK(r);
×
1481
        if (r == 0) {
×
1482
                _cleanup_free_ char *unit_dir = NULL, *build_dir = NULL, *build_dir_mount = NULL;
×
1483

1484
                const char *coverage = getenv("COVERAGE_BUILD_DIR");
×
1485
                if (!coverage)
×
1486
                        /* Make "/" read-only. */
1487
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL));
×
1488

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

1494
                ASSERT_OK(mkdir_p(PRIVATE_UNIT_DIR, 0755));
×
1495
                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", PRIVATE_UNIT_DIR, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1496
                /* Mark our test "playground" as MS_SLAVE, so we can MS_MOVE mounts underneath it. */
1497
                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, PRIVATE_UNIT_DIR, NULL, MS_SLAVE, NULL));
×
1498

1499
                /* Copy unit files to make them accessible even when unprivileged. */
1500
                ASSERT_OK(get_testdata_dir("test-execute/", &unit_dir));
×
1501
                ASSERT_OK(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY));
×
1502

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

1506
                if (build_dir) {
×
1507
                        /* Account for a build directory being in one of the soon-to-be-tmpfs directories. If we
1508
                         * overmount it with an empty tmpfs, manager_new() will pin the wrong systemd-executor binary,
1509
                         * which can then lead to unexpected (and painful to debug) test fails. */
1510
                        ASSERT_OK_ERRNO(access(build_dir, F_OK));
×
1511
                        ASSERT_NOT_NULL((build_dir_mount = path_join(PRIVATE_UNIT_DIR, "build_dir")));
×
1512
                        ASSERT_OK(mkdir_p(build_dir_mount, 0755));
×
1513
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir, build_dir_mount, NULL, MS_BIND, NULL));
×
1514
                }
1515

1516
                FOREACH_STRING(p, "/dev/shm", "/root", "/tmp", "/var/tmp", "/var/lib")
×
1517
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1518

1519
                if (build_dir_mount) {
×
1520
                        int k;
×
1521

1522
                        ASSERT_OK_OR(k = RET_NERRNO(access(build_dir, F_OK)), -ENOENT);
×
1523

1524
                        if (k == -ENOENT) {
×
1525
                                /* The build directory got overmounted by tmpfs, so let's use the "backup" bind mount to
1526
                                 * bring it back. */
1527
                                ASSERT_OK(mkdir_p(build_dir, 0755));
×
1528
                                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir_mount, build_dir, NULL, MS_MOVE, NULL));
×
1529
                        }
1530
                }
1531

1532
                /* Prepare credstore like tmpfiles.d/credstore.conf for LoadCredential= tests. */
1533
                FOREACH_STRING(p, "/run/credstore", "/run/credstore.encrypted") {
×
1534
                        ASSERT_OK(mkdir_p(p, 0700));
×
1535
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0700"));
×
1536
                }
1537

1538
                ASSERT_OK(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE));
×
1539
        }
1540

1541
        return r;
×
1542
}
1543

1544
TEST(run_tests_root) {
×
1545
        _cleanup_strv_free_ char **filters = NULL;
×
1546

1547
        if (!have_namespaces())
×
1548
                return (void) log_tests_skipped("unshare() is disabled");
×
1549

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

1553
        if (prepare_ns("(test-execute-root)") == 0) {
×
1554
                can_unshare = true;
×
1555
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1556
                _exit(EXIT_SUCCESS);
×
1557
        }
1558
}
1559

1560
TEST(run_tests_without_unshare) {
×
1561
        if (!have_namespaces()) {
×
1562
                /* unshare() is already filtered. */
1563
                can_unshare = false;
×
1564
                run_tests(RUNTIME_SCOPE_SYSTEM, strv_skip(saved_argv, 1));
×
1565
                return;
×
1566
        }
1567

1568
#if HAVE_SECCOMP
1569
        _cleanup_strv_free_ char **filters = NULL;
×
1570
        int r;
×
1571

1572
        /* The following tests are for 1beab8b0d0ff2d7d1436b52d4a0c3d56dc908962. */
1573
        if (!is_seccomp_available())
×
1574
                return (void) log_tests_skipped("Seccomp not available, cannot run unshare() filtered tests");
×
1575

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

1579
        if (prepare_ns("(test-execute-without-unshare)") == 0) {
×
1580
                _cleanup_hashmap_free_ Hashmap *s = NULL;
×
1581

1582
                r = sym_seccomp_syscall_resolve_name("unshare");
×
1583
                ASSERT_NE(r, __NR_SCMP_ERROR);
×
1584
                ASSERT_OK(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1)));
×
1585
                ASSERT_OK(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true));
×
1586

1587
                /* Check unshare() is actually filtered. */
1588
                ASSERT_ERROR_ERRNO(unshare(CLONE_NEWNS), EOPNOTSUPP);
×
1589

1590
                can_unshare = false;
×
1591
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1592
                _exit(EXIT_SUCCESS);
×
1593
        }
1594
#else
1595
        log_tests_skipped("Built without seccomp support, cannot run unshare() filtered tests");
1596
#endif
1597
}
1598

1599
TEST(run_tests_unprivileged) {
×
1600
        _cleanup_strv_free_ char **filters = NULL;
×
1601

1602
        if (!have_namespaces())
×
1603
                return (void) log_tests_skipped("unshare() is disabled");
×
1604

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

1608
        if (prepare_ns("(test-execute-unprivileged)") == 0) {
×
1609
                ASSERT_OK(capability_bounding_set_drop(0, /* right_now = */ true));
×
1610

1611
                can_unshare = false;
×
1612
                run_tests(RUNTIME_SCOPE_USER, filters);
×
1613
                _exit(EXIT_SUCCESS);
×
1614
        }
1615
}
1616

1617
static int intro(void) {
1✔
1618
        int r;
1✔
1619

1620
#if HAS_FEATURE_ADDRESS_SANITIZER
1621
        if (strstr_ptr(ci_environment(), "travis") || strstr_ptr(ci_environment(), "github-actions"))
1622
                return log_tests_skipped("Running on Travis CI/GH Actions under ASan, see https://github.com/systemd/systemd/issues/10696");
1623
#endif
1624
        /* It is needed otherwise cgroup creation fails */
1625
        if (geteuid() != 0 || have_effective_cap(CAP_SYS_ADMIN) <= 0)
1✔
1626
                return log_tests_skipped("not privileged");
×
1627

1628
        if (running_in_chroot() != 0)
1✔
1629
                return log_tests_skipped("running in chroot");
×
1630

1631
        if (enter_cgroup_subroot(NULL) == -ENOMEDIUM)
1✔
1632
                return log_tests_skipped("cgroupfs not available");
×
1633

1634
        if (path_is_read_only_fs("/sys") > 0)
1✔
1635
                return log_tests_skipped("/sys is mounted read-only");
1✔
1636

1637
        r = dlopen_libmount();
×
1638
        if (r < 0)
×
1639
                return log_tests_skipped("libmount not available.");
×
1640

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

1644
        if (have_net_dummy) {
×
1645
                /* Create a network namespace and a dummy interface in it for NetworkNamespacePath= */
1646
                have_netns = system("ip netns add test-execute-netns") == 0;
×
1647
                have_netns = have_netns && system("ip netns exec test-execute-netns ip link add dummy-test-ns type dummy") == 0;
×
1648
        }
1649

1650
        return EXIT_SUCCESS;
1651
}
1652

1653
static int outro(void) {
1✔
1654
        if (have_net_dummy) {
1✔
1655
                (void) system("ip link del dummy-test-exec");
×
1656
                (void) system("ip netns del test-execute-netns");
×
1657
        }
1658

1659
        (void) rmdir(PRIVATE_UNIT_DIR);
1✔
1660

1661
        return EXIT_SUCCESS;
1✔
1662
}
1663

1664
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