HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/test/test-execute.c

71,508 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 4cf15a7f53f720ec3eb6e7317471d666f33d12b8

Lines 1–1000 of 1,683

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fnmatch.h>
#include <gnu/libc-version.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/prctl.h> /* IWYU pragma: keep */
#include <unistd.h>
 
#include "sd-event.h"
 
#include "argv-util.h"
#include "build-path.h"
#include "capability-util.h"
#include "copy.h"
#include "cpu-set-util.h"
#include "dropin.h"
#include "errno-list.h"
#include "event-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "libmount-util.h"
#include "manager.h"
#include "mkdir.h"
#include "mount-util.h"
#include "path-util.h"
#include "process-util.h"
#include "rm-rf.h"
#include "seccomp-util.h"
#include "service.h"
#include "signal-util.h"
#include "stat-util.h"
#include "static-destruct.h"
#include "strv.h"
#include "sysctl-util.h"
#include "tests.h"
#include "unit.h"
#include "user-util.h"
#include "virt.h"
 
#define PRIVATE_UNIT_DIR "/run/test-execute-unit-dir"
 
static char *user_runtime_unit_dir = NULL;
static bool can_unshare;
static bool have_net_dummy;
static bool have_netns;
static unsigned n_ran_tests = 0;
 
STATIC_DESTRUCTOR_REGISTER(user_runtime_unit_dir, freep);
 
typedef void (*test_function_t)(Manager *m);
 
static int cld_dumped_to_killed(int code) {
        /* Depending on the system, seccomp version, … some signals might result in dumping, others in plain
         * killing. Let's ignore the difference here, and map both cases to CLD_KILLED */
        return code == CLD_DUMPED ? CLD_KILLED : code;
}
 
_noreturn_
static int time_handler(sd_event_source *s, uint64_t usec, void *userdata) {
        Unit *unit = ASSERT_PTR(userdata);
        int r;
 
        log_error("Test timeout when testing %s", unit->id);
        r = unit_kill(unit, KILL_ALL, /* subgroup= */ NULL, SIGKILL, SI_USER, /* value= */ 0, /* ret_error= */ NULL);
        if (r < 0)
                log_error_errno(r, "Failed to kill %s, ignoring: %m", unit->id);
 
        abort();
}
 
static void wait_for_service_finish(Manager *m, Unit *unit) {
        Service *service = SERVICE(ASSERT_PTR(unit));
        usec_t timeout = 2 * USEC_PER_MINUTE;
 
        ASSERT_NOT_NULL(m);
 
        /* Bump the timeout when running in plain QEMU or in CI, as some more involved tests might start
         * hitting the default 2m timeout (like exec-dynamicuser-statedir.service). */
        if (detect_virtualization() == VIRTUALIZATION_QEMU || ci_environment())
                timeout *= 2;
 
        printf("%s\n", unit->id);
        exec_context_dump(&service->exec_context, stdout, "\t");
 
        /* Use a per-Exec timeout rather than a service timeout, as especially under sanitizers some test
         * units running many commands can hit the service timeout. */
        _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
        ASSERT_OK(sd_event_add_time_relative(m->event, &s, CLOCK_MONOTONIC, timeout, 0, time_handler, unit));
 
        /* Here, sd_event_loop() cannot be used, as the sd_event object will be reused in the next test case. */
        ExecCommand *last_command = service->main_command;
        while (!IN_SET(service->state, SERVICE_DEAD, SERVICE_FAILED)) {
                ASSERT_OK(sd_event_run(m->event, 100 * USEC_PER_MSEC));
 
                if (service->main_command != last_command) {
                        last_command = service->main_command;
                        ASSERT_OK(sd_event_source_set_time_relative(s, timeout));
                }
        }
}
 
static void check_main_result(const char *file, unsigned line, const char *func,
                              Manager *m, Unit *unit, int status_expected, int code_expected) {
        Service *service = NULL;
 
        ASSERT_NOT_NULL(m);
        ASSERT_NOT_NULL(unit);
 
        wait_for_service_finish(m, unit);
 
        service = SERVICE(unit);
        exec_status_dump(&service->main_exec_status, stdout, "\t");
 
        if (cld_dumped_to_killed(service->main_exec_status.code) != cld_dumped_to_killed(code_expected)) {
                log_error("%s:%u:%s %s: can_unshare=%s: exit code %d, expected %d",
                          file, line, func, unit->id, yes_no(can_unshare),
                          service->main_exec_status.code, code_expected);
                abort();
        }
 
        if (service->main_exec_status.status != status_expected) {
                log_error("%s:%u:%s: %s: can_unshare=%s: exit status %d, expected %d",
                          file, line, func, unit->id, yes_no(can_unshare),
                          service->main_exec_status.status, status_expected);
                abort();
        }
}
 
static void check_service_result(const char *file, unsigned line, const char *func,
                                 Manager *m, Unit *unit, ServiceResult result_expected) {
        Service *service = NULL;
 
        ASSERT_NOT_NULL(m);
        ASSERT_NOT_NULL(unit);
 
        wait_for_service_finish(m, unit);
 
        service = SERVICE(unit);
 
        if (service->result != result_expected) {
                log_error("%s:%u:%s: %s: can_unshare=%s: service end result %s, expected %s",
                          file, line, func, unit->id, yes_no(can_unshare),
                          service_result_to_string(service->result),
                          service_result_to_string(result_expected));
                abort();
        }
}
 
static bool check_nobody_user_and_group(void) {
        static int cache = -1;
        struct passwd *p;
        struct group *g;
 
        if (cache >= 0)
                return !!cache;
 
        if (!synthesize_nobody())
                goto invalid;
 
        p = getpwnam(NOBODY_USER_NAME);
        if (!p ||
            !streq(p->pw_name, NOBODY_USER_NAME) ||
            p->pw_uid != UID_NOBODY ||
            p->pw_gid != GID_NOBODY)
                goto invalid;
 
        p = getpwuid(UID_NOBODY);
        if (!p ||
            !streq(p->pw_name, NOBODY_USER_NAME) ||
            p->pw_uid != UID_NOBODY ||
            p->pw_gid != GID_NOBODY)
                goto invalid;
 
        g = getgrnam(NOBODY_GROUP_NAME);
        if (!g ||
            !streq(g->gr_name, NOBODY_GROUP_NAME) ||
            g->gr_gid != GID_NOBODY)
                goto invalid;
 
        g = getgrgid(GID_NOBODY);
        if (!g ||
            !streq(g->gr_name, NOBODY_GROUP_NAME) ||
            g->gr_gid != GID_NOBODY)
                goto invalid;
 
        cache = 1;
        return true;
 
invalid:
        cache = 0;
        return false;
}
 
static bool check_user_has_group_with_same_name(const char *name) {
        struct passwd *p;
        struct group *g;
 
        ASSERT_NOT_NULL(name);
 
        p = getpwnam(name);
        if (!p ||
            !streq(p->pw_name, name))
                return false;
 
        g = getgrgid(p->pw_gid);
        if (!g ||
            !streq(g->gr_name, name))
                return false;
 
        return true;
}
 
static bool is_inaccessible_available(void) {
        FOREACH_STRING(p,
                       "/run/systemd/inaccessible/reg",
                       "/run/systemd/inaccessible/dir",
                       "/run/systemd/inaccessible/chr",
                       "/run/systemd/inaccessible/blk",
                       "/run/systemd/inaccessible/fifo",
                       "/run/systemd/inaccessible/sock")
                if (access(p, F_OK) < 0)
                        return false;
 
        return true;
}
 
static void start_parent_slices(Unit *unit) {
        Unit *slice;
 
        slice = UNIT_GET_SLICE(unit);
        if (slice) {
                start_parent_slices(slice);
                ASSERT_OK_OR(unit_start(slice, NULL), -EALREADY);
        }
}
 
static bool apparmor_restrict_unprivileged_userns(void) {
        int v, r;
 
        /* If kernel.apparmor_restrict_unprivileged_userns=1, then we cannot
         * use unprivileged user namespaces. */
        r = sysctl_read_int("kernel/apparmor_restrict_unprivileged_userns", &v);
        if (r < 0) {
                if (r != -ENOENT)
                        log_debug_errno(r, "Failed to read kernel.apparmor_restrict_unprivileged_userns sysctl, ignoring: %m");
 
                return false;
        }
 
        return v > 0;
}
 
static bool have_userns_privileges(void) {
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        int r;
 
        if (apparmor_restrict_unprivileged_userns())
                return false;
 
        r = ASSERT_OK(pidref_safe_fork(
                        "(sd-test-check-userns)",
                        FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL,
                        &pidref));
 
        if (r == 0) {
                /* Keep CAP_SYS_ADMIN if we have it to ensure we give an
                 * accurate result to the caller. Some kernels have a
                 * kernel.unprivileged_userns_clone sysctl which can be
                 * configured to make CLONE_NEWUSER require CAP_SYS_ADMIN.
                 * Additionally, AppArmor may restrict unprivileged user
                 * namespace creation. */
                r = capability_bounding_set_drop(UINT64_C(1) << CAP_SYS_ADMIN, /* right_now= */ true);
                if (r < 0) {
                        log_debug_errno(r, "Failed to drop capabilities: %m");
                        _exit(2);
                }
 
                r = RET_NERRNO(unshare(CLONE_NEWUSER));
                if (r < 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
                        log_debug_errno(r, "Failed to create user namespace: %m");
 
                _exit(r >= 0 ? EXIT_SUCCESS : ERRNO_IS_NEG_PRIVILEGE(r) ? EXIT_FAILURE : 2);
        }
 
        /* The exit code records the result of the check:
         *  EXIT_SUCCESS => we can use user namespaces
         *  EXIT_FAILURE => we can NOT use user namespaces
         *  2            => some other error occurred */
        r = pidref_wait_for_terminate_and_check("(sd-test-check-userns)", &pidref, 0);
        if (!IN_SET(r, EXIT_SUCCESS, EXIT_FAILURE))
                log_debug("Failed to check if user namespaces can be used, assuming not.");
 
        return r == EXIT_SUCCESS;
}
 
static void _test(const char *file, unsigned line, const char *func,
                  Manager *m, const char *unit_name, int status_expected, int code_expected) {
        Unit *unit;
 
        ASSERT_NOT_NULL(unit_name);
 
        ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, LOG_ERR, &unit));
        /* We need to start the slices as well otherwise the slice cgroups might be pruned
         * in on_cgroup_empty_event. */
        start_parent_slices(unit);
        ASSERT_OK(unit_start(unit, NULL));
        check_main_result(file, line, func, m, unit, status_expected, code_expected);
 
        ++n_ran_tests;
}
#define test(m, unit_name, status_expected, code_expected) \
        _test(PROJECT_FILE, __LINE__, __func__, m, unit_name, status_expected, code_expected)
 
static void _test_service(const char *file, unsigned line, const char *func,
                          Manager *m, const char *unit_name, ServiceResult result_expected) {
        Unit *unit;
 
        ASSERT_NOT_NULL(unit_name);
 
        ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, LOG_ERR, &unit));
        ASSERT_OK(unit_start(unit, NULL));
        check_service_result(file, line, func, m, unit, result_expected);
}
#define test_service(m, unit_name, result_expected) \
        _test_service(PROJECT_FILE, __LINE__, __func__, m, unit_name, result_expected)
 
static void test_exec_bindpaths(Manager *m) {
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths source", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths destination", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths:source", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths:destination", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths source", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths destination", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths:source", 0755));
        ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths:destination", 0755));
 
        test(m, "exec-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
 
        (void) rm_rf("/tmp/test-exec-bindpaths", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindreadonlypaths", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindpaths source", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindpaths destination", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindpaths:source", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindpaths:destination", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindreadonlypaths source", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindreadonlypaths destination", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindreadonlypaths:source", REMOVE_ROOT|REMOVE_PHYSICAL);
        (void) rm_rf("/tmp/test-exec-bindreadonlypaths:destination", REMOVE_ROOT|REMOVE_PHYSICAL);
}
 
static void test_exec_cpuaffinity(Manager *m) {
        _cleanup_(cpu_set_done) CPUSet c = {};
 
        ASSERT_OK(cpu_set_realloc(&c, 8192)); /* just allocate the maximum possible size */
        ASSERT_OK_ERRNO(sched_getaffinity(0, c.allocated, c.set));
 
        if (!CPU_ISSET_S(0, c.allocated, c.set)) {
                log_notice("Cannot use CPU 0, skipping %s", __func__);
                return;
        }
 
        test(m, "exec-cpuaffinity1.service", 0, CLD_EXITED);
        test(m, "exec-cpuaffinity2.service", 0, CLD_EXITED);
 
        if (!CPU_ISSET_S(1, c.allocated, c.set) ||
            !CPU_ISSET_S(2, c.allocated, c.set)) {
                log_notice("Cannot use CPU 1 or 2, skipping remaining tests in %s", __func__);
                return;
        }
 
        test(m, "exec-cpuaffinity3.service", 0, CLD_EXITED);
}
 
static void test_exec_credentials(Manager *m) {
        test(m, "exec-set-credential.service", 0, CLD_EXITED);
        test(m, "exec-load-credential.service", 0, CLD_EXITED);
        test(m, "exec-credentials-dir-specifier.service", 0, CLD_EXITED);
}
 
static void test_exec_workingdirectory(Manager *m) {
        ASSERT_OK(mkdir_p("/tmp/test-exec_workingdirectory", 0755));
 
        test(m, "exec-workingdirectory.service", 0, CLD_EXITED);
        test(m, "exec-workingdirectory-trailing-dot.service", 0, CLD_EXITED);
 
        (void) rm_rf("/tmp/test-exec_workingdirectory", REMOVE_ROOT|REMOVE_PHYSICAL);
}
 
static void test_exec_execsearchpath(Manager *m) {
        int r;
 
        ASSERT_OK(r = is_symlink("/bin/ls"));
        if (r > 0)
                return (void) log_tests_skipped("/bin/ls is a symlink, maybe coreutils is built with --enable-single-binary=symlinks");
 
        ASSERT_OK(mkdir_p("/tmp/test-exec_execsearchpath", 0755));
 
        ASSERT_OK(copy_file("/bin/ls", "/tmp/test-exec_execsearchpath/ls_temp", 0,  0777, COPY_REPLACE));
 
        test(m, "exec-execsearchpath.service", 0, CLD_EXITED);
 
        ASSERT_OK(rm_rf("/tmp/test-exec_execsearchpath", REMOVE_ROOT|REMOVE_PHYSICAL));
 
        test(m, "exec-execsearchpath.service", EXIT_EXEC, CLD_EXITED);
}
 
static void test_exec_execsearchpath_specifier(Manager *m) {
        test(m, "exec-execsearchpath-unit-specifier.service", 0, CLD_EXITED);
}
 
static void test_exec_execsearchpath_environment(Manager *m) {
        test(m, "exec-execsearchpath-environment.service", 0, CLD_EXITED);
        test(m, "exec-execsearchpath-environment-path-set.service", 0, CLD_EXITED);
}
 
static void test_exec_execsearchpath_environment_files(Manager *m) {
        static const char path_not_set[] =
                "VAR1='word1 word2'\n"
                "VAR2=word3 \n"
                "# comment1\n"
                "\n"
                "; comment2\n"
                " ; # comment3\n"
                "line without an equal\n"
                "VAR3='$word 5 6'\n"
                "VAR4='new\nline'\n"
                "VAR5=password\\with\\backslashes";
 
        static const char path_set[] =
                "VAR1='word1 word2'\n"
                "VAR2=word3 \n"
                "# comment1\n"
                "\n"
                "; comment2\n"
                " ; # comment3\n"
                "line without an equal\n"
                "VAR3='$word 5 6'\n"
                "VAR4='new\nline'\n"
                "VAR5=password\\with\\backslashes\n"
                "PATH=/usr";
 
        int r;
 
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile.conf", path_not_set, WRITE_STRING_FILE_CREATE);
        ASSERT_OK(r);
 
        test(m, "exec-execsearchpath-environmentfile.service", 0, CLD_EXITED);
 
        (void) unlink("/tmp/test-exec_environmentfile.conf");
 
        r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile-set.conf", path_set, WRITE_STRING_FILE_CREATE);
        ASSERT_OK(r);
 
        test(m, "exec-execsearchpath-environmentfile-set.service", 0, CLD_EXITED);
 
        (void) unlink("/tmp/test-exec_environmentfile-set.conf");
}
 
static void test_exec_execsearchpath_passenvironment(Manager *m) {
        ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1));
        ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1));
        ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1));
        ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1));
        ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1));
 
        test(m, "exec-execsearchpath-passenvironment.service", 0, CLD_EXITED);
 
        ASSERT_OK_ERRNO(setenv("PATH", "/usr", 1));
        test(m, "exec-execsearchpath-passenvironment-set.service", 0, CLD_EXITED);
 
        ASSERT_OK_ERRNO(unsetenv("VAR1"));
        ASSERT_OK_ERRNO(unsetenv("VAR2"));
        ASSERT_OK_ERRNO(unsetenv("VAR3"));
        ASSERT_OK_ERRNO(unsetenv("VAR4"));
        ASSERT_OK_ERRNO(unsetenv("VAR5"));
        ASSERT_OK_ERRNO(unsetenv("PATH"));
}
 
static void test_exec_personality(Manager *m) {
#if defined(__x86_64__)
        test(m, "exec-personality-x86-64.service", 0, CLD_EXITED);
 
#elif defined(__s390x__)
        test(m, "exec-personality-s390x.service", 0, CLD_EXITED);
 
#elif defined(__s390__)
        test(m, "exec-personality-s390.service", 0, CLD_EXITED);
 
#elif defined(__powerpc64__)
#  if __BYTE_ORDER == __BIG_ENDIAN
        test(m, "exec-personality-ppc64.service", 0, CLD_EXITED);
#  else
        test(m, "exec-personality-ppc64le.service", 0, CLD_EXITED);
#  endif
 
#elif defined(__aarch64__)
        test(m, "exec-personality-aarch64.service", 0, CLD_EXITED);
 
#elif defined(__i386__)
        test(m, "exec-personality-x86.service", 0, CLD_EXITED);
#elif defined(__loongarch_lp64)
        test(m, "exec-personality-loongarch64.service", 0, CLD_EXITED);
#else
        log_notice("Unknown personality, skipping %s", __func__);
#endif
}
 
static void test_exec_ignoresigpipe(Manager *m) {
        test(m, "exec-ignoresigpipe-yes.service", 0, CLD_EXITED);
        test(m, "exec-ignoresigpipe-no.service", SIGPIPE, CLD_KILLED);
}
 
static void test_exec_privatetmp(Manager *m) {
        ASSERT_OK(touch("/tmp/test-exec_privatetmp"));
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
                test(m, "exec-privatetmp-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
                test(m, "exec-privatetmp-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
 
                (void) unlink("/tmp/test-exec_privatetmp_disconnected");
                test(m, "exec-privatetmp-disconnected-nodefaultdeps-nor-sandboxing.service", 0, CLD_EXITED);
                ASSERT_OK_ERRNO(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
 
                FOREACH_STRING(s,
                               "exec-privatetmp-disconnected.service",
                               "exec-privatetmp-disconnected-defaultdependencies-no.service",
                               "exec-privatetmp-disconnected-requires-mounts-for-var.service",
                               "exec-privatetmp-disconnected-wants-mounts-for-var.service",
                               "exec-privatetmp-disconnected-after-and-requires-for-var.service",
                               "exec-privatetmp-disconnected-after-and-wants-for-var.service") {
                        (void) unlink("/tmp/test-exec_privatetmp_disconnected");
                        (void) unlink("/var/tmp/test-exec_privatetmp_disconnected");
                        test(m, s, can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
                        ASSERT_FAIL(access("/tmp/test-exec_privatetmp_disconnected", F_OK));
                        ASSERT_FAIL(access("/var/tmp/test-exec_privatetmp_disconnected", F_OK));
                }
        }
 
        test(m, "exec-privatetmp-no.service", 0, CLD_EXITED);
 
        (void) unlink("/tmp/test-exec_privatetmp");
}
 
static void test_exec_privatedevices(Manager *m) {
        int r;
 
        if (detect_container() > 0) {
                log_notice("Testing in container, skipping %s", __func__);
                return;
        }
        if (!is_inaccessible_available()) {
                log_notice("Testing without inaccessible, skipping %s", __func__);
                return;
        }
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
                test(m, "exec-privatedevices-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
                if (access("/dev/kmsg", F_OK) >= 0)
                        test(m, "exec-privatedevices-bind.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
                test(m, "exec-privatedevices-disabled-by-prefix.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
                test(m, "exec-privatedevices-yes-with-group.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
        }
 
        test(m, "exec-privatedevices-no.service", 0, CLD_EXITED);
 
        /* We use capsh to test if the capabilities are
         * properly set, so be sure that it exists */
        r = find_executable("capsh", NULL);
        if (r < 0) {
                log_notice_errno(r, "Could not find capsh binary, skipping remaining tests in %s: %m", __func__);
                return;
        }
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
                test(m, "exec-privatedevices-yes-capability-mknod.service", can_unshare || MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
                test(m, "exec-privatedevices-yes-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
        }
 
        test(m, "exec-privatedevices-no-capability-mknod.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
        test(m, "exec-privatedevices-no-capability-sys-rawio.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
}
 
static void test_exec_protecthome(Manager *m) {
        if (!can_unshare) {
                log_notice("Cannot reliably unshare, skipping %s", __func__);
                return;
        }
 
        test(m, "exec-protecthome-tmpfs-vs-protectsystem-strict.service", 0, CLD_EXITED);
}
 
static void test_exec_protectkernelmodules(Manager *m) {
        int r;
 
        if (detect_container() > 0) {
                log_notice("Testing in container, skipping %s", __func__);
                return;
        }
        if (!is_inaccessible_available()) {
                log_notice("Testing without inaccessible, skipping %s", __func__);
                return;
        }
 
        r = find_executable("capsh", NULL);
        if (r < 0) {
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
                return;
        }
 
        test(m, "exec-protectkernelmodules-no-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_FAILURE, CLD_EXITED);
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) {
                test(m, "exec-protectkernelmodules-yes-capabilities.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
                test(m, "exec-protectkernelmodules-yes-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
        }
}
 
static void test_exec_readonlypaths(Manager *m) {
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
                test(m, "exec-readonlypaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
 
        if (path_is_read_only_fs("/var") > 0) {
                log_notice("Directory /var is readonly, skipping remaining tests in %s", __func__);
                return;
        }
 
        test(m, "exec-readonlypaths.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
        test(m, "exec-readonlypaths-with-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
        test(m, "exec-readonlypaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
}
 
static void test_exec_readwritepaths(Manager *m) {
 
        if (path_is_read_only_fs("/") > 0) {
                log_notice("Root directory is readonly, skipping %s", __func__);
                return;
        }
 
        test(m, "exec-readwritepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
}
 
static void test_exec_inaccessiblepaths(Manager *m) {
 
        if (!is_inaccessible_available()) {
                log_notice("Testing without inaccessible, skipping %s", __func__);
                return;
        }
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
                test(m, "exec-inaccessiblepaths-sys.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
 
        if (path_is_read_only_fs("/") > 0) {
                log_notice("Root directory is readonly, skipping remaining tests in %s", __func__);
                return;
        }
 
        test(m, "exec-inaccessiblepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
}
 
#if !HAS_FEATURE_ADDRESS_SANITIZER
static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        char **result = userdata;
        char buf[4096];
        ssize_t l;
 
        ASSERT_NOT_NULL(s);
        ASSERT_GT(fd, 0);
 
        l = read(fd, buf, sizeof(buf) - 1);
        if (l < 0) {
                if (errno == EAGAIN)
                        goto reenable;
 
                return 0;
        }
        if (l == 0)
                return 0;
 
        buf[l] = '\0';
        if (result)
                ASSERT_NOT_NULL(strextend(result, buf));
        else
                log_error("ldd: %s", buf);
 
reenable:
        /* Re-enable the event source if we did not encounter EOF */
        ASSERT_OK(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT));
        return 0;
}
 
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
        PidRef *pidref = ASSERT_PTR(userdata);
 
        (void) pidref_kill(pidref, SIGKILL);
 
        return 1;
}
 
static int on_spawn_exit(sd_event_source *s, const siginfo_t *si, void *userdata) {
        int ret = -EIO;
 
        ASSERT_NOT_NULL(si);
 
        if (si->si_code == CLD_EXITED)
                ret = si->si_status;
 
        sd_event_exit(sd_event_source_get_event(s), ret);
        return 1;
}
 
static int find_libraries(const char *exec, char ***ret) {
        _cleanup_(sd_event_unrefp) sd_event *e = NULL;
        _cleanup_(sd_event_source_unrefp) sd_event_source *sigchld_source = NULL;
        _cleanup_(sd_event_source_unrefp) sd_event_source *stdout_source = NULL;
        _cleanup_(sd_event_source_unrefp) sd_event_source *stderr_source = NULL;
        _cleanup_close_pair_ int outpipe[2] = EBADF_PAIR, errpipe[2] = EBADF_PAIR;
        _cleanup_strv_free_ char **libraries = NULL;
        _cleanup_free_ char *result = NULL;
        int r;
 
        ASSERT_NOT_NULL(exec);
        ASSERT_NOT_NULL(ret);
 
        ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC));
        ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC));
 
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        r = pidref_safe_fork_full(
                        "(spawn-ldd)",
                        (int[]) { -EBADF, outpipe[1], errpipe[1] },
                        NULL, 0,
                        FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_LOG,
                        &pidref);
        ASSERT_OK(r);
        if (r == 0) {
                execlp("ldd", "ldd", exec, NULL);
                _exit(EXIT_FAILURE);
        }
 
        outpipe[1] = safe_close(outpipe[1]);
        errpipe[1] = safe_close(errpipe[1]);
 
        ASSERT_OK(sd_event_new(&e));
 
        ASSERT_OK(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC,
                                             10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pidref));
        ASSERT_OK(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result));
        ASSERT_OK(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT));
        ASSERT_OK(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL));
        ASSERT_OK(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT));
        ASSERT_OK(event_add_child_pidref(e, &sigchld_source, &pidref, WEXITED, on_spawn_exit, NULL));
        /* Child exit should be processed after IO is complete */
        ASSERT_OK(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1));
 
        ASSERT_OK(sd_event_loop(e));
 
        _cleanup_strv_free_ char **v = NULL;
        ASSERT_OK(strv_split_newlines_full(&v, result, 0));
 
        STRV_FOREACH(q, v) {
                _cleanup_free_ char *word = NULL;
                const char *p = *q;
 
                r = extract_first_word(&p, &word, NULL, 0);
                ASSERT_OK(r);
                if (r == 0)
                        continue;
 
                if (path_is_absolute(word)) {
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
                        continue;
                }
 
                word = mfree(word);
                r = extract_first_word(&p, &word, NULL, 0);
                ASSERT_OK(r);
                if (r == 0)
                        continue;
 
                if (!streq_ptr(word, "=>"))
                        continue;
 
                word = mfree(word);
                r = extract_first_word(&p, &word, NULL, 0);
                ASSERT_OK(r);
                if (r == 0)
                        continue;
 
                if (path_is_absolute(word)) {
                        ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word)));
                        continue;
                }
        }
 
        *ret = TAKE_PTR(libraries);
        return 0;
}
#endif
 
static void test_exec_mount_apivfs(Manager *m) {
#if !HAS_FEATURE_ADDRESS_SANITIZER
        _cleanup_free_ char *fullpath_touch = NULL, *fullpath_test = NULL, *data = NULL;
        _cleanup_strv_free_ char **libraries = NULL, **libraries_test = NULL;
        int r;
 
        ASSERT_NOT_NULL(user_runtime_unit_dir);
 
        r = find_executable("ldd", NULL);
        if (r < 0) {
                log_notice_errno(r, "Skipping %s, could not find 'ldd' command: %m", __func__);
                return;
        }
        r = find_executable("touch", &fullpath_touch);
        if (r < 0) {
                log_notice_errno(r, "Skipping %s, could not find 'touch' command: %m", __func__);
                return;
        }
        r = find_executable("test", &fullpath_test);
        if (r < 0) {
                log_notice_errno(r, "Skipping %s, could not find 'test' command: %m", __func__);
                return;
        }
 
        if (MANAGER_IS_USER(m) && !have_userns_privileges())
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
 
        ASSERT_OK(find_libraries(fullpath_touch, &libraries));
        ASSERT_OK(find_libraries(fullpath_test, &libraries_test));
        ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true));
 
        ASSERT_NOT_NULL(strextend(&data, "[Service]\n"));
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")));
        ASSERT_NOT_NULL((strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")));
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")));
        ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")));
 
        STRV_FOREACH(p, libraries)
                ASSERT_NOT_NULL((strextend(&data, "BindReadOnlyPaths=", *p, "\n")));
 
        ASSERT_OK(write_drop_in(user_runtime_unit_dir, "exec-mount-apivfs-no.service", 10, "bind-mount", data));
 
        ASSERT_OK(mkdir_p("/tmp/test-exec-mount-apivfs-no/root", 0755));
 
        test(m, "exec-mount-apivfs-no.service", can_unshare || !MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED);
 
        (void) rm_rf("/tmp/test-exec-mount-apivfs-no/root", REMOVE_ROOT|REMOVE_PHYSICAL);
#endif
}
 
static void test_exec_noexecpaths(Manager *m) {
 
        if (MANAGER_IS_SYSTEM(m) || have_userns_privileges())
                test(m, "exec-noexecpaths-simple.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED);
        else
                return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__);
}
 
static void test_exec_temporaryfilesystem(Manager *m) {
 
        test(m, "exec-temporaryfilesystem-options.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
        test(m, "exec-temporaryfilesystem-ro.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
        test(m, "exec-temporaryfilesystem-rw.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
        test(m, "exec-temporaryfilesystem-usr.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED);
}
 
static void test_exec_systemcallfilter(Manager *m) {
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
        int r;
 
        if (!is_seccomp_available()) {
                log_notice("Seccomp not available, skipping %s", __func__);
                return;
        }
 
        test(m, "exec-systemcallfilter-writing-handoff-timestamp.service", 0, CLD_EXITED);
 
        test(m, "exec-systemcallfilter-not-failing.service", 0, CLD_EXITED);
        test(m, "exec-systemcallfilter-not-failing2.service", 0, CLD_EXITED);
        test(m, "exec-systemcallfilter-not-failing3.service", 0, CLD_EXITED);
        test(m, "exec-systemcallfilter-failing.service", SIGSYS, CLD_KILLED);
        test(m, "exec-systemcallfilter-failing2.service", SIGSYS, CLD_KILLED);
        test(m, "exec-systemcallfilter-failing3.service", SIGSYS, CLD_KILLED);
 
        r = find_executable("python3", NULL);
        if (r < 0) {
                log_notice_errno(r, "Skipping remaining tests in %s, could not find python3 binary: %m", __func__);
                return;
        }
 
        test(m, "exec-systemcallfilter-with-errno-name.service", errno_from_name("EILSEQ"), CLD_EXITED);
        test(m, "exec-systemcallfilter-with-errno-number.service", 255, CLD_EXITED);
        test(m, "exec-systemcallfilter-with-errno-multi.service", errno_from_name("EILSEQ"), CLD_EXITED);
        test(m, "exec-systemcallfilter-with-errno-in-allow-list.service", errno_from_name("EILSEQ"), CLD_EXITED);
        test(m, "exec-systemcallfilter-override-error-action.service", SIGSYS, CLD_KILLED);
        test(m, "exec-systemcallfilter-override-error-action2.service", errno_from_name("EILSEQ"), CLD_EXITED);
 
        test(m, "exec-systemcallfilter-nonewprivileges.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
        test(m, "exec-systemcallfilter-nonewprivileges-protectclock.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
 
        r = find_executable("capsh", NULL);
        if (r < 0) {
                log_notice_errno(r, "Skipping %s, could not find capsh binary: %m", __func__);
                return;
        }
 
        test(m, "exec-systemcallfilter-nonewprivileges-bounding1.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
        test(m, "exec-systemcallfilter-nonewprivileges-bounding2.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
#endif
}
 
static void test_exec_systemcallerrornumber(Manager *m) {
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
        int r;
 
        if (!is_seccomp_available()) {
                log_notice("Seccomp not available, skipping %s", __func__);
                return;
        }
 
        r = find_executable("python3", NULL);
        if (r < 0) {
                log_notice_errno(r, "Skipping %s, could not find python3 binary: %m", __func__);
                return;
        }
 
        test(m, "exec-systemcallerrornumber-name.service", errno_from_name("EACCES"), CLD_EXITED);
        test(m, "exec-systemcallerrornumber-number.service", 255, CLD_EXITED);
#endif
}
 
static void test_exec_restrictnamespaces(Manager *m) {
#if HAVE_SECCOMP
        if (!is_seccomp_available()) {
                log_notice("Seccomp not available, skipping %s", __func__);
                return;
        }
 
        test(m, "exec-restrictnamespaces-no.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
        test(m, "exec-restrictnamespaces-yes.service", 1, CLD_EXITED);
        test(m, "exec-restrictnamespaces-mnt.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
        test(m, "exec-restrictnamespaces-mnt-deny-list.service", 1, CLD_EXITED);
        test(m, "exec-restrictnamespaces-merge-and.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
        test(m, "exec-restrictnamespaces-merge-or.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
        test(m, "exec-restrictnamespaces-merge-all.service", can_unshare ? 0 : EXIT_FAILURE, CLD_EXITED);
#endif
}
 
static void test_exec_systemcallfilter_system(Manager *m) {
/* Skip this particular test case when running under ASan, as
 * LSan intermittently segfaults when accessing memory right
 * after the test finishes. Generally, ASan & LSan don't like
 * the seccomp stuff.
 */
#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER
        if (!is_seccomp_available()) {
                log_notice("Seccomp not available, skipping %s", __func__);
                return;
        }
 
        test(m, "exec-systemcallfilter-system-user.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
 
        if (!check_nobody_user_and_group()) {
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
                return;
        }
 
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
                return;
        }
 
        test(m, "exec-systemcallfilter-system-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
#endif
}
 
static void test_exec_user(Manager *m) {
        test(m, "exec-user.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
 
        if (!check_nobody_user_and_group()) {
                log_notice("nobody user/group is not synthesized or may conflict to other entries, skipping remaining tests in %s", __func__);
                return;
        }
 
        if (!STR_IN_SET(NOBODY_USER_NAME, "nobody", "nfsnobody")) {
                log_notice("Unsupported nobody user name '%s', skipping remaining tests in %s", NOBODY_USER_NAME, __func__);
                return;
        }
 
        test(m, "exec-user-" NOBODY_USER_NAME ".service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);
}
 
static void test_exec_group(Manager *m) {
        test(m, "exec-group.service", MANAGER_IS_SYSTEM(m) ? 0 : EXIT_GROUP, CLD_EXITED);