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

systemd / systemd / 15313160050

28 May 2025 09:01PM UTC coverage: 72.04% (+0.06%) from 71.981%
15313160050

push

github

poettering
update NEWS

299462 of 415690 relevant lines covered (72.04%)

702804.32 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

10
#include "sd-event.h"
11

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

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

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

49
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
1✔
50

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

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

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

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

69
        abort();
×
70
}
71

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

76
        ASSERT_NOT_NULL(m);
×
77

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

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

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

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

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

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

101
        wait_for_service_finish(m, unit);
×
102

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

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

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

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

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

128
        wait_for_service_finish(m, unit);
×
129

130
        service = SERVICE(unit);
×
131

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

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

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

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

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

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

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

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

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

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

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

190
        ASSERT_NOT_NULL(name);
×
191

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

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

202
        return true;
203
}
204

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

216
        return true;
×
217
}
218

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

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

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

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

242
                return false;
×
243
        }
244

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

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

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

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

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

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

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

289
        return r == EXIT_SUCCESS;
×
290
}
291

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

296
        ASSERT_NOT_NULL(unit_name);
×
297

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

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

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

314
        ASSERT_NOT_NULL(unit_name);
×
315

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

418
        int r;
×
419

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

671
        ASSERT_NOT_NULL(pid);
×
672

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

675
        return 1;
×
676
}
677

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

681
        ASSERT_NOT_NULL(si);
×
682

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

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

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

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

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

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

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

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

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

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

734
        ASSERT_OK(sd_event_loop(e));
×
735

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

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

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

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

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

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

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

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

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

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

785
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
786

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1011
        return NULL;
1012
}
1013

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1449
        finish = now(CLOCK_MONOTONIC);
×
1450

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1535
        return r;
×
1536
}
1537

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1635
        return EXIT_SUCCESS;
1636
}
1637

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

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

1646
        return EXIT_SUCCESS;
1✔
1647
}
1648

1649
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