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

systemd / systemd / 13912360373

17 Mar 2025 10:34PM UTC coverage: 71.946% (+0.03%) from 71.915%
13912360373

push

github

web-flow
nsresourced,vmspawn: allow unpriv "tap" based networking in vmspawn (#36688)

This extends nsresourced to also allow delegation of a network tap
device (in addition to veth) to unpriv clients, with a strictly enforced
naming scheme.

also tightens security on a couple of things:

* enforces polkit on all nsresourced ops too (though by default still
everything is allowed)
* put a limit on delegated network devices
* forcibly clean up delegated network devices when the userns goes away

145 of 375 new or added lines in 14 files covered. (38.67%)

2324 existing lines in 47 files now uncovered.

296268 of 411794 relevant lines covered (71.95%)

711485.52 hits per line

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

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

3
#include <linux/prctl.h>
4
#include <stdio.h>
5
#include <sys/mount.h>
6
#include <sys/prctl.h>
7
#include <sys/types.h>
8

9
#include "sd-event.h"
10

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

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

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

47
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
1✔
48

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

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

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

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

67
        abort();
×
68
}
69

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

74
        ASSERT_NOT_NULL(m);
×
75

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

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

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

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

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

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

99
        wait_for_service_finish(m, unit);
×
100

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

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

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

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

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

126
        wait_for_service_finish(m, unit);
×
127

128
        service = SERVICE(unit);
×
129

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

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

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

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

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

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

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

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

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

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

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

188
        ASSERT_NOT_NULL(name);
×
189

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

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

200
        return true;
201
}
202

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

214
        return true;
×
215
}
216

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

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

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

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

240
                return false;
×
241
        }
242

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

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

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

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

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

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

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

287
        return r == EXIT_SUCCESS;
×
288
}
289

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

294
        ASSERT_NOT_NULL(unit_name);
×
295

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

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

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

312
        ASSERT_NOT_NULL(unit_name);
×
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

416
        int r;
×
417

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

497
        (void) unlink("/tmp/test-exec_privatetmp");
×
498
}
×
499

500
static void test_exec_privatedevices(Manager *m) {
×
501
        int r;
×
502

503
        if (detect_container() > 0) {
×
504
                log_notice("Testing in container, skipping %s", __func__);
×
505
                return;
×
506
        }
507
        if (!is_inaccessible_available()) {
×
508
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
509
                return;
×
510
        }
511

512
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
513
                test(m, "exec-privatedevices-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
514
                if (access("/dev/kmsg", F_OK) >= 0)
×
515
                        test(m, "exec-privatedevices-bind.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
516
                test(m, "exec-privatedevices-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
517
                test(m, "exec-privatedevices-yes-with-group.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
518
        }
519

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

522
        /* We use capsh to test if the capabilities are
523
         * properly set, so be sure that it exists */
524
        r = find_executable("capsh", NULL);
×
525
        if (r < 0) {
×
526
                log_notice_errno(r, "Could not find capsh binary, skipping remaining tests in %s: %m", __func__);
×
527
                return;
×
528
        }
529

530
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
531
                test(m, "exec-privatedevices-yes-capability-mknod.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
532
                test(m, "exec-privatedevices-yes-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
533
        }
534

535
        test(m, "exec-privatedevices-no-capability-mknod.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
536
        test(m, "exec-privatedevices-no-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
537
}
538

539
static void test_exec_protecthome(Manager *m) {
×
540
        if (!can_unshare) {
×
541
                log_notice("Cannot reliably unshare, skipping %s", __func__);
×
542
                return;
×
543
        }
544

545
        test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
×
546
}
547

548
static void test_exec_protectkernelmodules(Manager *m) {
×
549
        int r;
×
550

551
        if (detect_container() > 0) {
×
552
                log_notice("Testing in container, skipping %s", __func__);
×
553
                return;
×
554
        }
555
        if (!is_inaccessible_available()) {
×
556
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
557
                return;
×
558
        }
559

560
        r = find_executable("capsh", NULL);
×
561
        if (r < 0) {
×
562
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
563
                return;
×
564
        }
565

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

568
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
569
                test(m, "exec-protectkernelmodules-yes-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
570
                test(m, "exec-protectkernelmodules-yes-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
571
        }
572
}
573

574
static void test_exec_readonlypaths(Manager *m) {
×
575

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

579
        if (path_is_read_only_fs("/var") > 0) {
×
580
                log_notice("Directory /var is readonly, skipping remaining tests in %s", __func__);
×
581
                return;
×
582
        }
583

584
        test(m, "exec-readonlypaths.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
585
        test(m, "exec-readonlypaths-with-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
586
        test(m, "exec-readonlypaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
587
}
588

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

591
        if (path_is_read_only_fs("/") > 0) {
×
592
                log_notice("Root directory is readonly, skipping %s", __func__);
×
593
                return;
×
594
        }
595

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

599
static void test_exec_inaccessiblepaths(Manager *m) {
×
600

601
        if (!is_inaccessible_available()) {
×
602
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
603
                return;
×
604
        }
605

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

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

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

617
#if !HAS_FEATURE_ADDRESS_SANITIZER
618
static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
×
619
        char **result = userdata;
×
620
        char buf[4096];
×
621
        ssize_t l;
×
622

623
        ASSERT_NOT_NULL(s);
×
624
        ASSERT_GT(fd, 0);
×
625

626
        l = read(fd, buf, sizeof(buf) - 1);
×
627
        if (l < 0) {
×
628
                if (errno == EAGAIN)
×
629
                        goto reenable;
×
630

631
                return 0;
×
632
        }
633
        if (l == 0)
×
634
                return 0;
635

636
        buf[l] = '\0';
×
637
        if (result)
×
638
                ASSERT_NOT_NULL(strextend(result, buf));
×
639
        else
640
                log_error("ldd: %s", buf);
×
641

642
reenable:
×
643
        /* Re-enable the event source if we did not encounter EOF */
644
        ASSERT_OK(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT));
×
645
        return 0;
646
}
647

648
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
×
649
        pid_t *pid = userdata;
×
650

651
        ASSERT_NOT_NULL(pid);
×
652

653
        (void) kill(*pid, SIGKILL);
×
654

655
        return 1;
×
656
}
657

658
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
×
659
        int ret = -EIO;
×
660

661
        ASSERT_NOT_NULL(si);
×
662

663
        if (si->si_code == CLD_EXITED)
×
664
                ret = si->si_status;
×
665

666
        sd_event_exit(sd_event_source_get_event(s), ret);
×
667
        return 1;
×
668
}
669

670
static int find_libraries(const char *exec, char ***ret) {
×
671
        _cleanup_(sd_event_unrefp) sd_event *e = NULL;
×
672
        _cleanup_(sd_event_source_unrefp) sd_event_source *sigchld_source = NULL;
×
673
        _cleanup_(sd_event_source_unrefp) sd_event_source *stdout_source = NULL;
×
674
        _cleanup_(sd_event_source_unrefp) sd_event_source *stderr_source = NULL;
×
675
        _cleanup_close_pair_ int outpipe[2] = EBADF_PAIR, errpipe[2] = EBADF_PAIR;
×
676
        _cleanup_strv_free_ char **libraries = NULL;
×
677
        _cleanup_free_ char *result = NULL;
×
678
        pid_t pid;
×
679
        int r;
×
680

681
        ASSERT_NOT_NULL(exec);
×
682
        ASSERT_NOT_NULL(ret);
×
683

684
        ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD));
×
685

686
        ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
×
687
        ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
×
688

689
        r = safe_fork_full("(spawn-ldd)",
×
690
                           (int[]) { -EBADF, outpipe[1], errpipe[1] },
×
691
                           NULL, 0,
692
                           FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_LOG, &pid);
693
        ASSERT_OK(r);
×
694
        if (r == 0) {
×
695
                execlp("ldd", "ldd", exec, NULL);
×
696
                _exit(EXIT_FAILURE);
×
697
        }
698

699
        outpipe[1] = safe_close(outpipe[1]);
×
700
        errpipe[1] = safe_close(errpipe[1]);
×
701

702
        ASSERT_OK(sd_event_new(&e));
×
703

704
        ASSERT_OK(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC,
×
705
                                             10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pid));
706
        ASSERT_OK(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result));
×
707
        ASSERT_OK(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT));
×
708
        ASSERT_OK(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL));
×
709
        ASSERT_OK(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT));
×
710
        ASSERT_OK(sd_event_add_child(e, &sigchld_source, pid, WEXITED, on_spawn_sigchld, NULL));
×
711
        /* SIGCHLD should be processed after IO is complete */
712
        ASSERT_OK(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1));
×
713

714
        ASSERT_OK(sd_event_loop(e));
×
715

716
        _cleanup_strv_free_ char **v = NULL;
×
717
        ASSERT_OK(strv_split_newlines_full(&v, result, 0));
×
718

719
        STRV_FOREACH(q, v) {
×
720
                _cleanup_free_ char *word = NULL;
×
721
                const char *p = *q;
×
722

723
                r = extract_first_word(&p, &word, NULL, 0);
×
724
                ASSERT_OK(r);
×
725
                if (r == 0)
×
726
                        continue;
×
727

728
                if (path_is_absolute(word)) {
×
729
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
×
730
                        continue;
×
731
                }
732

733
                word = mfree(word);
×
734
                r = extract_first_word(&p, &word, NULL, 0);
×
735
                ASSERT_OK(r);
×
736
                if (r == 0)
×
737
                        continue;
×
738

739
                if (!streq_ptr(word, "=>"))
×
740
                        continue;
×
741

742
                word = mfree(word);
×
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

754
        *ret = TAKE_PTR(libraries);
×
755
        return 0;
×
756
}
757
#endif
758

759
static void test_exec_mount_apivfs(Manager *m) {
×
760
#if !HAS_FEATURE_ADDRESS_SANITIZER
761
        _cleanup_free_ char *fullpath_touch = NULL, *fullpath_test = NULL, *data = NULL;
×
762
        _cleanup_strv_free_ char **libraries = NULL, **libraries_test = NULL;
×
763
        int r;
×
764

765
        ASSERT_NOT_NULL(user_runtime_unit_dir);
×
766

767
        r = find_executable("ldd", NULL);
×
768
        if (r < 0) {
×
769
                log_notice_errno(r, "Skipping %s, could not find 'ldd' command: %m", __func__);
×
770
                return;
×
771
        }
772
        r = find_executable("touch", &fullpath_touch);
×
773
        if (r < 0) {
×
774
                log_notice_errno(r, "Skipping %s, could not find 'touch' command: %m", __func__);
×
775
                return;
×
776
        }
777
        r = find_executable("test", &fullpath_test);
×
778
        if (r < 0) {
×
779
                log_notice_errno(r, "Skipping %s, could not find 'test' command: %m", __func__);
×
780
                return;
×
781
        }
782

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

786
        ASSERT_OK(find_libraries(fullpath_touch, &libraries));
×
787
        ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
×
788
        ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
×
789

790
        ASSERT_NOT_NULL(strextend(&data, "[Service]\n"));
×
791
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")));
×
792
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")));
×
793
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")));
×
794
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")));
×
795

796
        STRV_FOREACH(p, libraries)
×
797
                ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
×
798

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

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

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

805
        (void) rm_rf("/tmp/test-exec-mount-apivfs-no/root", REMOVE_ROOT|REMOVE_PHYSICAL);
×
806
#endif
807
}
808

809
static void test_exec_noexecpaths(Manager *m) {
×
810

811
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
812
                test(m, "exec-noexecpaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
813
        else
814
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
815
}
816

817
static void test_exec_temporaryfilesystem(Manager *m) {
×
818

819
        test(m, "exec-temporaryfilesystem-options.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
820
        test(m, "exec-temporaryfilesystem-ro.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
821
        test(m, "exec-temporaryfilesystem-rw.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
822
        test(m, "exec-temporaryfilesystem-usr.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
823
}
×
824

825
static void test_exec_systemcallfilter(Manager *m) {
×
826
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
827
        int r;
×
828

829
        if (!is_seccomp_available()) {
×
830
                log_notice("Seccomp not available, skipping %s", __func__);
×
831
                return;
×
832
        }
833

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

836
        test(m, "exec-systemcallfilter-not-failing.service", 0, CLD_EXITED);
×
837
        test(m, "exec-systemcallfilter-not-failing2.service", 0, CLD_EXITED);
×
838
        test(m, "exec-systemcallfilter-not-failing3.service", 0, CLD_EXITED);
×
839
        test(m, "exec-systemcallfilter-failing.service", SIGSYS, CLD_KILLED);
×
840
        test(m, "exec-systemcallfilter-failing2.service", SIGSYS, CLD_KILLED);
×
841
        test(m, "exec-systemcallfilter-failing3.service", SIGSYS, CLD_KILLED);
×
842

843
        r = find_executable("python3", NULL);
×
844
        if (r < 0) {
×
845
                log_notice_errno(r, "Skipping remaining tests in %s, could not find python3 binary: %m", __func__);
×
846
                return;
×
847
        }
848

849
        test(m, "exec-systemcallfilter-with-errno-name.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
850
        test(m, "exec-systemcallfilter-with-errno-number.service", 255, CLD_EXITED);
×
851
        test(m, "exec-systemcallfilter-with-errno-multi.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
852
        test(m, "exec-systemcallfilter-with-errno-in-allow-list.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
853
        test(m, "exec-systemcallfilter-override-error-action.service", SIGSYS, CLD_KILLED);
×
854
        test(m, "exec-systemcallfilter-override-error-action2.service", errno_from_name("EILSEQ"), CLD_EXITED);
×
855

856
        test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
857
        test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
858

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

865
        test(m, "exec-systemcallfilter-nonewprivileges-bounding1.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
866
        test(m, "exec-systemcallfilter-nonewprivileges-bounding2.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
867
#endif
868
}
869

870
static void test_exec_systemcallerrornumber(Manager *m) {
×
871
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
872
        int r;
×
873

874
        if (!is_seccomp_available()) {
×
875
                log_notice("Seccomp not available, skipping %s", __func__);
×
876
                return;
×
877
        }
878

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

885
        test(m, "exec-systemcallerrornumber-name.service", errno_from_name("EACCES"), CLD_EXITED);
×
886
        test(m, "exec-systemcallerrornumber-number.service", 255, CLD_EXITED);
×
887
#endif
888
}
889

890
static void test_exec_restrictnamespaces(Manager *m) {
×
891
#if HAVE_SECCOMP
892
        if (!is_seccomp_available()) {
×
893
                log_notice("Seccomp not available, skipping %s", __func__);
×
894
                return;
×
895
        }
896

897
        test(m, "exec-restrictnamespaces-no.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
898
        test(m, "exec-restrictnamespaces-yes.service", 1, CLD_EXITED);
×
899
        test(m, "exec-restrictnamespaces-mnt.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
900
        test(m, "exec-restrictnamespaces-mnt-deny-list.service", 1, CLD_EXITED);
×
901
        test(m, "exec-restrictnamespaces-merge-and.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
902
        test(m, "exec-restrictnamespaces-merge-or.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
903
        test(m, "exec-restrictnamespaces-merge-all.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
×
904
#endif
905
}
906

907
static void test_exec_systemcallfilter_system(Manager *m) {
×
908
/* Skip this particular test case when running under ASan, as
909
 * LSan intermittently segfaults when accessing memory right
910
 * after the test finishes. Generally, ASan & LSan don't like
911
 * the seccomp stuff.
912
 */
913
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
914
        if (!is_seccomp_available()) {
×
915
                log_notice("Seccomp not available, skipping %s", __func__);
×
916
                return;
×
917
        }
918

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

921
        if (!check_nobody_user_and_group()) {
×
922
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
923
                return;
×
924
        }
925

926
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
927
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
928
                return;
×
929
        }
930

931
        test(m, "exec-systemcallfilter-system-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
932
#endif
933
}
934

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

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

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

948
        test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
949
}
950

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

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

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

964
        test(m, "exec-group-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
965
}
966

967
static void test_exec_supplementarygroups(Manager *m) {
×
968
        int status = MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP;
×
969
        test(m, "exec-supplementarygroups.service", status, CLD_EXITED);
×
970
        test(m, "exec-supplementarygroups-single-group.service", status, CLD_EXITED);
×
971
        test(m, "exec-supplementarygroups-single-group-user.service", status, CLD_EXITED);
×
972
        test(m, "exec-supplementarygroups-multiple-groups-default-group-user.service", status, CLD_EXITED);
×
973
        test(m, "exec-supplementarygroups-multiple-groups-withgid.service", status, CLD_EXITED);
×
974
        test(m, "exec-supplementarygroups-multiple-groups-withuid.service", status, CLD_EXITED);
×
975
}
×
976

977
static char* private_directory_bad(Manager *m) {
×
978
        /* This mirrors setup_exec_directory(). */
979

980
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
×
981
                _cleanup_free_ char *p = NULL;
×
982
                struct stat st;
×
983

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

986
                if (stat(p, &st) >= 0 &&
×
987
                    (st.st_mode & (S_IRWXG|S_IRWXO)))
×
988
                        return TAKE_PTR(p);
×
989
        }
990

991
        return NULL;
992
}
993

994
static void test_exec_dynamicuser(Manager *m) {
×
995
        if (MANAGER_IS_USER(m)) {
×
996
                log_notice("Skipping %s for user manager", __func__);
×
997
                return;
×
998
        }
999

1000
        _cleanup_free_ char *bad = private_directory_bad(m);
×
1001
        if (bad) {
×
1002
                log_warning("%s: %s has bad permissions, skipping test.", __func__, bad);
×
1003
                return;
×
1004
        }
1005

1006
        if (strstr_ptr(ci_environment(), "github-actions")) {
×
1007
                log_notice("%s: skipping test on GH Actions because of systemd/systemd#10337", __func__);
×
1008
                return;
×
1009
        }
1010

1011
        int status = can_unshare ? 0 : EXIT_NAMESPACE;
×
1012

1013
        test(m, "exec-dynamicuser-fixeduser.service", status, CLD_EXITED);
×
1014
        if (check_user_has_group_with_same_name("adm"))
×
1015
                test(m, "exec-dynamicuser-fixeduser-adm.service", status, CLD_EXITED);
×
1016
        if (check_user_has_group_with_same_name("games"))
×
1017
                test(m, "exec-dynamicuser-fixeduser-games.service", status, CLD_EXITED);
×
1018
        test(m, "exec-dynamicuser-fixeduser-one-supplementarygroup.service", status, CLD_EXITED);
×
1019
        test(m, "exec-dynamicuser-supplementarygroups.service", status, CLD_EXITED);
×
1020
        test(m, "exec-dynamicuser-statedir.service", status, CLD_EXITED);
×
1021

1022
        (void) rm_rf("/var/lib/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1023
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1024
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1025
        (void) rm_rf("/var/lib/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1026
        (void) rm_rf("/var/lib/private/quux", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1027
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1028
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1029
        (void) rm_rf("/var/lib/private/waldo", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1030

1031
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1032
        test(m, "exec-dynamicuser-statedir-migrate-step2.service", status, CLD_EXITED);
×
1033
        test(m, "exec-dynamicuser-statedir-migrate-step1.service", 0, CLD_EXITED);
×
1034

1035
        (void) rm_rf("/var/lib/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1036
        (void) rm_rf("/var/lib/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1037
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1038
        (void) rm_rf("/var/lib/private/test-dynamicuser-migrate2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1039

1040
        test(m, "exec-dynamicuser-runtimedirectory1.service", status, CLD_EXITED);
×
1041
        test(m, "exec-dynamicuser-runtimedirectory2.service", status, CLD_EXITED);
×
1042
        test(m, "exec-dynamicuser-runtimedirectory3.service", status, CLD_EXITED);
×
1043
}
1044

1045
static void test_exec_environment(Manager *m) {
×
1046
        test(m, "exec-environment-no-substitute.service", 0, CLD_EXITED);
×
1047
        test(m, "exec-environment.service", 0, CLD_EXITED);
×
1048
        test(m, "exec-environment-multiple.service", 0, CLD_EXITED);
×
1049
        test(m, "exec-environment-empty.service", 0, CLD_EXITED);
×
1050
}
×
1051

1052
static void test_exec_environmentfile(Manager *m) {
×
1053
        static const char e[] =
×
1054
                "VAR1='word1 word2'\n"
1055
                "VAR2=word3 \n"
1056
                "# comment1\n"
1057
                "\n"
1058
                "; comment2\n"
1059
                " ; # comment3\n"
1060
                "line without an equal\n"
1061
                "VAR3='$word 5 6'\n"
1062
                "VAR4='new\nline'\n"
1063
                "VAR5=password\\with\\backslashes";
1064
        int r;
×
1065

1066
        r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE);
×
1067
        ASSERT_OK(r);
×
1068

1069
        test(m, "exec-environmentfile.service", 0, CLD_EXITED);
×
1070

1071
        (void) unlink("/tmp/test-exec_environmentfile.conf");
×
1072
}
×
1073

1074
static void test_exec_passenvironment(Manager *m) {
×
1075
        /* test-execute runs under MANAGER_USER which, by default, forwards all
1076
         * variables present in the environment, but only those that are
1077
         * present _at the time it is created_!
1078
         *
1079
         * So these PassEnvironment checks are still expected to work, since we
1080
         * are ensuring the variables are not present at manager creation (they
1081
         * are unset explicitly in main) and are only set here.
1082
         *
1083
         * This is still a good approximation of how a test for MANAGER_SYSTEM
1084
         * would work.
1085
         */
1086
        ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
×
1087
        ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
×
1088
        ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
×
1089
        ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
×
1090
        ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
×
1091
        test(m, "exec-passenvironment.service", 0, CLD_EXITED);
×
1092
        test(m, "exec-passenvironment-repeated.service", 0, CLD_EXITED);
×
1093
        test(m, "exec-passenvironment-empty.service", 0, CLD_EXITED);
×
1094
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
1095
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
1096
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
1097
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
1098
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
1099
        test(m, "exec-passenvironment-absent.service", 0, CLD_EXITED);
×
1100
}
×
1101

1102
static void test_exec_umask(Manager *m) {
×
1103
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
×
1104
                test(m, "exec-umask-default.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1105
                test(m, "exec-umask-0177.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1106
        } else
1107
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1108
}
1109

1110
static void test_exec_runtimedirectory(Manager *m) {
×
1111
        (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1112
        test(m, "exec-runtimedirectory.service", 0, CLD_EXITED);
×
1113
        (void) rm_rf("/run/test-exec_runtimedirectory2", REMOVE_ROOT|REMOVE_PHYSICAL);
×
1114

1115
        test(m, "exec-runtimedirectory-mode.service", 0, CLD_EXITED);
×
1116
        test(m, "exec-runtimedirectory-owner.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1117

1118
        if (!check_nobody_user_and_group()) {
×
1119
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
1120
                return;
×
1121
        }
1122

1123
        if (!STR_IN_SET(NOBODY_GROUP_NAME, "nobody", "nfsnobody", "nogroup")) {
×
1124
                log_notice("Unsupported nobody group name '%s', skipping remaining tests in %s", NOBODY_GROUP_NAME, __func__);
×
1125
                return;
×
1126
        }
1127

1128
        test(m, "exec-runtimedirectory-owner-" NOBODY_GROUP_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
×
1129
}
1130

1131
static void test_exec_capabilityboundingset(Manager *m) {
×
1132
        int r;
×
1133

1134
        r = find_executable("capsh", NULL);
×
1135
        if (r < 0) {
×
1136
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
×
1137
                return;
×
1138
        }
1139

1140
        if (have_effective_cap(CAP_CHOWN) <= 0 ||
×
1141
            have_effective_cap(CAP_FOWNER) <= 0 ||
×
1142
            have_effective_cap(CAP_KILL) <= 0) {
×
1143
                log_notice("Skipping %s, this process does not have enough capabilities", __func__);
×
1144
                return;
×
1145
        }
1146

1147
        test(m, "exec-capabilityboundingset-simple.service", 0, CLD_EXITED);
×
1148
        test(m, "exec-capabilityboundingset-reset.service", 0, CLD_EXITED);
×
1149
        test(m, "exec-capabilityboundingset-merge.service", 0, CLD_EXITED);
×
1150
        test(m, "exec-capabilityboundingset-invert.service", 0, CLD_EXITED);
×
1151
}
1152

1153
static void test_exec_basic(Manager *m) {
×
1154
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
×
1155
                test(m, "exec-basic.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
×
1156
        else
1157
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
×
1158
}
1159

1160
static void test_exec_ambientcapabilities(Manager *m) {
×
1161
        int r;
×
1162

1163
        /* Check if the kernel has support for ambient capabilities. Run
1164
         * the tests only if that's the case. Clearing all ambient
1165
         * capabilities is fine, since we are expecting them to be unset
1166
         * in the first place for the tests. */
1167
        r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0);
×
1168
        if (r < 0 && IN_SET(errno, EINVAL, EOPNOTSUPP, ENOSYS)) {
×
1169
                log_notice("Skipping %s, the kernel does not support ambient capabilities", __func__);
×
1170
                return;
×
1171
        }
1172

1173
        if (have_effective_cap(CAP_CHOWN) <= 0 ||
×
1174
            have_effective_cap(CAP_NET_RAW) <= 0) {
×
1175
                log_notice("Skipping %s, this process does not have enough capabilities", __func__);
×
1176
                return;
×
1177
        }
1178

1179
        test(m, "exec-ambientcapabilities.service", 0, CLD_EXITED);
×
1180
        test(m, "exec-ambientcapabilities-merge.service", 0, CLD_EXITED);
×
1181

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

1185
        if (!check_nobody_user_and_group()) {
×
1186
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
×
1187
                return;
×
1188
        }
1189

1190
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
×
1191
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
×
1192
                return;
×
1193
        }
1194

1195
        test(m, "exec-ambientcapabilities-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1196
        test(m, "exec-ambientcapabilities-merge-" NOBODY_USER_NAME ".service", 0, CLD_EXITED);
×
1197
}
1198

1199
static void test_exec_privatenetwork(Manager *m) {
×
1200
        int r;
×
1201

1202
        if (!have_net_dummy)
×
1203
                return (void)log_notice("Skipping %s, dummy network interface not available", __func__);
×
1204

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

1208
        r = find_executable("ip", NULL);
×
1209
        if (r < 0) {
×
1210
                log_notice_errno(r, "Skipping %s, could not find ip binary: %m", __func__);
×
1211
                return;
×
1212
        }
1213

1214
        test(m, "exec-privatenetwork-yes-privatemounts-no.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_FAILURE, CLD_EXITED);
×
1215
        test(m, "exec-privatenetwork-yes-privatemounts-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NETWORK : EXIT_NAMESPACE, CLD_EXITED);
×
1216
}
1217

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

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

1224
        if (!have_netns)
×
1225
                return (void)log_notice("Skipping %s, network namespace not available", __func__);
×
1226

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

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

1236
        test(m, "exec-networknamespacepath-privatemounts-no.service", MANAGER_IS_SYSTEM(m) ? EXIT_SUCCESS : EXIT_FAILURE, CLD_EXITED);
×
1237
        test(m, "exec-networknamespacepath-privatemounts-yes.service", can_unshare ? EXIT_SUCCESS : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
×
1238
}
1239

1240
static void test_exec_oomscoreadjust(Manager *m) {
×
1241
        test(m, "exec-oomscoreadjust-positive.service", 0, CLD_EXITED);
×
1242

1243
        if (detect_container() > 0) {
×
1244
                log_notice("Testing in container, skipping remaining tests in %s", __func__);
×
1245
                return;
×
1246
        }
1247
        test(m, "exec-oomscoreadjust-negative.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
×
1248
}
1249

1250
static void test_exec_ioschedulingclass(Manager *m) {
×
1251
        test(m, "exec-ioschedulingclass-none.service", 0, CLD_EXITED);
×
1252
        test(m, "exec-ioschedulingclass-idle.service", 0, CLD_EXITED);
×
1253
        test(m, "exec-ioschedulingclass-best-effort.service", 0, CLD_EXITED);
×
1254

1255
        if (detect_container() > 0) {
×
1256
                log_notice("Testing in container, skipping remaining tests in %s", __func__);
×
1257
                return;
×
1258
        }
1259
        test(m, "exec-ioschedulingclass-realtime.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_IOPRIO, CLD_EXITED);
×
1260
}
1261

1262
static void test_exec_unsetenvironment(Manager *m) {
×
1263
        test(m, "exec-unsetenvironment.service", 0, CLD_EXITED);
×
1264
}
×
1265

1266
static void test_exec_specifier(Manager *m) {
×
1267
        test(m, "exec-specifier.service", 0, CLD_EXITED);
×
1268
        if (MANAGER_IS_SYSTEM(m))
×
1269
                test(m, "exec-specifier-system.service", 0, CLD_EXITED);
×
1270
        else
1271
                test(m, "exec-specifier-user.service", 0, CLD_EXITED);
×
1272
        test(m, "exec-specifier@foo-bar.service", 0, CLD_EXITED);
×
1273
        test(m, "exec-specifier-interpolation.service", 0, CLD_EXITED);
×
1274
}
×
1275

1276
static void test_exec_standardinput(Manager *m) {
×
1277
        test(m, "exec-standardinput-data.service", 0, CLD_EXITED);
×
1278
        test(m, "exec-standardinput-file.service", 0, CLD_EXITED);
×
1279

1280
        ExecOutput saved = m->defaults.std_output;
×
1281
        m->defaults.std_output = EXEC_OUTPUT_NULL;
×
1282
        test(m, "exec-standardinput-file-cat.service", 0, CLD_EXITED);
×
1283
        m->defaults.std_output = saved;
×
1284
}
×
1285

1286
static void test_exec_standardoutput(Manager *m) {
×
1287
        test(m, "exec-standardoutput-file.service", 0, CLD_EXITED);
×
1288
}
×
1289

1290
static void test_exec_standardoutput_append(Manager *m) {
×
1291
        test(m, "exec-standardoutput-append.service", 0, CLD_EXITED);
×
1292
}
×
1293

1294
static void test_exec_standardoutput_truncate(Manager *m) {
×
1295
        test(m, "exec-standardoutput-truncate.service", 0, CLD_EXITED);
×
1296
}
×
1297

1298
static void test_exec_condition(Manager *m) {
×
1299
        test_service(m, "exec-condition-failed.service", SERVICE_FAILURE_EXIT_CODE);
×
1300
        test_service(m, "exec-condition-skip.service", SERVICE_SKIP_CONDITION);
×
1301
}
×
1302

1303
static void test_exec_umask_namespace(Manager *m) {
×
1304
        /* exec-specifier-credentials-dir.service creates /run/credentials and enables implicit
1305
         * InaccessiblePath= for the directory for all later services with mount namespace. */
1306
        if (!is_inaccessible_available()) {
×
1307
                log_notice("Testing without inaccessible, skipping %s", __func__);
×
1308
                return;
×
1309
        }
1310
        test(m, "exec-umask-namespace.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NAMESPACE : EXIT_GROUP, CLD_EXITED);
×
1311
}
1312

1313
typedef struct test_entry {
1314
        test_function_t f;
1315
        const char *name;
1316
} test_entry;
1317

1318
#define entry(x) {x, #x}
1319

1320
static void run_tests(RuntimeScope scope, char **patterns) {
×
1321
        _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL;
×
1322
        _cleanup_free_ char *unit_paths = NULL;
×
1323
        _cleanup_(manager_freep) Manager *m = NULL;
×
1324
        usec_t start, finish;
×
1325
        int r;
×
1326

1327
        static const test_entry tests[] = {
×
1328
                entry(test_exec_basic),
1329
                entry(test_exec_ambientcapabilities),
1330
                entry(test_exec_bindpaths),
1331
                entry(test_exec_capabilityboundingset),
1332
                entry(test_exec_condition),
1333
                entry(test_exec_cpuaffinity),
1334
                entry(test_exec_credentials),
1335
                entry(test_exec_dynamicuser),
1336
                entry(test_exec_environment),
1337
                entry(test_exec_environmentfile),
1338
                entry(test_exec_execsearchpath),
1339
                entry(test_exec_execsearchpath_environment),
1340
                entry(test_exec_execsearchpath_environment_files),
1341
                entry(test_exec_execsearchpath_passenvironment),
1342
                entry(test_exec_execsearchpath_specifier),
1343
                entry(test_exec_group),
1344
                entry(test_exec_ignoresigpipe),
1345
                entry(test_exec_inaccessiblepaths),
1346
                entry(test_exec_ioschedulingclass),
1347
                entry(test_exec_mount_apivfs),
1348
                entry(test_exec_networknamespacepath),
1349
                entry(test_exec_noexecpaths),
1350
                entry(test_exec_oomscoreadjust),
1351
                entry(test_exec_passenvironment),
1352
                entry(test_exec_personality),
1353
                entry(test_exec_privatedevices),
1354
                entry(test_exec_privatenetwork),
1355
                entry(test_exec_privatetmp),
1356
                entry(test_exec_protecthome),
1357
                entry(test_exec_protectkernelmodules),
1358
                entry(test_exec_readonlypaths),
1359
                entry(test_exec_readwritepaths),
1360
                entry(test_exec_restrictnamespaces),
1361
                entry(test_exec_runtimedirectory),
1362
                entry(test_exec_specifier),
1363
                entry(test_exec_standardinput),
1364
                entry(test_exec_standardoutput),
1365
                entry(test_exec_standardoutput_append),
1366
                entry(test_exec_standardoutput_truncate),
1367
                entry(test_exec_supplementarygroups),
1368
                entry(test_exec_systemcallerrornumber),
1369
                entry(test_exec_systemcallfilter),
1370
                entry(test_exec_systemcallfilter_system),
1371
                entry(test_exec_temporaryfilesystem),
1372
                entry(test_exec_umask),
1373
                entry(test_exec_umask_namespace),
1374
                entry(test_exec_unsetenvironment),
1375
                entry(test_exec_user),
1376
                entry(test_exec_workingdirectory),
1377
                {},
1378
        };
1379

1380
        ASSERT_OK_ERRNO(unsetenv("USER"));
×
1381
        ASSERT_OK_ERRNO(unsetenv("LOGNAME"));
×
1382
        ASSERT_OK_ERRNO(unsetenv("SHELL"));
×
1383
        ASSERT_OK_ERRNO(unsetenv("HOME"));
×
1384
        ASSERT_OK_ERRNO(unsetenv("TMPDIR"));
×
1385

1386
        /* Unset VARx, especially, VAR1, VAR2 and VAR3, which are used in the PassEnvironment test cases,
1387
         * otherwise (and if they are present in the environment), `manager_default_environment` will copy
1388
         * them into the default environment which is passed to each created job, which will make the tests
1389
         * that expect those not to be present to fail. */
1390
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
×
1391
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
×
1392
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
×
1393
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
×
1394
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
×
1395

1396
        ASSERT_NOT_NULL((runtime_dir = setup_fake_runtime_dir()));
×
1397
        ASSERT_NOT_NULL((user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")));
×
1398
        ASSERT_NOT_NULL((unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)));
×
1399
        ASSERT_OK(setenv_unit_path(unit_paths));
×
1400

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

1405
        r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m);
×
1406
        if (manager_errno_skip_test(r))
×
1407
                return (void) log_tests_skipped_errno(r, "manager_new");
×
1408
        ASSERT_OK(r);
×
1409

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

1413
        /* Uncomment below if you want to make debugging logs stored to journal. */
1414
        //manager_override_log_target(m, LOG_TARGET_AUTO);
1415
        //manager_override_log_level(m, LOG_DEBUG);
1416

1417
        /* Measure and print the time that it takes to run tests, excluding startup of the manager object,
1418
         * to try and measure latency of spawning services */
1419
        n_ran_tests = 0;
×
1420
        start = now(CLOCK_MONOTONIC);
×
1421

1422
        for (const test_entry *test = tests; test->f; test++)
×
1423
                if (strv_fnmatch_or_empty(patterns, test->name, FNM_NOESCAPE)) {
×
1424
                        log_info("Starting %s.", test->name);
×
1425
                        test->f(m);
×
1426
                } else
1427
                        log_info("Skipping %s because it does not match any pattern.", test->name);
×
1428

1429
        finish = now(CLOCK_MONOTONIC);
×
1430

1431
        log_info("ran %u tests with %s manager + unshare=%s in: %s",
×
1432
                 n_ran_tests,
1433
                 scope == RUNTIME_SCOPE_SYSTEM ? "system" : "user",
1434
                 yes_no(can_unshare),
1435
                 FORMAT_TIMESPAN(finish - start, USEC_PER_MSEC));
1436
}
1437

1438
static int prepare_ns(const char *process_name) {
×
1439
        int r;
×
1440

1441
        r = safe_fork(process_name,
×
1442
                      FORK_RESET_SIGNALS |
1443
                      FORK_CLOSE_ALL_FDS |
1444
                      FORK_DEATHSIG_SIGTERM |
1445
                      FORK_WAIT |
1446
                      FORK_REOPEN_LOG |
1447
                      FORK_LOG |
1448
                      FORK_NEW_MOUNTNS |
1449
                      FORK_MOUNTNS_SLAVE,
1450
                      NULL);
1451
        ASSERT_OK(r);
×
1452
        if (r == 0) {
×
1453
                _cleanup_free_ char *unit_dir = NULL, *build_dir = NULL, *build_dir_mount = NULL;
×
1454
                int ret;
×
1455

1456
                const char *coverage = getenv("COVERAGE_BUILD_DIR");
×
1457
                if (!coverage)
×
1458
                        /* Make "/" read-only. */
1459
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL));
×
1460

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

1466
                ASSERT_OK(mkdir_p(PRIVATE_UNIT_DIR, 0755));
×
1467
                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", PRIVATE_UNIT_DIR, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1468
                /* Mark our test "playground" as MS_SLAVE, so we can MS_MOVE mounts underneath it. */
1469
                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, PRIVATE_UNIT_DIR, NULL, MS_SLAVE, NULL));
×
1470

1471
                /* Copy unit files to make them accessible even when unprivileged. */
1472
                ASSERT_OK(get_testdata_dir("test-execute/", &unit_dir));
×
1473
                ASSERT_OK(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY));
×
1474

1475
                /* Mount tmpfs on the following directories to make not StateDirectory= or friends disturb the host. */
1476
                ret = get_build_exec_dir(&build_dir);
×
1477
                if (ret != -ENOEXEC)
×
1478
                        ASSERT_OK(ret);
×
1479

1480
                if (build_dir) {
×
1481
                        /* Account for a build directory being in one of the soon-to-be-tmpfs directories. If we
1482
                         * overmount it with an empty tmpfs, manager_new() will pin the wrong systemd-executor binary,
1483
                         * which can then lead to unexpected (and painful to debug) test fails. */
1484
                        ASSERT_OK_ERRNO(access(build_dir, F_OK));
×
1485
                        ASSERT_NOT_NULL((build_dir_mount = path_join(PRIVATE_UNIT_DIR, "build_dir")));
×
1486
                        ASSERT_OK(mkdir_p(build_dir_mount, 0755));
×
1487
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir, build_dir_mount, NULL, MS_BIND, NULL));
×
1488
                }
1489

1490
                FOREACH_STRING(p, "/dev/shm", "/root", "/tmp", "/var/tmp", "/var/lib")
×
1491
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL));
×
1492

1493
                if (build_dir_mount) {
×
1494
                        ret = RET_NERRNO(access(build_dir, F_OK));
×
1495
                        if (ret != -ENOENT)
×
1496
                                ASSERT_OK(ret);
×
1497

1498
                        if (ret == -ENOENT) {
×
1499
                                /* The build directory got overmounted by tmpfs, so let's use the "backup" bind mount to
1500
                                 * bring it back. */
1501
                                ASSERT_OK(mkdir_p(build_dir, 0755));
×
1502
                                ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir_mount, build_dir, NULL, MS_MOVE, NULL));
×
1503
                        }
1504
                }
1505

1506
                /* Prepare credstore like tmpfiles.d/credstore.conf for LoadCredential= tests. */
1507
                FOREACH_STRING(p, "/run/credstore", "/run/credstore.encrypted") {
×
1508
                        ASSERT_OK(mkdir_p(p, 0700));
×
1509
                        ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0700"));
×
1510
                }
1511

1512
                ASSERT_OK(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE));
×
1513
        }
1514

1515
        return r;
×
1516
}
1517

1518
TEST(run_tests_root) {
×
1519
        _cleanup_strv_free_ char **filters = NULL;
×
1520

1521
        if (!have_namespaces())
×
1522
                return (void) log_tests_skipped("unshare() is disabled");
×
1523

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

1527
        if (prepare_ns("(test-execute-root)") == 0) {
×
1528
                can_unshare = true;
×
1529
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1530
                _exit(EXIT_SUCCESS);
×
1531
        }
1532
}
1533

1534
TEST(run_tests_without_unshare) {
×
1535
        if (!have_namespaces()) {
×
1536
                /* unshare() is already filtered. */
1537
                can_unshare = false;
×
1538
                run_tests(RUNTIME_SCOPE_SYSTEM, strv_skip(saved_argv, 1));
×
1539
                return;
×
1540
        }
1541

1542
#if HAVE_SECCOMP
1543
        _cleanup_strv_free_ char **filters = NULL;
×
1544
        int r;
×
1545

1546
        /* The following tests are for 1beab8b0d0ff2d7d1436b52d4a0c3d56dc908962. */
1547
        if (!is_seccomp_available())
×
1548
                return (void) log_tests_skipped("Seccomp not available, cannot run unshare() filtered tests");
×
1549

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

1553
        if (prepare_ns("(test-execute-without-unshare)") == 0) {
×
1554
                _cleanup_hashmap_free_ Hashmap *s = NULL;
×
1555

1556
                r = seccomp_syscall_resolve_name("unshare");
×
1557
                ASSERT_NE(r, __NR_SCMP_ERROR);
×
1558
                ASSERT_OK(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1)));
×
1559
                ASSERT_OK(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true));
×
1560

1561
                /* Check unshare() is actually filtered. */
1562
                ASSERT_ERROR_ERRNO(unshare(CLONE_NEWNS), EOPNOTSUPP);
×
1563

1564
                can_unshare = false;
×
1565
                run_tests(RUNTIME_SCOPE_SYSTEM, filters);
×
1566
                _exit(EXIT_SUCCESS);
×
1567
        }
1568
#else
1569
        log_tests_skipped("Built without seccomp support, cannot run unshare() filtered tests");
1570
#endif
1571
}
1572

1573
TEST(run_tests_unprivileged) {
×
1574
        _cleanup_strv_free_ char **filters = NULL;
×
1575

1576
        if (!have_namespaces())
×
1577
                return (void) log_tests_skipped("unshare() is disabled");
×
1578

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

1582
        if (prepare_ns("(test-execute-unprivileged)") == 0) {
×
1583
                ASSERT_OK(capability_bounding_set_drop(0, /* right_now = */ true));
×
1584

1585
                can_unshare = false;
×
1586
                run_tests(RUNTIME_SCOPE_USER, filters);
×
1587
                _exit(EXIT_SUCCESS);
×
1588
        }
1589
}
1590

1591
static int intro(void) {
1✔
1592
#if HAS_FEATURE_ADDRESS_SANITIZER
1593
        if (strstr_ptr(ci_environment(), "travis") || strstr_ptr(ci_environment(), "github-actions"))
1594
                return log_tests_skipped("Running on Travis CI/GH Actions under ASan, see https://github.com/systemd/systemd/issues/10696");
1595
#endif
1596
        /* It is needed otherwise cgroup creation fails */
1597
        if (geteuid() != 0 || have_effective_cap(CAP_SYS_ADMIN) <= 0)
1✔
1598
                return log_tests_skipped("not privileged");
×
1599

1600
        if (enter_cgroup_subroot(NULL) == -ENOMEDIUM)
1✔
1601
                return log_tests_skipped("cgroupfs not available");
×
1602

1603
        if (path_is_read_only_fs("/sys") > 0)
1✔
1604
                return log_tests_skipped("/sys is mounted read-only");
1✔
1605

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

1609
        if (have_net_dummy) {
×
1610
                /* Create a network namespace and a dummy interface in it for NetworkNamespacePath= */
1611
                have_netns = system("ip netns add test-execute-netns") == 0;
×
1612
                have_netns = have_netns && system("ip netns exec test-execute-netns ip link add dummy-test-ns type dummy") == 0;
×
1613
        }
1614

1615
        return EXIT_SUCCESS;
1616
}
1617

1618
static int outro(void) {
1✔
1619
        if (have_net_dummy) {
1✔
1620
                (void) system("ip link del dummy-test-exec");
×
1621
                (void) system("ip netns del test-execute-netns");
×
1622
        }
1623

1624
        (void) rmdir(PRIVATE_UNIT_DIR);
1✔
1625

1626
        return EXIT_SUCCESS;
1✔
1627
}
1628

1629
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