fix(nativeguest): keep loader paths out of guest environment (#3147)

* fix(nativeguest): keep loader paths out of guest environment

* fix(nativeguest): preserve caller library search paths

* fix(nativeguest): preserve empty caller library path components
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-24 10:30:54 -05:00
1 parent caf16c8aa5
commit c298da6f60
5 files changed
+49 -27

No files matched your search

@@ -76,7 +76,6 @@ object NativeGuest {
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf( fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
"DDNATV_ROOT" to root.path, "DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(), "DDNATV_EXEC" to execLoader.orEmpty(),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() } ).filterValues { it.isNotEmpty() }
@@ -84,10 +83,10 @@ object NativeGuest {
* The host command line for the guest program at [program] (an absolute guest path to a real * The host command line for the guest program at [program] (an absolute guest path to a real
* file, not a symlink). * file, not a symlink).
*/ */
fun command(root: File, program: String, args: List<String>): List<String> { fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" } val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/")) val host = File(root, program.removePrefix("/"))
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch) return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
} }
@@ -100,7 +99,6 @@ object NativeGuest {
"DDNATV_HOSTNAME" to hostname.orEmpty(), "DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" }, "DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"), "DDNATV_PRELOAD" to preload.joinToString(":"),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() } ).filterValues { it.isNotEmpty() }
} }
@@ -273,7 +271,9 @@ object NativeGuest {
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder { fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
val program = argv.first() val program = argv.first()
val cmd = command(root, program, argv.drop(1)) val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty()
val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs }
val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":"))
val builder = ProcessBuilder(cmd).redirectErrorStream(false) val builder = ProcessBuilder(cmd).redirectErrorStream(false)
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root) builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
builder.environment().apply { builder.environment().apply {
@@ -44,7 +44,36 @@ class NativeGuestTest {
val root = rootWithLoader() val root = rootWithLoader()
val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1")) val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1"))
assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0]) assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0])
assertEquals(listOf("--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1)) assertEquals(listOf("--library-path", NativeGuest.libraryPath(root), "--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1))
assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root))
}
@Test
fun builderKeepsCallerLibraryPathAheadOfRootfsDirectories() {
val root = rootWithLoader()
val rootDirs = NativeGuest.libraryPath(root).split(':')
val callerPath = "/custom/lib:${rootDirs[1]}:/other/lib"
val builder = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), mapOf("LD_LIBRARY_PATH" to callerPath))
val command = builder.command()
assertEquals(listOf("/custom/lib", rootDirs[1], "/other/lib") + rootDirs.filterNot { it == rootDirs[1] },
command[command.indexOf("--library-path") + 1].split(':'))
assertEquals(callerPath, builder.environment()["LD_LIBRARY_PATH"])
}
@Test
fun builderPreservesEmptyCallerLibraryPathComponents() {
val root = rootWithLoader()
val rootPath = NativeGuest.libraryPath(root)
for (callerPath in listOf(":/custom/lib", "/custom/lib:", ":/custom/lib::")) {
val builder = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), mapOf("LD_LIBRARY_PATH" to callerPath))
val command = builder.command()
assertEquals("$callerPath:$rootPath", command[command.indexOf("--library-path") + 1])
assertEquals(callerPath, builder.environment()["LD_LIBRARY_PATH"])
}
for (env in listOf(emptyMap(), mapOf("LD_LIBRARY_PATH" to ""))) {
val command = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), env).command()
assertEquals(rootPath, command[command.indexOf("--library-path") + 1])
}
} }
@Test @Test
@@ -53,6 +82,7 @@ class NativeGuestTest {
val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b")) val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"))
assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"]) assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"])
assertEquals(root.path, env["DDNATV_ROOT"]) assertEquals(root.path, env["DDNATV_ROOT"])
assertTrue("LD_LIBRARY_PATH" !in env)
assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so")) assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so"))
} }
-15
View File
@@ -76,7 +76,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
init_ddnatv_hook(); init_ddnatv_hook();
int count = 0; int count = 0;
int has_preload = 0; int has_preload = 0;
int has_ld_library_path = 0;
int has_root = 0; int has_root = 0;
int has_tunables = 0; int has_tunables = 0;
int has_path = 0; int has_path = 0;
@@ -104,7 +103,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
switch (e[0]) { switch (e[0]) {
case 'L': case 'L':
if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; } if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; }
else if (strncmp(e, "LD_LIBRARY_PATH=", 16) == 0) has_ld_library_path = 1;
break; break;
case 'G': case 'G':
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1; if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
@@ -217,19 +215,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
new_env[dst++] = str; new_env[dst++] = str;
} }
} }
if (!has_ld_library_path && g_ddnatv_root[0] != '\0') {
size_t size = 16 + 1;
for (size_t i = 0; i < sizeof(k_rootfs_lib_dirs) / sizeof(k_rootfs_lib_dirs[0]); i++) {
char dir[PATH_MAX];
size += 1 + strlen(rewrite_path_in_root(k_rootfs_lib_dirs[i], dir, sizeof(dir)));
}
char *str = malloc(size);
if (str) {
size_t n = ddnatv_append(str, size, 0, "LD_LIBRARY_PATH=", 16);
append_rootfs_lib_dirs(str, size, n, 0);
new_env[dst++] = str;
}
}
if (!has_root && g_ddnatv_root[0] != '\0') { if (!has_root && g_ddnatv_root[0] != '\0') {
char *str = malloc(PATH_MAX + 16); char *str = malloc(PATH_MAX + 16);
if (str) { if (str) {
-5
View File
@@ -755,11 +755,6 @@ static size_t append_rootfs_lib_dirs_missing_from(char *out, size_t outsz, size_
return used; return used;
} }
// All of them.
static size_t append_rootfs_lib_dirs(char *out, size_t outsz, size_t used, int separate) {
return append_rootfs_lib_dirs_missing_from(out, outsz, used, separate, NULL);
}
#ifndef DDNATV_HOST_TEST #ifndef DDNATV_HOST_TEST
// Relative *at() calls. A program that walks a path one component at a time (systemd's chase(), used // Relative *at() calls. A program that walks a path one component at a time (systemd's chase(), used
// by libudev; fts) opens "/" and then "sys", "class", ... relative to the last descriptor, and those // by libudev; fts) opens "/" and then "sys", "class", ... relative to the last descriptor, and those
+13 -1
View File
@@ -27,6 +27,7 @@ static void show(const char *path, char *const argv[], char *const envp[]) {
printf("\n"); printf("\n");
for (int i = 0; envp && envp[i]; i++) 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); if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20);
else if (strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) printf("envpath\t%s\n", envp[i] + 16);
fflush(stdout); fflush(stdout);
} }
@@ -124,12 +125,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
def tearDownClass(cls): def tearDownClass(cls):
cls.tmp.cleanup() cls.tmp.cleanup()
def call(self, how, *argv, binds=None, real_exe=None): def call(self, how, *argv, binds=None, real_exe=None, ld_library_path=None):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
if binds: if binds:
hook_env["DDNATV_BINDS"] = binds hook_env["DDNATV_BINDS"] = binds
if real_exe: if real_exe:
hook_env["DDNATV_REAL_EXE"] = real_exe hook_env["DDNATV_REAL_EXE"] = real_exe
if ld_library_path is not None:
hook_env["LD_LIBRARY_PATH"] = ld_library_path
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")}
if self.prefix: if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
@@ -139,6 +142,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) 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")] 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.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")]
self.env_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("envpath\t")]
self.assertEqual(1, len(calls), out.stdout + out.stderr) self.assertEqual(1, len(calls), out.stdout + out.stderr)
if how == "spawn": if how == "spawn":
self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr)
@@ -167,6 +171,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): 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")) self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x"))
def test_guest_library_environment_is_preserved(self):
for how in ("exec", "spawn"):
for value in (None, "", "/custom/lib:/other/lib"):
with self.subTest(how=how, value=value):
argv = self.call(how, GUEST_TOOL, ld_library_path=value)[1:]
self.assertEqual([] if value is None else [value], self.env_paths)
self.assertIn(str(self.root / "usr/lib/aarch64-linux-gnu"), argv[argv.index("--library-path") + 1])
def test_a_program_started_through_ldso_records_its_library_path(self): def test_a_program_started_through_ldso_records_its_library_path(self):
for how in ("exec", "spawn"): for how in ("exec", "spawn"):
with self.subTest(how=how): with self.subTest(how=how):