fix(nativeguest): x86-64 path calls, SIGSYS handlers and re-execs stay inside the rootfs hook (#3074)

* fix(nativeguest): x86-64 path system calls and SIGSYS handlers stay inside the rootfs hook

FEX passed most guest path system calls to the kernel with an inline svc, so the
native path hook never mapped them, and it mirrored guest SIGSYS handlers with a
raw rt_sigaction that replaced the hook's own handler, after which the next
blocked system call killed the program. Path calls now go through libc's
syscall(), which the hook maps (guarded until the hook is initialised so an early
allocator cannot deadlock), and a SIGSYS handler set through syscall() is
recorded and chained like one set through sigaction().

* fix(ddexec): a program that re-execs itself keeps the rootfs hook

A re-exec through /proc/self/exe starts the program through the guest
ld.so again but left out the hook, so the child saw host paths. Steam's
reaper then recorded host install folders, and Battle.net games moved to
a mapped drive the Library could not resolve. The re-exec now preloads
the hook of the root the same way the first start does.
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-23 11:11:10 -05:00
1 parent bf7f7ecda7
commit 823f70320f
11 files changed
+942 -52

No files matched your search

+154
View File
@@ -0,0 +1,154 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c"
SYSROOT = Path("/usr/aarch64-linux-gnu")
LIBRARY = r"""
int dd_probe_value(void) { return 7; }
"""
HOOK = r"""
#include <unistd.h>
__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); }
"""
PROGRAM = r"""
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/auxv.h>
#include <sys/syscall.h>
int dd_probe_value(void);
int main(int argc, char **argv, char **envp) {
if (dd_probe_value() != 7) return 4;
if (argc > 1 && strcmp(argv[1], "again") == 0) {
for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]);
printf("\n%s\n", (char *)getauxval(AT_EXECFN));
return 0;
}
char *next[] = {"first", "again", "x y", NULL};
syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0);
return 3;
}
"""
def ndk_clang():
sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk")
for ndk in sorted((sdk / "ndk").glob("*"), reverse=True):
clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
if clang.exists():
return str(clang)
return shutil.which("clang")
class DdexecReexecTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cc, prefix = runner()
clang = ndk_clang()
if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir():
raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap")
cls.qemu = list(prefix[:3]) if prefix else []
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.loader = tmp / "libddexec.so"
subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding",
"-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib",
"-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic",
"-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True)
cls.libdir = tmp / "own-lib"
cls.libdir.mkdir()
(tmp / "lib.c").write_text(LIBRARY)
subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")],
check=True)
(tmp / "prog.c").write_text(PROGRAM)
cls.program = tmp / "prog"
subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"],
check=True)
cls.root = tmp / "root"
(cls.root / "usr/lib").mkdir(parents=True)
(cls.root / "lib").mkdir()
shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1")
(tmp / "hook.c").write_text(HOOK)
subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")],
check=True)
probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True)
if probe.returncode != 0:
raise unittest.SkipTest("bwrap cannot create a namespace here")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def env(self, real_exe, library_path=None, root=SYSROOT):
env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))}
env["DDNATV_ROOT"] = str(root)
env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib")
if real_exe:
env["DDNATV_REAL_EXE"] = str(real_exe)
if library_path:
env["DDNATV_LIBRARY_PATH"] = library_path
return env
def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT):
jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"]
parent = str(Path(execfn).parent)
jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn]
start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn]
cmd = jail + start + ["again", "x y"]
return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120)
def test_reexec_through_proc_self_exe_runs_the_guest_program(self):
out = self.reexec("/proc/self/exe", self.program)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_through_thread_self_exe_runs_the_guest_program(self):
out = self.reexec("/proc/thread-self/exe", self.program)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_finds_libraries_through_the_recorded_library_path(self):
out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}")
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self):
out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_without_a_known_program_fails_cleanly(self):
out = self.reexec("/proc/self/exe", None)
self.assertEqual(127, out.returncode)
self.assertIn("DDNATV_REAL_EXE", out.stderr)
def test_a_started_program_keeps_its_own_arguments(self):
ldso = SYSROOT / "lib/ld-linux-aarch64.so.1"
cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}",
str(self.program), "again", "a"]
out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines())
def test_the_usage_check_still_applies_outside_a_reexec(self):
out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program),
capture_output=True, text=True, timeout=120)
self.assertEqual(127, out.returncode)
self.assertIn("usage", out.stderr)
if __name__ == "__main__":
unittest.main()
+49
View File
@@ -0,0 +1,49 @@
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch"
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
def changed():
removed, added = {}, {}
for line in PATCH.read_text().splitlines():
found = REGISTER.search(line)
if found and line[:1] in "+-":
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
return removed, added
class FexPathSyscallsTest(unittest.TestCase):
def test_only_the_passthrough_table_changes(self):
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self):
removed, added = changed()
self.assertEqual(sorted(removed), sorted(added))
self.assertGreater(len(added), 10)
for name, (template, arity, number) in added.items():
with self.subTest(name=name):
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
self.assertEqual("SyscallPathPassthrough", template)
def test_the_new_templates_call_the_libc_syscall(self):
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
calls = [line for line in added if "syscall(" in line and "Result" in line]
self.assertEqual(5, len(calls))
self.assertTrue(all("::syscall(syscall_num" in line for line in calls))
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
def test_every_routed_syscall_is_rewritten_by_the_hook(self):
hook = HOOK.read_text()
for name, (_, _, number) in changed()[1].items():
with self.subTest(name=name):
self.assertIn(f"number == __NR_{number})", hook)
if __name__ == "__main__":
unittest.main()
+19 -3
View File
@@ -15,24 +15,27 @@ RECORDER = r"""
#define _GNU_SOURCE
#include <spawn.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static void show(const char *path, char *const argv[]) {
static void show(const char *path, char *const argv[], char *const envp[]) {
printf("call\t%s", path);
for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]);
printf("\n");
for (int i = 0; envp && envp[i]; i++)
if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20);
fflush(stdout);
}
int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
show(path, argv);
show(path, argv, envp);
if (pid) *pid = 1;
return 0;
}
int execve(const char *path, char *const argv[], char *const envp[]) {
show(path, argv);
show(path, argv, envp);
_exit(0);
}
"""
@@ -114,6 +117,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120)
calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")]
self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")]
self.assertEqual(1, len(calls), out.stdout + out.stderr)
if how == "spawn":
self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr)
@@ -142,6 +146,18 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self):
self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x"))
def test_a_program_started_through_ldso_records_its_library_path(self):
for how in ("exec", "spawn"):
with self.subTest(how=how):
argv = self.call(how, GUEST_TOOL, "x")[1:]
self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths)
def test_ldso_started_by_name_records_no_library_path(self):
for how in ("exec", "spawn"):
with self.subTest(how=how):
self.call(how, GUEST_LDSO, "--list", GUEST_TOOL)
self.assertEqual([], self.library_paths)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,163 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); }
int main(int argc, char **argv) {
const char *dir = argv[1];
char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX];
snprintf(p, sizeof(p), "%s/made", dir);
show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755));
snprintf(p, sizeof(p), "%s/made/file", dir);
long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
show("openat", fd);
if (fd >= 0) close((int)fd);
show("truncate", syscall(SYS_truncate, p, 4));
show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600));
show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0));
fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC);
show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1);
if (fd >= 0) close((int)fd);
snprintf(q, sizeof(q), "%s/made/moved", dir);
show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q));
show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0));
snprintf(q, sizeof(q), "%s/made/link", dir);
show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q));
show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0));
snprintf(q, sizeof(q), "%s/made", dir);
show("chdir", syscall(SYS_chdir, q));
show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1);
show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0));
show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR));
return 0;
}
"""
ALLOCATOR = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
extern void *__libc_malloc(size_t);
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static int ready;
void *malloc(size_t size) {
if (!ready) {
pthread_mutex_lock(&lock);
if (!ready) {
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC);
if (fd >= 0) close((int)fd);
ready = 1;
}
pthread_mutex_unlock(&lock);
}
return __libc_malloc(size);
}
int main(void) {
puts("ready");
return 0;
}
"""
EARLY = r"""
#include <stdlib.h>
__attribute__((constructor)) static void early(void) { free(malloc(1)); }
"""
CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat",
"chdir", "cwd", "unlinkat-file", "unlinkat-dir")
class NativeHookPathSyscallsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
(cls.root / "opt").mkdir(parents=True)
(tmp / "allocator.c").write_text(ALLOCATOR)
cls.allocator = tmp / "allocator"
subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True)
(tmp / "early.c").write_text(EARLY)
cls.early = tmp / "early.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_program(self, argv, hook_env):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120)
def run_probe(self, guest_dir, hook=True):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {}
out = self.run_program([str(self.probe), guest_dir], hook_env)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()}
def test_guest_paths_through_syscall_land_in_the_root(self):
results = self.run_probe("/opt")
for call in CALLS:
with self.subTest(call=call):
self.assertEqual(1, results[call])
self.assertEqual([], list((self.root / "opt").iterdir()))
def test_paths_already_in_the_root_are_kept(self):
results = self.run_probe(str(self.root / "opt"))
for call in CALLS:
with self.subTest(call=call):
self.assertEqual(1, results[call])
def test_without_the_hook_guest_paths_reach_the_host(self):
results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False)
self.assertEqual(0, results["mkdirat"])
self.assertEqual(0, results["openat"])
self.assertEqual(0, results["chdir"])
def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self):
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc",
"LD_PRELOAD": f"{self.hook}:{self.early}"}
out = self.run_program([str(self.allocator)], hook_env)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual("ready", out.stdout.strip())
if __name__ == "__main__":
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
static uint64_t current(void) {
uint64_t mask = 0;
syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask));
return mask;
}
struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; };
static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; }
static long raw_sigaction(int sig, const struct kact *act, struct kact *old) {
register long x8 __asm__("x8") = SYS_rt_sigaction;
register long x0 __asm__("x0") = sig;
register long x1 __asm__("x1") = (long)act;
register long x2 __asm__("x2") = (long)old;
register long x3 __asm__("x3") = 8;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
return x0;
}
static void handlers(void) {
struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel;
syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8);
syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8);
raw_sigaction(SIGSYS, NULL, &kernel);
printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own);
struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 };
syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8);
raw_sigaction(SIGUSR1, NULL, &kernel);
printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own);
}
static void show(const char *how) {
uint64_t mask = current();
printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1))));
uint64_t none = 0;
syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none));
}
int main(int argc, char **argv) {
uint64_t all = ~0ULL;
sigset_t set;
sigfillset(&set);
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all));
else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all));
else if (strcmp(argv[i], "syscall-unblock") == 0) {
syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all));
uint64_t usr1 = 1ULL << (SIGUSR1 - 1);
syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1));
}
else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL);
else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL);
else if (strcmp(argv[i], "sigaction") == 0) {
handlers();
continue;
}
show(argv[i]);
}
return 0;
}
"""
WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask")
class NativeHookSigsysMaskTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def masks(self, *ways, hook=True):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *ways], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()}
def test_blocking_every_signal_leaves_sigsys_open(self):
masks = self.masks(*WAYS)
for way in WAYS:
with self.subTest(way=way):
self.assertEqual((0, 1), masks[way])
def test_unblocking_is_unchanged(self):
self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"])
def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self):
seen = self.masks("sigaction")
self.assertEqual((1, 0), seen["sigaction"])
self.assertEqual((1,), seen["sigaction-usr1"])
def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self):
self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"])
def test_without_the_hook_every_signal_is_blocked(self):
masks = self.masks(*WAYS, hook=False)
for way in WAYS:
with self.subTest(way=way):
self.assertEqual((1, 1), masks[way])
if __name__ == "__main__":
unittest.main()