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

systemd / systemd / 17844524571

18 Sep 2025 08:58PM UTC coverage: 72.326% (+0.09%) from 72.24%
17844524571

push

github

DaanDeMeyer
userdb: suppress creation of empty userdb dirs

13 of 16 new or added lines in 1 file covered. (81.25%)

3248 existing lines in 52 files now uncovered.

303003 of 418940 relevant lines covered (72.33%)

1051258.58 hits per line

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

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

3
#include <fnmatch.h>
4
#include <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, /* subgroup= */ NULL, SIGKILL, SI_USER, /* value= */ 0, /* ret_error= */ 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
                ASSERT_OK_OR(unit_start(slice, NULL), -EALREADY);
×
227
        }
228
}
×
229

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

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

241
                return false;
×
242
        }
243

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

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

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

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

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

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

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

288
        return r == EXIT_SUCCESS;
×
289
}
290

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

295
        ASSERT_NOT_NULL(unit_name);
×
296

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

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

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

313
        ASSERT_NOT_NULL(unit_name);
×
314

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

417
        int r;
×
418

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

670
        ASSERT_NOT_NULL(pid);
×
671

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

674
        return 1;
×
675
}
676

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

680
        ASSERT_NOT_NULL(si);
×
681

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

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

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

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

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

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

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

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

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

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

733
        ASSERT_OK(sd_event_loop(e));
×
734

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

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

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

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

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

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

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

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

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

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

784
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
785

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1010
        return NULL;
1011
}
1012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1448
        finish = now(CLOCK_MONOTONIC);
×
1449

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1531
        return r;
×
1532
}
1533

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1634
        return EXIT_SUCCESS;
1635
}
1636

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

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

1645
        return EXIT_SUCCESS;
1✔
1646
}
1647

1648
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