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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 hits per line

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

1.24
/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 <sys/mount.h>
7
#include <sys/prctl.h>
8
#include <sys/types.h>
9

10
#include "sd-event.h"
11

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

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

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

48
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
1✔
49

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

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

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

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

68
        abort();
×
69
}
70

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

75
        ASSERT_NOT_NULL(m);
×
76

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

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

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

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

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

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

100
        wait_for_service_finish(m, unit);
×
101

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

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

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

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

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

127
        wait_for_service_finish(m, unit);
×
128

129
        service = SERVICE(unit);
×
130

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

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

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

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

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

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

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

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

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

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

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

189
        ASSERT_NOT_NULL(name);
×
190

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

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

201
        return true;
202
}
203

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

215
        return true;
×
216
}
217

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

221
        slice = UNIT_GET_SLICE(unit);
×
222
        if (slice) {
×
223
                start_parent_slices(slice);
×
224
                int r = unit_start(slice, NULL);
×
225
                if (r != -EALREADY)
×
226
                        ASSERT_OK(r);
×
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_reset) 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
                FOREACH_STRING(s,
×
496
                               "exec-privatetmp-disconnected.service",
497
                               "exec-privatetmp-disconnected-defaultdependencies-no.service",
498
                               "exec-privatetmp-disconnected-requires-mounts-for-var.service",
499
                               "exec-privatetmp-disconnected-wants-mounts-for-var.service",
500
                               "exec-privatetmp-disconnected-after-and-requires-for-var.service",
501
                               "exec-privatetmp-disconnected-after-and-wants-for-var.service") {
502
                        (void) unlink("/tmp/test-exec_privatetmp_disconnected");
×
503
                        (void) unlink("/var/tmp/test-exec_privatetmp_disconnected");
×
504
                        test(m, s, can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
505
                        ASSERT_FAIL(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
×
506
                        ASSERT_FAIL(access("/var/tmp/test-exec_privatetmp_disconnected", F_OK));
×
507
                }
508
        }
509

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

512
        (void) unlink("/tmp/test-exec_privatetmp");
×
513
}
×
514

515
static void test_exec_privatedevices(Manager *m) {
×
516
        int r;
×
517

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

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

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

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

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

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

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

560
        test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
×
561
}
562

563
static void test_exec_protectkernelmodules(Manager *m) {
×
564
        int r;
×
565

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

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

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

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

589
static void test_exec_readonlypaths(Manager *m) {
×
590

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

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

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

604
static void test_exec_readwritepaths(Manager *m) {
×
605

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

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

614
static void test_exec_inaccessiblepaths(Manager *m) {
×
615

616
        if (!is_inaccessible_available()) {
×
617
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
618
                return;
×
619
        }
620

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

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

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

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

638
        ASSERT_NOT_NULL(s);
×
639
        ASSERT_GT(fd, 0);
×
640

641
        l = read(fd, buf, sizeof(buf) - 1);
×
642
        if (l < 0) {
×
643
                if (errno == EAGAIN)
×
644
                        goto reenable;
×
645

646
                return 0;
×
647
        }
648
        if (l == 0)
×
649
                return 0;
650

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

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

663
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
×
664
        pid_t *pid = userdata;
×
665

666
        ASSERT_NOT_NULL(pid);
×
667

668
        (void) kill(*pid, SIGKILL);
×
669

670
        return 1;
×
671
}
672

673
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
×
674
        int ret = -EIO;
×
675

676
        ASSERT_NOT_NULL(si);
×
677

678
        if (si->si_code == CLD_EXITED)
×
679
                ret = si->si_status;
×
680

681
        sd_event_exit(sd_event_source_get_event(s), ret);
×
682
        return 1;
×
683
}
684

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

696
        ASSERT_NOT_NULL(exec);
×
697
        ASSERT_NOT_NULL(ret);
×
698

699
        ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD));
×
700

701
        ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
×
702
        ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
×
703

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

714
        outpipe[1] = safe_close(outpipe[1]);
×
715
        errpipe[1] = safe_close(errpipe[1]);
×
716

717
        ASSERT_OK(sd_event_new(&e));
×
718

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

729
        ASSERT_OK(sd_event_loop(e));
×
730

731
        _cleanup_strv_free_ char **v = NULL;
×
732
        ASSERT_OK(strv_split_newlines_full(&v, result, 0));
×
733

734
        STRV_FOREACH(q, v) {
×
735
                _cleanup_free_ char *word = NULL;
×
736
                const char *p = *q;
×
737

738
                r = extract_first_word(&p, &word, NULL, 0);
×
739
                ASSERT_OK(r);
×
740
                if (r == 0)
×
741
                        continue;
×
742

743
                if (path_is_absolute(word)) {
×
744
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
745
                        continue;
×
746
                }
747

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

754
                if (!streq_ptr(word, "=>"))
×
755
                        continue;
×
756

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

763
                if (path_is_absolute(word)) {
×
764
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
765
                        continue;
×
766
                }
767
        }
768

769
        *ret = TAKE_PTR(libraries);
×
770
        return 0;
×
771
}
772
#endif
773

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

780
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
781

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

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

801
        ASSERT_OK(find_libraries(fullpath_touch, &libraries));
×
802
        ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
×
803
        ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
×
804

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

811
        STRV_FOREACH(p, libraries)
×
812
                ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
×
813

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

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

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

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

824
static void test_exec_noexecpaths(Manager *m) {
×
825

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

832
static void test_exec_temporaryfilesystem(Manager *m) {
×
833

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

840
static void test_exec_systemcallfilter(Manager *m) {
×
841
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
842
        int r;
×
843

844
        if (!is_seccomp_available()) {
×
845
                log_notice("Seccomp not available, skipping %s", __func__);
×
846
                return;
×
847
        }
848

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

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

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

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

871
        test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
872
        test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
873

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

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

885
static void test_exec_systemcallerrornumber(Manager *m) {
×
886
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
887
        int r;
×
888

889
        if (!is_seccomp_available()) {
×
890
                log_notice("Seccomp not available, skipping %s", __func__);
×
891
                return;
×
892
        }
893

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

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

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

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

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

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

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

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

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

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

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

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

963
        test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
964
}
965

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

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

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

979
        test(m, "exec-group-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
980
}
981

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

992
static char* private_directory_bad(Manager *m) {
×
993
        /* This mirrors setup_exec_directory(). */
994

995
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
×
996
                _cleanup_free_ char *p = NULL;
×
997
                struct stat st;
×
998

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

1001
                if (stat(p, &st) >= 0 &&
×
1002
                    (st.st_mode & (S_IRWXG|S_IRWXO)))
×
1003
                        return TAKE_PTR(p);
×
1004
        }
1005

1006
        return NULL;
1007
}
1008

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

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

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

1026
        int status = can_unshare ? 0 : EXIT_NAMESPACE;
×
1027

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

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

1046
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1047
        test(m, "exec-dynamicuser-statedir-migrate-step2.service", status, CLD_EXITED);
×
1048
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1049

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

1055
        test(m, "exec-dynamicuser-runtimedirectory1.service", status, CLD_EXITED);
×
1056
        test(m, "exec-dynamicuser-runtimedirectory2.service", status, CLD_EXITED);
×
1057
        test(m, "exec-dynamicuser-runtimedirectory3.service", status, CLD_EXITED);
×
1058
}
1059

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

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

1081
        r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE);
×
1082
        ASSERT_OK(r);
×
1083

1084
        test(m, "exec-environmentfile.service", 0, CLD_EXITED);
×
1085

1086
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
1087
}
×
1088

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

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

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

1130
        test(m, "exec-runtimedirectory-mode.service", 0, CLD_EXITED);
×
1131
        test(m, "exec-runtimedirectory-owner.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1132

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

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

1143
        test(m, "exec-runtimedirectory-owner-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1144
}
1145

1146
static void test_exec_capabilityboundingset(Manager *m) {
×
1147
        int r;
×
1148

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

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

1162
        test(m, "exec-capabilityboundingset-simple.service", 0, CLD_EXITED);
×
1163
        test(m, "exec-capabilityboundingset-reset.service", 0, CLD_EXITED);
×
1164
        test(m, "exec-capabilityboundingset-merge.service", 0, CLD_EXITED);
×
1165
        test(m, "exec-capabilityboundingset-invert.service", 0, CLD_EXITED);
×
1166
}
1167

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

1175
static void test_exec_ambientcapabilities(Manager *m) {
×
1176
        int r;
×
1177

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

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

1194
        test(m, "exec-ambientcapabilities.service", 0, CLD_EXITED);
×
1195
        test(m, "exec-ambientcapabilities-merge.service", 0, CLD_EXITED);
×
1196

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

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

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

1210
        test(m, "exec-ambientcapabilities-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1211
        test(m, "exec-ambientcapabilities-merge-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1212
}
1213

1214
static void test_exec_privatenetwork(Manager *m) {
×
1215
        int r;
×
1216

1217
        if (!have_net_dummy)
×
1218
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1219

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

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

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

1233
static void test_exec_networknamespacepath(Manager *m) {
×
1234
        int r;
×
1235

1236
        if (!have_net_dummy)
×
1237
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1238

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

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

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

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

1255
static void test_exec_oomscoreadjust(Manager *m) {
×
1256
        test(m, "exec-oomscoreadjust-positive.service", 0, CLD_EXITED);
×
1257

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

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

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

1277
static void test_exec_unsetenvironment(Manager *m) {
×
1278
        test(m, "exec-unsetenvironment.service", 0, CLD_EXITED);
×
1279
}
×
1280

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

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

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

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

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

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

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

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

1328
typedef struct test_entry {
1329
        test_function_t f;
1330
        const char *name;
1331
} test_entry;
1332

1333
#define entry(x) {x, #x}
1334

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

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

1395
        ASSERT_OK_ERRNO(unsetenv("USER"));
×
1396
        ASSERT_OK_ERRNO(unsetenv("LOGNAME"));
×
1397
        ASSERT_OK_ERRNO(unsetenv("SHELL"));
×
1398
        ASSERT_OK_ERRNO(unsetenv("HOME"));
×
1399
        ASSERT_OK_ERRNO(unsetenv("TMPDIR"));
×
1400

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

1411
        ASSERT_NOT_NULL((runtime_dir = setup_fake_runtime_dir()));
×
1412
        ASSERT_NOT_NULL((user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")));
×
1413
        ASSERT_NOT_NULL((unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)));
×
1414
        ASSERT_OK(setenv_unit_path(unit_paths));
×
1415

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

1420
        r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m);
×
1421
        if (manager_errno_skip_test(r))
×
1422
                return (void) log_tests_skipped_errno(r, "manager_new");
×
1423
        ASSERT_OK(r);
×
1424

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

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

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

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

1444
        finish = now(CLOCK_MONOTONIC);
×
1445

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

1453
static int prepare_ns(const char *process_name) {
×
1454
        int r;
×
1455

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

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

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

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

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

1490
                /* Mount tmpfs on the following directories to make not StateDirectory= or friends disturb the host. */
1491
                ret = get_build_exec_dir(&build_dir);
×
1492
                if (ret != -ENOEXEC)
×
1493
                        ASSERT_OK(ret);
×
1494

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

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

1508
                if (build_dir_mount) {
×
1509
                        ret = RET_NERRNO(access(build_dir, F_OK));
×
1510
                        if (ret != -ENOENT)
×
1511
                                ASSERT_OK(ret);
×
1512

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

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

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

1530
        return r;
×
1531
}
1532

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1615
        if (enter_cgroup_subroot(NULL) == -ENOMEDIUM)
1✔
1616
                return log_tests_skipped("cgroupfs not available");
×
1617

1618
        if (path_is_read_only_fs("/sys") > 0)
1✔
1619
                return log_tests_skipped("/sys is mounted read-only");
1✔
1620

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

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

1630
        return EXIT_SUCCESS;
1631
}
1632

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

1639
        (void) rmdir(PRIVATE_UNIT_DIR);
1✔
1640

1641
        return EXIT_SUCCESS;
1✔
1642
}
1643

1644
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