fix(desktop): a program started through a directory link knows its real path (#3158)

* fix(desktop): a program started through a directory link knows its real path

* fix(desktop): a missing or non-directory component still fails the lookup
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-24 16:23:06 -05:00
1 parent afe81ea69f
commit 14b130500f
2 files changed
+178 -10

No files matched your search

+62 -10
View File
@@ -9,17 +9,73 @@
// Runs before every exec, mostly in a child a shell has just forked: the copies write only the
// string (ddnatv_copy_cstr), not the whole PATH_MAX buffer, since each page written there is a
// copy-on-write fault.
static int follow_link(const char *path, char *target, size_t size) {
ssize_t len = readlink(path, target, size - 1);
if (len < 0) return 0;
target[len] = '\0';
// proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name
const char *base = strrchr(target, '/');
return strncmp(base ? base + 1 : target, ".l2s.", 5) != 0;
}
static void resolve_symlinks(const char *path, char *out, size_t out_size, int depth) {
if (!path || !out || out_size == 0) return;
ddnatv_copy_cstr(out, out_size, path);
if (depth > 8) return;
char link_target[PATH_MAX];
ssize_t len = readlink(path, link_target, sizeof(link_target) - 1);
if (len < 0) return;
link_target[len] = '\0';
char next_path[PATH_MAX];
if (g_ddnatv_root_len > 0 && strncmp(path, g_ddnatv_root, g_ddnatv_root_len) == 0 && path[g_ddnatv_root_len] == '/') {
char done[PATH_MAX];
char todo[PATH_MAX];
size_t used = ddnatv_append(done, sizeof(done), 0, g_ddnatv_root, g_ddnatv_root_len);
ddnatv_copy_cstr(todo, sizeof(todo), path + g_ddnatv_root_len);
int links = 0;
char *rest = todo;
while (*rest) {
while (*rest == '/') rest++;
if (!*rest) break;
char *end = strchr(rest, '/');
size_t n = end ? (size_t)(end - rest) : strlen(rest);
if (n == 1 && rest[0] == '.') {
rest += n;
continue;
}
if (n == 2 && rest[0] == '.' && rest[1] == '.') {
char *slash = strrchr(done + g_ddnatv_root_len, '/');
if (slash) used = (size_t)(slash - done);
done[used] = '\0';
rest += n;
continue;
}
size_t before = used;
used = ddnatv_append(done, sizeof(done), used, "/", 1);
used = ddnatv_append(done, sizeof(done), used, rest, n);
rest += n;
if (used >= sizeof(done) - 1) return;
if (!follow_link(done, link_target, sizeof(link_target))) {
struct stat st;
if (rest[strspn(rest, "/")] && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return;
continue;
}
if (++links > 40) return;
size_t m = ddnatv_append(next_path, sizeof(next_path), 0, link_target, strlen(link_target));
m = ddnatv_append(next_path, sizeof(next_path), m, "/", 1);
m = ddnatv_append(next_path, sizeof(next_path), m, rest, strlen(rest));
if (m >= sizeof(next_path) - 1) return;
if (link_target[0] == '/') {
char rw_buf[PATH_MAX];
resolve_symlinks(rewrite_path(next_path, rw_buf, sizeof(rw_buf)), out, out_size, depth + 1);
return;
}
used = before;
done[used] = '\0';
ddnatv_copy_cstr(todo, sizeof(todo), next_path);
rest = todo;
}
if (used > g_ddnatv_root_len) ddnatv_copy_cstr(out, out_size, done);
return;
}
if (!follow_link(path, link_target, sizeof(link_target))) return;
if (link_target[0] == '/') {
char rw_buf[PATH_MAX];
const char *rewritten = rewrite_path(link_target, rw_buf, sizeof(rw_buf));
@@ -32,15 +88,11 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d
memcpy(next_path, path, dir_len);
next_path[dir_len] = '\0';
size_t n = ddnatv_append(next_path, sizeof(next_path), dir_len, "/", 1);
ddnatv_append(next_path, sizeof(next_path), n, link_target, (size_t)len);
ddnatv_append(next_path, sizeof(next_path), n, link_target, strlen(link_target));
} else {
ddnatv_copy_cstr(next_path, sizeof(next_path), link_target);
}
}
// proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name
const char *next_base = strrchr(next_path, '/');
next_base = next_base ? next_base + 1 : next_path;
if (strncmp(next_base, ".l2s.", 5) == 0) return;
resolve_symlinks(next_path, out, out_size, depth + 1);
}
+116
View File
@@ -0,0 +1,116 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
RECORDER = r"""
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int execve(const char *path, char *const argv[], char *const envp[]) {
const char *exe = "-";
for (int i = 0; envp && envp[i]; i++)
if (strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) exe = envp[i] + 16;
printf("exe\t%s\n", exe);
fflush(stdout);
_exit(0);
}
"""
PROBE = r"""
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc < 2) return 0;
char *args[] = {argv[1], NULL};
execv(argv[1], args);
perror("execv");
return 1;
}
"""
class NativeHookExecTargetTest(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 / "recorder.c").write_text(RECORDER)
cls.recorder = tmp / "recorder.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=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"
opt = cls.root / "opt"
(opt / "real").mkdir(parents=True)
(opt / "nest").mkdir()
(cls.root / "lib").mkdir()
(cls.root / "lib/ld-linux-aarch64.so.1").write_bytes(b"")
shutil.copy(cls.probe, opt / "real/prog")
shutil.copy(cls.probe, opt / "real/.l2s.prog0001")
os.symlink("./real", opt / "rel")
os.symlink("/opt/real", opt / "abs")
os.symlink("../rel", opt / "nest/sub")
os.symlink("rel/prog", opt / "link")
os.symlink(".l2s.prog0001", opt / "real/hard")
cls.real = str(opt / "real/prog")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def exe(self, program):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
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), program], env=env, capture_output=True, text=True, timeout=120)
for line in out.stdout.splitlines():
if line.startswith("exe\t"):
return line.split("\t", 1)[1]
self.fail(out.stdout + out.stderr)
def test_a_program_reached_through_a_relative_directory_link_is_named_by_its_real_path(self):
self.assertEqual(self.real, self.exe("/opt/rel/prog"))
def test_a_program_reached_through_a_guest_absolute_directory_link_is_named_by_its_real_path(self):
self.assertEqual(self.real, self.exe("/opt/abs/prog"))
def test_links_that_climb_with_dot_dot_resolve_like_the_kernel(self):
self.assertEqual(self.real, self.exe("/opt/nest/sub/./prog"))
def test_a_link_to_the_program_itself_still_resolves(self):
self.assertEqual(self.real, self.exe("/opt/link"))
def test_a_plain_path_is_unchanged(self):
self.assertEqual(self.real, self.exe("/opt/real/prog"))
def test_a_missing_directory_is_not_skipped_by_dot_dot(self):
self.assertNotEqual(self.real, self.exe("/opt/missing/../real/prog"))
def test_a_file_is_not_used_as_a_directory(self):
self.assertNotEqual(self.real, self.exe("/opt/real/prog/../prog"))
def test_a_proot_hard_link_keeps_its_own_name(self):
self.assertEqual(str(self.root / "opt/real/hard"), self.exe("/opt/real/hard"))
if __name__ == "__main__":
unittest.main()