From 46206b3e1602b248031694007a133041927e0c80 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Tue, 24 Nov 2026 16:18:05 -0500 Subject: [PATCH] fix(desktop): links read into a buffer sized from lstat show their guest target (#3157) * fix(desktop): links read into a buffer sized from lstat show their guest target lstat reports the guest length of a link stored with a rootfs target, and dpkg's update-alternatives then reads it with exactly that many bytes. readlink filled the buffer with the start of the host path, which could no longer be mapped back, so every alternative looked dangling ("current alternative /data/dat is unknown"). The whole target is read first, mapped, then copied into the caller's buffer. * fix(desktop): a zero-sized readlink buffer still fails with EINVAL * test(desktop): read errno before printing the zero-size readlink result --- tools/nativeguest/hook/fileops.c | 25 ++++-- tools/tests/test_native_hook_readlink.py | 106 +++++++++++++++++++++++ 2 files changed, 125 insertions(+), 6 deletions(-) create mode 100644 tools/tests/test_native_hook_readlink.py diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index 2632f0eefb..b20c07f814 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -418,6 +418,13 @@ int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpa return ret; } +static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, ssize_t ret) { + if (ret <= 0 || out == buf) return ret; + size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz; + memcpy(buf, out, n); + return (ssize_t)n; +} + // Hook readlink ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (is_proc_self_exe(pathname)) { @@ -431,13 +438,16 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink"); char pbuf[PATH_MAX]; const char *target = rewrite_path(pathname, pbuf, sizeof(pbuf)); - ssize_t ret = orig_readlink ? orig_readlink(target, buf, bufsiz) : -1; + char whole[PATH_MAX]; + char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf; + size_t outsiz = out == whole ? sizeof(whole) : bufsiz; + ssize_t ret = orig_readlink ? orig_readlink(target, out, outsiz) : -1; if (ret < 0 && errno == ENOENT) { char alt[PATH_MAX]; const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); - if (retry) ret = orig_readlink(retry, buf, bufsiz); + if (retry) ret = orig_readlink(retry, out, outsiz); } - return postprocess_readlink(pathname, buf, ret, bufsiz); + return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); } // Hook readlinkat @@ -459,13 +469,16 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { } char pbuf[PATH_MAX]; const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname; - ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, buf, bufsiz) : -1; + char whole[PATH_MAX]; + char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf; + size_t outsiz = out == whole ? sizeof(whole) : bufsiz; + ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, out, outsiz) : -1; if (ret < 0 && errno == ENOENT && pathname && pathname[0] == '/') { char alt[PATH_MAX]; const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); - if (retry) ret = orig_readlinkat(dirfd, retry, buf, bufsiz); + if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz); } - return postprocess_readlink(pathname, buf, ret, bufsiz); + return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); } // Fortified readlink variants used by dpkg / update-alternatives diff --git a/tools/tests/test_native_hook_readlink.py b/tools/tests/test_native_hook_readlink.py new file mode 100644 index 0000000000..ed594f6365 --- /dev/null +++ b/tools/tests/test_native_hook_readlink.py @@ -0,0 +1,106 @@ +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""" +#include +#include +#include +#include +#include +#include +#include + +static void show(const char *name, ssize_t len, const char *buf) { + printf("%s\t%zd\t%.*s\n", name, len, len > 0 ? (int)len : 0, buf); +} + +int main(int argc, char **argv) { + const char *link = argv[1]; + struct stat st; + if (lstat(link, &st) != 0) return 2; + char *exact = malloc((size_t)st.st_size + 1); + show("sized", readlink(link, exact, (size_t)st.st_size), exact); + char full[4096]; + show("full", readlink(link, full, sizeof(full)), full); + char small[4]; + show("small", readlink(link, small, sizeof(small)), small); + show("sized-at", readlinkat(AT_FDCWD, link, exact, (size_t)st.st_size), exact); + errno = 0; + ssize_t zero = readlink(link, full, 0); + int zero_errno = errno; + printf("zero\t%zd\t%d\n", zero, zero_errno); + errno = 0; + zero = readlinkat(AT_FDCWD, link, full, 0); + zero_errno = errno; + printf("zero-at\t%zd\t%d\n", zero, zero_errno); + return 0; +} +""" + + +class NativeHookReadlinkTest(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(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 / "bin").mkdir(parents=True) + (cls.root / "etc/alternatives").mkdir(parents=True) + (cls.root / "bin/nano").write_text("") + os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor") + os.symlink("/bin/nano", cls.root / "etc/alternatives/guest") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def read(self, link): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + 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), link], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(0, out.returncode, out.stdout + out.stderr) + return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + + def test_a_buffer_sized_from_lstat_gets_the_guest_target(self): + result = self.read("/etc/alternatives/editor") + self.assertEqual(["9", "/bin/nano"], result["sized"]) + self.assertEqual(["9", "/bin/nano"], result["sized-at"]) + self.assertEqual(["9", "/bin/nano"], result["full"]) + + def test_a_short_buffer_gets_the_start_of_the_guest_target(self): + self.assertEqual(["4", "/bin"], self.read("/etc/alternatives/editor")["small"]) + + def test_a_guest_target_is_unchanged(self): + result = self.read("/etc/alternatives/guest") + self.assertEqual(["9", "/bin/nano"], result["sized"]) + self.assertEqual(["4", "/bin"], result["small"]) + + def test_a_zero_sized_buffer_is_rejected(self): + result = self.read("/etc/alternatives/editor") + self.assertEqual(["-1", str(errno.EINVAL)], result["zero"]) + self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"]) + + +if __name__ == "__main__": + unittest.main()