Files
DroidDeck/tools/tests/test_native_hook_memfd_reopen.py
T
MaxsTechReview 872c5e1834 fix(native): reopen refused memfds and answer links in the form they are named (#3734)
* fix(native): reopen refused memfds and answer links in the form they are named

Android's app policy refuses the open permission on memory files, so a
read-only reopen of an own memfd through /proc/self/fd/N,
/proc/thread-self/fd/N, /proc/<own pid or thread>/fd/N or /dev/fd/N
failed with EACCES while read, write and mmap of the descriptor still
worked. The hook now answers such a refused read-only open with a new
memfd holding the same bytes, name, mode and seals. Writable opens,
other processes' descriptors and regular files stay refused. FEX routes
guest openat through libc syscall(), so x86 guests get the same answer.

readlink() stripped the rootfs prefix from every target, so a link
stored with a real target (Proton's s: drive) read as /root/... while
getcwd(), /proc/self/fd and /proc/self/maps give the real path, and a
path resolved through the link no longer matched the working directory.
A link named by its real rootfs path, and /proc/<pid>/cwd, now keep the
real target, as realpath() of a real path does; guest and relative names
keep the guest form.

* fix(native): keep the memfd copy read-only, leave openat2 errors native, keep guest form for remapped link names

The copy that answers a refused read-only memfd reopen is now sealed
against writes and resizing, so it cannot be written through as a
read-only descriptor could not. openat2 reads its open_how only after
the kernel refused the open with EACCES, so an unreadable pointer gets
the kernel's EFAULT. readlinkat and fstatat keep the guest form for a
relative name the hook remapped to a real path; only a name the caller
supplied in real form keeps the real target.

* fix(native): pin the memfd being copied and refuse copies that cannot match it

* Copy a refused memfd only when the path and the descriptor name one file
2026-12-05 02:54:50 -05:00

230 lines
8.8 KiB
Python

import errno
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 <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#define SIZE 100003
static unsigned long sum_of(int fd) {
unsigned long sum = 0;
unsigned char buf[4096];
ssize_t n;
long total = 0;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
for (ssize_t i = 0; i < n; i++) sum = sum * 31 + buf[i];
total += n;
}
return total == SIZE ? sum : 0;
}
static int open_by(const char *how, const char *path, int flags) {
if (strcmp(how, "open") == 0) return open(path, flags);
if (strcmp(how, "openat") == 0) return openat(AT_FDCWD, path, flags);
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, 0);
}
static void report(const char *label, int fd, int src) {
if (fd < 0) {
printf("%s\terr\t%d\n", label, errno);
return;
}
char link[64], target[256];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, target, sizeof(target) - 1);
target[n > 0 ? n : 0] = '\0';
char *deleted = strstr(target, " (deleted)");
if (deleted) *deleted = '\0';
struct stat a, b;
fstat(fd, &a);
fstat(src, &b);
unsigned long sum = sum_of(fd);
int write_errno = pwrite(fd, "x", 1, 0) < 0 ? errno : 0;
int grow_errno = ftruncate(fd, SIZE + 1) < 0 ? errno : 0;
printf("%s\tok\t%lu\t%d\t%s\t%d\t%ld\t%o\t%d\t%d\n", label, sum, fcntl(fd, F_GET_SEALS), target,
(fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (long)lseek(src, 0, SEEK_CUR), (unsigned)(a.st_mode & 07777),
write_errno != 0, grow_errno != 0);
close(fd);
}
int main(int argc, char **argv) {
int src = memfd_create("probe-module", MFD_ALLOW_SEALING);
unsigned char *data = malloc(SIZE);
for (long i = 0; i < SIZE; i++) data[i] = (unsigned char)(i * 7 + 3);
if (write(src, data, SIZE) != SIZE) return 3;
unsigned long want = 0;
for (long i = 0; i < SIZE; i++) want = want * 31 + data[i];
printf("want\t%lu\n", want);
fcntl(src, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
fchmod(src, 0);
char path[64];
const char *forms[] = {"self", "thread", "pid", "dev"};
const char *hows[] = {"open", "openat", "syscall"};
for (int f = 0; f < 4; f++) {
for (int h = 0; h < 3; h++) {
if (f == 0) snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (f == 1) snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", src);
if (f == 2) snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), src);
if (f == 3) snprintf(path, sizeof(path), "/dev/fd/%d", src);
char label[32];
snprintf(label, sizeof(label), "%s-%s", forms[f], hows[h]);
report(label, open_by(hows[h], path, O_RDONLY | O_CLOEXEC), src);
}
}
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
report("keep-cloexec-off", open(path, O_RDONLY), src);
report("write", open(path, O_RDWR), src);
int foreign = memfd_create("probe-foreign", 0);
fchmod(foreign, 0);
pid_t child = fork();
if (child < 0) return 6;
if (child == 0) {
pause();
_exit(0);
}
snprintf(path, sizeof(path), "/proc/%d/fd/%d", (int)child, foreign);
report("other-pid", open(path, O_RDONLY), src);
kill(child, SIGKILL);
waitpid(child, NULL, 0);
int plain = open(argv[1], O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (write(plain, "x", 1) != 1) return 4;
fchmod(plain, 0);
snprintf(path, sizeof(path), "/proc/self/fd/%d", plain);
report("plain-file", open(path, O_RDONLY | O_CLOEXEC), plain);
int open_mfd = memfd_create("probe-open", 0);
if (write(open_mfd, data, SIZE) != SIZE) return 5;
snprintf(path, sizeof(path), "/proc/self/fd/%d", open_mfd);
int again = open(path, O_RDONLY | O_CLOEXEC);
struct stat a, b;
fstat(again, &a);
fstat(open_mfd, &b);
printf("readable-memfd\t%d\n", again >= 0 && a.st_ino == b.st_ino);
unsigned long long how[3] = {O_RDONLY | O_CLOEXEC, 0, 0};
errno = 0;
long direct = syscall(437, AT_FDCWD, "/", how, sizeof(how));
printf("kernel-openat2\t%d\n", direct >= 0 || errno != ENOSYS);
int (*open2)(int, const char *, void *, size_t) = dlsym(RTLD_DEFAULT, "openat2");
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (open2 && argc > 2) {
errno = 0;
int refused = open2(AT_FDCWD, path, (void *)8, 24);
int refused_errno = errno;
printf("unreadable-how\t%d\t%d\n", refused, refused_errno);
}
return 0;
}
"""
class NativeHookMemfdReopenTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
if os.geteuid() == 0:
raise unittest.SkipTest("root ignores the file mode that stands in for the refused reopen")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
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.mkdir()
cls.plain = cls.root / "plain"
cls.bare = cls.run_probe(False)
cls.kernel_openat2 = cls.bare["kernel-openat2"] == ["1"]
cls.hooked = cls.run_probe(True, *(["how"] if cls.kernel_openat2 else []))
@classmethod
def tearDownClass(cls):
os.chmod(cls.plain, 0o600)
cls.tmp.cleanup()
@classmethod
def run_probe(cls, hook, *extra):
if cls.plain.exists():
os.chmod(cls.plain, 0o600)
hook_env = {"DDNATV_ROOT": str(cls.root), "LD_PRELOAD": str(cls.hook)} if hook else {}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if cls.prefix:
cmd = list(cls.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(cls.probe), str(cls.plain), *extra], env=env, capture_output=True, text=True, timeout=120)
if out.returncode != 0:
raise AssertionError(out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_the_refused_reopen_is_the_condition_without_the_hook(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-open"])
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-syscall"])
def test_a_refused_read_only_reopen_of_an_own_memfd_gets_its_bytes_and_seals(self):
want = self.hooked["want"][0]
for form in ("self", "thread", "pid", "dev"):
for how in ("open", "openat", "syscall"):
with self.subTest(form=form, how=how):
status, total, seals, name, cloexec, offset, mode, unwritable, fixed = self.hooked[f"{form}-{how}"]
self.assertEqual("ok", status)
self.assertEqual(want, total)
self.assertEqual(str(0x2 | 0x4 | 0x8), seals)
self.assertEqual("1", unwritable)
self.assertEqual("1", fixed)
self.assertEqual("/memfd:probe-module", name)
self.assertEqual("1", cloexec)
self.assertEqual("100003", offset)
self.assertEqual("0", mode)
def test_close_on_exec_follows_the_open_flags(self):
self.assertEqual("0", self.hooked["keep-cloexec-off"][4])
def test_an_unreadable_open_how_gets_the_kernel_error(self):
if not self.kernel_openat2:
self.skipTest("the runner has no openat2")
self.assertEqual(["-1", str(errno.EFAULT)], self.hooked["unreadable-how"])
def test_a_writable_reopen_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["write"])
def test_another_process_descriptor_is_not_copied(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["other-pid"])
self.assertEqual(["err", str(errno.EACCES)], self.hooked["other-pid"])
def test_a_refused_regular_file_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["plain-file"])
self.assertEqual(self.bare["plain-file"], self.hooked["plain-file"])
def test_a_memfd_the_kernel_reopens_is_the_same_file(self):
self.assertEqual(["1"], self.hooked["readable-memfd"])
self.assertEqual(["1"], self.bare["readable-memfd"])
if __name__ == "__main__":
unittest.main()