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

systemd / systemd / 15986406979

30 Jun 2025 05:03PM UTC coverage: 72.045% (-0.09%) from 72.13%
15986406979

push

github

bluca
man/systemd-sysext: list ephemeral/ephemeral-import in the list of options

ephemeral/ephemeral-import are described as possible '--mutable' options but
not present in the list. Note, "systemd-sysext --help" lists them correctly.

300514 of 417119 relevant lines covered (72.05%)

708586.28 hits per line

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

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

3
#include <fnmatch.h>
4
#include <linux/prctl.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 "manager.h"
25
#include "mkdir.h"
26
#include "mount-util.h"
27
#include "path-util.h"
28
#include "process-util.h"
29
#include "rm-rf.h"
30
#include "seccomp-util.h"
31
#include "service.h"
32
#include "signal-util.h"
33
#include "stat-util.h"
34
#include "static-destruct.h"
35
#include "strv.h"
36
#include "sysctl-util.h"
37
#include "tests.h"
38
#include "unit.h"
39
#include "user-util.h"
40
#include "virt.h"
41

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

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

50
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
1✔
51

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

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

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

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

70
        abort();
×
71
}
72

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

77
        ASSERT_NOT_NULL(m);
×
78

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

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

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

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

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

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

102
        wait_for_service_finish(m, unit);
×
103

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

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

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

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

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

129
        wait_for_service_finish(m, unit);
×
130

131
        service = SERVICE(unit);
×
132

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

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

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

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

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

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

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

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

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

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

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

191
        ASSERT_NOT_NULL(name);
×
192

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

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

203
        return true;
204
}
205

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

217
        return true;
×
218
}
219

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

223
        slice = UNIT_GET_SLICE(unit);
×
224
        if (slice) {
×
225
                start_parent_slices(slice);
×
226
                int r = unit_start(slice, NULL);
×
227
                if (r != -EALREADY)
×
228
                        ASSERT_OK(r);
×
229
        }
230
}
×
231

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

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

243
                return false;
×
244
        }
245

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

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

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

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

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

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

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

290
        return r == EXIT_SUCCESS;
×
291
}
292

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

297
        ASSERT_NOT_NULL(unit_name);
×
298

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

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

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

315
        ASSERT_NOT_NULL(unit_name);
×
316

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

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

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

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

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

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

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

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

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

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

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

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

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

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

372
static void test_exec_execsearchpath(Manager *m) {
×
373
        ASSERT_OK(mkdir_p("/tmp/test-exec_execsearchpath", 0755));
×
374

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

377
        test(m, "exec-execsearchpath.service", 0, CLD_EXITED);
×
378

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

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

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

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

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

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

419
        int r;
×
420

421
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile.conf", path_not_set, WRITE_STRING_FILE_CREATE);
×
422
        ASSERT_OK(r);
×
423

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

426
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
427

428
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile-set.conf", path_set, WRITE_STRING_FILE_CREATE);
×
429
        ASSERT_OK(r);
×
430

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

433
        (void) unlink("/tmp/test-exec_environmentfile-set.conf");
×
434
}
×
435

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

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

445
        ASSERT_OK_ERRNO(setenv("PATH", "/usr", 1));
×
446
        test(m, "exec-execsearchpath-passenvironment-set.service", 0, CLD_EXITED);
×
447

448
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
449
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
450
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
451
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
452
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
453
        ASSERT_OK_ERRNO(unsetenv("PATH"));
×
454
}
×
455

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

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

463
#elif defined(__s390__)
464
        test(m, "exec-personality-s390.service", 0, CLD_EXITED);
465

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

473
#elif defined(__aarch64__)
474
        test(m, "exec-personality-aarch64.service", 0, CLD_EXITED);
475

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

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

490
static void test_exec_privatetmp(Manager *m) {
×
491
        ASSERT_OK(touch("/tmp/test-exec_privatetmp"));
×
492

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

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

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

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

518
        (void) unlink("/tmp/test-exec_privatetmp");
×
519
}
×
520

521
static void test_exec_privatedevices(Manager *m) {
×
522
        int r;
×
523

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

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

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

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

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

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

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

566
        test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
×
567
}
568

569
static void test_exec_protectkernelmodules(Manager *m) {
×
570
        int r;
×
571

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

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

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

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

595
static void test_exec_readonlypaths(Manager *m) {
×
596

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

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

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

610
static void test_exec_readwritepaths(Manager *m) {
×
611

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

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

620
static void test_exec_inaccessiblepaths(Manager *m) {
×
621

622
        if (!is_inaccessible_available()) {
×
623
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
624
                return;
×
625
        }
626

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

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

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

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

644
        ASSERT_NOT_NULL(s);
×
645
        ASSERT_GT(fd, 0);
×
646

647
        l = read(fd, buf, sizeof(buf) - 1);
×
648
        if (l < 0) {
×
649
                if (errno == EAGAIN)
×
650
                        goto reenable;
×
651

652
                return 0;
×
653
        }
654
        if (l == 0)
×
655
                return 0;
656

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

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

669
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
×
670
        pid_t *pid = userdata;
×
671

672
        ASSERT_NOT_NULL(pid);
×
673

674
        (void) kill(*pid, SIGKILL);
×
675

676
        return 1;
×
677
}
678

679
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
×
680
        int ret = -EIO;
×
681

682
        ASSERT_NOT_NULL(si);
×
683

684
        if (si->si_code == CLD_EXITED)
×
685
                ret = si->si_status;
×
686

687
        sd_event_exit(sd_event_source_get_event(s), ret);
×
688
        return 1;
×
689
}
690

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

702
        ASSERT_NOT_NULL(exec);
×
703
        ASSERT_NOT_NULL(ret);
×
704

705
        ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD));
×
706

707
        ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
×
708
        ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
×
709

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

720
        outpipe[1] = safe_close(outpipe[1]);
×
721
        errpipe[1] = safe_close(errpipe[1]);
×
722

723
        ASSERT_OK(sd_event_new(&e));
×
724

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

735
        ASSERT_OK(sd_event_loop(e));
×
736

737
        _cleanup_strv_free_ char **v = NULL;
×
738
        ASSERT_OK(strv_split_newlines_full(&v, result, 0));
×
739

740
        STRV_FOREACH(q, v) {
×
741
                _cleanup_free_ char *word = NULL;
×
742
                const char *p = *q;
×
743

744
                r = extract_first_word(&p, &word, NULL, 0);
×
745
                ASSERT_OK(r);
×
746
                if (r == 0)
×
747
                        continue;
×
748

749
                if (path_is_absolute(word)) {
×
750
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
751
                        continue;
×
752
                }
753

754
                word = mfree(word);
×
755
                r = extract_first_word(&p, &word, NULL, 0);
×
756
                ASSERT_OK(r);
×
757
                if (r == 0)
×
758
                        continue;
×
759

760
                if (!streq_ptr(word, "=>"))
×
761
                        continue;
×
762

763
                word = mfree(word);
×
764
                r = extract_first_word(&p, &word, NULL, 0);
×
765
                ASSERT_OK(r);
×
766
                if (r == 0)
×
767
                        continue;
×
768

769
                if (path_is_absolute(word)) {
×
770
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
771
                        continue;
×
772
                }
773
        }
774

775
        *ret = TAKE_PTR(libraries);
×
776
        return 0;
×
777
}
778
#endif
779

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

786
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
787

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

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

807
        ASSERT_OK(find_libraries(fullpath_touch, &libraries));
×
808
        ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
×
809
        ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
×
810

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

817
        STRV_FOREACH(p, libraries)
×
818
                ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
×
819

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

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

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

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

830
static void test_exec_noexecpaths(Manager *m) {
×
831

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

838
static void test_exec_temporaryfilesystem(Manager *m) {
×
839

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

846
static void test_exec_systemcallfilter(Manager *m) {
×
847
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
848
        int r;
×
849

850
        if (!is_seccomp_available()) {
×
851
                log_notice("Seccomp not available, skipping %s", __func__);
×
852
                return;
×
853
        }
854

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

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

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

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

877
        test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
878
        test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
879

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

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

891
static void test_exec_systemcallerrornumber(Manager *m) {
×
892
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
893
        int r;
×
894

895
        if (!is_seccomp_available()) {
×
896
                log_notice("Seccomp not available, skipping %s", __func__);
×
897
                return;
×
898
        }
899

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

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

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

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

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

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

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

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

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

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

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

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

969
        test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
970
}
971

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

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

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

985
        test(m, "exec-group-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
986
}
987

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

998
static char* private_directory_bad(Manager *m) {
×
999
        /* This mirrors setup_exec_directory(). */
1000

1001
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
×
1002
                _cleanup_free_ char *p = NULL;
×
1003
                struct stat st;
×
1004

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

1007
                if (stat(p, &st) >= 0 &&
×
1008
                    (st.st_mode & (S_IRWXG|S_IRWXO)))
×
1009
                        return TAKE_PTR(p);
×
1010
        }
1011

1012
        return NULL;
1013
}
1014

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

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

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

1032
        int status = can_unshare ? 0 : EXIT_NAMESPACE;
×
1033

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

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

1052
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1053
        test(m, "exec-dynamicuser-statedir-migrate-step2.service", status, CLD_EXITED);
×
1054
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1055

1056
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1057
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1058
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1059
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1060

1061
        test(m, "exec-dynamicuser-runtimedirectory1.service", status, CLD_EXITED);
×
1062
        test(m, "exec-dynamicuser-runtimedirectory2.service", status, CLD_EXITED);
×
1063
        test(m, "exec-dynamicuser-runtimedirectory3.service", status, CLD_EXITED);
×
1064
}
1065

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

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

1087
        r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE);
×
1088
        ASSERT_OK(r);
×
1089

1090
        test(m, "exec-environmentfile.service", 0, CLD_EXITED);
×
1091

1092
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
1093
}
×
1094

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

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

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

1136
        test(m, "exec-runtimedirectory-mode.service", 0, CLD_EXITED);
×
1137
        test(m, "exec-runtimedirectory-owner.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1138

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

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

1149
        test(m, "exec-runtimedirectory-owner-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1150
}
1151

1152
static void test_exec_capabilityboundingset(Manager *m) {
×
1153
        int r;
×
1154

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

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

1168
        test(m, "exec-capabilityboundingset-simple.service", 0, CLD_EXITED);
×
1169
        test(m, "exec-capabilityboundingset-reset.service", 0, CLD_EXITED);
×
1170
        test(m, "exec-capabilityboundingset-merge.service", 0, CLD_EXITED);
×
1171
        test(m, "exec-capabilityboundingset-invert.service", 0, CLD_EXITED);
×
1172
}
1173

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

1181
static void test_exec_ambientcapabilities(Manager *m) {
×
1182
        int r;
×
1183

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

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

1200
        test(m, "exec-ambientcapabilities.service", 0, CLD_EXITED);
×
1201
        test(m, "exec-ambientcapabilities-merge.service", 0, CLD_EXITED);
×
1202

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

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

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

1216
        test(m, "exec-ambientcapabilities-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1217
        test(m, "exec-ambientcapabilities-merge-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1218
}
1219

1220
static void test_exec_privatenetwork(Manager *m) {
×
1221
        int r;
×
1222

1223
        if (!have_net_dummy)
×
1224
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1225

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

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

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

1239
static void test_exec_networknamespacepath(Manager *m) {
×
1240
        int r;
×
1241

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

1245
        if (!have_netns)
×
1246
                return (void)log_notice("Skipping %s, network namespace not available", __func__);
×
1247

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

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

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

1261
static void test_exec_oomscoreadjust(Manager *m) {
×
1262
        test(m, "exec-oomscoreadjust-positive.service", 0, CLD_EXITED);
×
1263

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

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

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

1283
static void test_exec_unsetenvironment(Manager *m) {
×
1284
        test(m, "exec-unsetenvironment.service", 0, CLD_EXITED);
×
1285
}
×
1286

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

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

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

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

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

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

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

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

1334
typedef struct test_entry {
1335
        test_function_t f;
1336
        const char *name;
1337
} test_entry;
1338

1339
#define entry(x) {x, #x}
1340

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

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

1401
        ASSERT_OK_ERRNO(unsetenv("USER"));
×
1402
        ASSERT_OK_ERRNO(unsetenv("LOGNAME"));
×
1403
        ASSERT_OK_ERRNO(unsetenv("SHELL"));
×
1404
        ASSERT_OK_ERRNO(unsetenv("HOME"));
×
1405
        ASSERT_OK_ERRNO(unsetenv("TMPDIR"));
×
1406

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

1417
        ASSERT_NOT_NULL((runtime_dir = setup_fake_runtime_dir()));
×
1418
        ASSERT_NOT_NULL((user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")));
×
1419
        ASSERT_NOT_NULL((unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)));
×
1420
        ASSERT_OK(setenv_unit_path(unit_paths));
×
1421

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

1426
        r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m);
×
1427
        if (manager_errno_skip_test(r))
×
1428
                return (void) log_tests_skipped_errno(r, "manager_new");
×
1429
        ASSERT_OK(r);
×
1430

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

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

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

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

1450
        finish = now(CLOCK_MONOTONIC);
×
1451

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

1459
static int prepare_ns(const char *process_name) {
×
1460
        int r;
×
1461

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

1477
                const char *coverage = getenv("COVERAGE_BUILD_DIR");
×
1478
                if (!coverage)
×
1479
                        /* Make "/" read-only. */
1480
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL));
×
1481

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

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

1492
                /* Copy unit files to make them accessible even when unprivileged. */
1493
                ASSERT_OK(get_testdata_dir("test-execute/", &unit_dir));
×
1494
                ASSERT_OK(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY));
×
1495

1496
                /* Mount tmpfs on the following directories to make not StateDirectory= or friends disturb the host. */
1497
                ret = get_build_exec_dir(&build_dir);
×
1498
                if (ret != -ENOEXEC)
×
1499
                        ASSERT_OK(ret);
×
1500

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

1511
                FOREACH_STRING(p, "/dev/shm", "/root", "/tmp", "/var/tmp", "/var/lib")
×
1512
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1513

1514
                if (build_dir_mount) {
×
1515
                        ret = RET_NERRNO(access(build_dir, F_OK));
×
1516
                        if (ret != -ENOENT)
×
1517
                                ASSERT_OK(ret);
×
1518

1519
                        if (ret == -ENOENT) {
×
1520
                                /* The build directory got overmounted by tmpfs, so let's use the "backup" bind mount to
1521
                                 * bring it back. */
1522
                                ASSERT_OK(mkdir_p(build_dir, 0755));
×
1523
                                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir_mount, build_dir, NULL, MS_MOVE, NULL));
×
1524
                        }
1525
                }
1526

1527
                /* Prepare credstore like tmpfiles.d/credstore.conf for LoadCredential= tests. */
1528
                FOREACH_STRING(p, "/run/credstore", "/run/credstore.encrypted") {
×
1529
                        ASSERT_OK(mkdir_p(p, 0700));
×
1530
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0700"));
×
1531
                }
1532

1533
                ASSERT_OK(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE));
×
1534
        }
1535

1536
        return r;
×
1537
}
1538

1539
TEST(run_tests_root) {
×
1540
        _cleanup_strv_free_ char **filters = NULL;
×
1541

1542
        if (!have_namespaces())
×
1543
                return (void) log_tests_skipped("unshare() is disabled");
×
1544

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

1548
        if (prepare_ns("(test-execute-root)") == 0) {
×
1549
                can_unshare = true;
×
1550
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1551
                _exit(EXIT_SUCCESS);
×
1552
        }
1553
}
1554

1555
TEST(run_tests_without_unshare) {
×
1556
        if (!have_namespaces()) {
×
1557
                /* unshare() is already filtered. */
1558
                can_unshare = false;
×
1559
                run_tests(RUNTIME_SCOPE_SYSTEM, strv_skip(saved_argv, 1));
×
1560
                return;
×
1561
        }
1562

1563
#if HAVE_SECCOMP
1564
        _cleanup_strv_free_ char **filters = NULL;
×
1565
        int r;
×
1566

1567
        /* The following tests are for 1beab8b0d0ff2d7d1436b52d4a0c3d56dc908962. */
1568
        if (!is_seccomp_available())
×
1569
                return (void) log_tests_skipped("Seccomp not available, cannot run unshare() filtered tests");
×
1570

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

1574
        if (prepare_ns("(test-execute-without-unshare)") == 0) {
×
1575
                _cleanup_hashmap_free_ Hashmap *s = NULL;
×
1576

1577
                r = seccomp_syscall_resolve_name("unshare");
×
1578
                ASSERT_NE(r, __NR_SCMP_ERROR);
×
1579
                ASSERT_OK(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1)));
×
1580
                ASSERT_OK(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true));
×
1581

1582
                /* Check unshare() is actually filtered. */
1583
                ASSERT_ERROR_ERRNO(unshare(CLONE_NEWNS), EOPNOTSUPP);
×
1584

1585
                can_unshare = false;
×
1586
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1587
                _exit(EXIT_SUCCESS);
×
1588
        }
1589
#else
1590
        log_tests_skipped("Built without seccomp support, cannot run unshare() filtered tests");
1591
#endif
1592
}
1593

1594
TEST(run_tests_unprivileged) {
×
1595
        _cleanup_strv_free_ char **filters = NULL;
×
1596

1597
        if (!have_namespaces())
×
1598
                return (void) log_tests_skipped("unshare() is disabled");
×
1599

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

1603
        if (prepare_ns("(test-execute-unprivileged)") == 0) {
×
1604
                ASSERT_OK(capability_bounding_set_drop(0, /* right_now = */ true));
×
1605

1606
                can_unshare = false;
×
1607
                run_tests(RUNTIME_SCOPE_USER, filters);
×
1608
                _exit(EXIT_SUCCESS);
×
1609
        }
1610
}
1611

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

1621
        if (enter_cgroup_subroot(NULL) == -ENOMEDIUM)
1✔
1622
                return log_tests_skipped("cgroupfs not available");
×
1623

1624
        if (path_is_read_only_fs("/sys") > 0)
1✔
1625
                return log_tests_skipped("/sys is mounted read-only");
1✔
1626

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

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

1636
        return EXIT_SUCCESS;
1637
}
1638

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

1645
        (void) rmdir(PRIVATE_UNIT_DIR);
1✔
1646

1647
        return EXIT_SUCCESS;
1✔
1648
}
1649

1650
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