From 31892c3be913149b2409226df5e8d1a59ad5be81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Mon, 12 Oct 2026 16:59:30 +0300 Subject: [PATCH] Sanitize root child environments and harden root-mode install Co-Authored-By: Codex Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- scripts/linux/tests/test_desktop_actions.py | 9 ++++--- .../linux/tests/test_install_root_helper.py | 8 ++++++ .../Elevation/RootStartupEnvironment.cs | 19 +++++++++++++ .../Launching/TracedProcess.cs | 4 +++ .../Theme/LinuxSystemAppearanceService.cs | 2 +- .../Windowing/CursorSettingsResolver.cs | 2 +- .../SystemIntegration/RootActionModeTests.cs | 27 +++++++++++++++++++ 7 files changed, 65 insertions(+), 6 deletions(-) diff --git a/scripts/linux/tests/test_desktop_actions.py b/scripts/linux/tests/test_desktop_actions.py index c90cdad8a97d..5b2b77a8b729 100644 --- a/scripts/linux/tests/test_desktop_actions.py +++ b/scripts/linux/tests/test_desktop_actions.py @@ -19,14 +19,15 @@ def test_portable_filters_preserve_following_groups(self): for script in ("packaging/linux/appimage/build-appimage.sh", f"packaging/linux/flatpak/{APP_ID}.yml"): expression = re.search(r"sed -i '([^']+)'", (REPO / script).read_text()).group(1) - for suffix in ("", following): + for suffix in ("", following, following + "\n[Desktop Action last]\nName=Last action\nExec=files %U\n"): fixture = desktop + "\n" + suffix expected = before_root.replace("root-mode;", "") + suffix if suffix: - fixture = fixture.replace("Actions=new-window;root-mode;", "Actions=new-window;root-mode;later;") - expected = expected.replace("Actions=new-window;", "Actions=new-window;later;") + actions = "later;last;" if "[Desktop Action last]" in suffix else "later;" + fixture = fixture.replace("Actions=new-window;root-mode;", "Actions=new-window;root-mode;" + actions) + expected = expected.replace("Actions=new-window;", "Actions=new-window;" + actions) for newline in ("\n", "\r\n"): - with self.subTest(script=script, following_group=bool(suffix), newline=repr(newline)): + with self.subTest(script=script, following_groups=suffix.count("[Desktop Action"), newline=repr(newline)): result = subprocess.run(["sed", expression], input=fixture.replace("\n", newline), text=True, capture_output=True, check=True) self.assertEqual(expected.strip(), result.stdout.strip()) diff --git a/scripts/linux/tests/test_install_root_helper.py b/scripts/linux/tests/test_install_root_helper.py index 2f4837c8d609..5b381a5ce926 100644 --- a/scripts/linux/tests/test_install_root_helper.py +++ b/scripts/linux/tests/test_install_root_helper.py @@ -96,6 +96,14 @@ def query(command, **kwargs): self.assertIn(f"{owned_path} is owned by a distro package", diagnostic.getvalue()) self.assertIn("omit --install-root-helper", diagnostic.getvalue()) snapshot.assert_not_called() + self.assertEqual(self.contents, self.helper.read_bytes()) + self.assertFalse(self.stage.exists()) + + def test_local_install_delegates_to_package_ownership_guard(self): + local = INSTALLER.with_name("install-local.sh").read_text() + self.assertIn('/usr/bin/sudo /usr/bin/python3 "$root/scripts/linux/install-root-helper.py"', local) + self.assertNotIn("/usr/lib/linuxfiles", local) + self.assertNotIn("/usr/share/polkit-1/actions", local) def test_unowned_paths_allow_tarball_helper_installation(self): with mock.patch.object(installer.os, "access", return_value=True), \ diff --git a/src/Files.Platform.Linux/Elevation/RootStartupEnvironment.cs b/src/Files.Platform.Linux/Elevation/RootStartupEnvironment.cs index 3f8ddd233ba4..3ef8f69a237e 100644 --- a/src/Files.Platform.Linux/Elevation/RootStartupEnvironment.cs +++ b/src/Files.Platform.Linux/Elevation/RootStartupEnvironment.cs @@ -4,6 +4,7 @@ using Files.Platform.Linux.Native; using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; namespace Files.Platform.Linux.Elevation @@ -24,6 +25,24 @@ public static void Apply() Environment.SetEnvironmentVariable(entry.Key, entry.Value); } + /// Keep only root storage, display connection and locale settings for child processes. + public static void ApplyChildEnvironment(ProcessStartInfo info, uint effectiveUserId, string rootHome) + { + if (effectiveUserId != 0) return; + var overrides = GetOverrides(rootHome); + var kept = new Dictionary(); + foreach (var name in new[] { "DISPLAY", "XAUTHORITY", "LANG", "LANGUAGE", "LC_ALL", + "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_MESSAGES", + "LC_PAPER", "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT", "LC_IDENTIFICATION" }) + { + if (info.Environment.TryGetValue(name, out var value)) kept[name] = value; + } + info.Environment.Clear(); + foreach (var entry in kept) info.Environment[entry.Key] = entry.Value; + foreach (var entry in overrides) + if (entry.Value is not null) info.Environment[entry.Key] = entry.Value; + } + public static IReadOnlyDictionary GetOverrides(string rootHome) { if (!Path.IsPathFullyQualified(rootHome) || rootHome == "/" || rootHome.Contains('\0')) diff --git a/src/Files.Platform.Linux/Launching/TracedProcess.cs b/src/Files.Platform.Linux/Launching/TracedProcess.cs index 1a87438560ea..4213ccc4deaf 100644 --- a/src/Files.Platform.Linux/Launching/TracedProcess.cs +++ b/src/Files.Platform.Linux/Launching/TracedProcess.cs @@ -2,6 +2,8 @@ // Licensed under the MIT License. using Files.Platform.Abstractions.Diagnostics; +using Files.Platform.Linux.Elevation; +using Files.Platform.Linux.Native; using System.Diagnostics; namespace Files.Platform.Linux.Launching @@ -10,6 +12,8 @@ internal static class TracedProcess { public static Process? Start(ProcessStartInfo info) { + if (ProcessIdentityNative.CurrentUserId == 0) + RootStartupEnvironment.ApplyChildEnvironment(info, 0, ElevationNative.HomeDirectory(0)); using var trace = PerformanceTrace.Begin("process-spawn"); return Process.Start(info); } diff --git a/src/Files.Platform.Linux/Theme/LinuxSystemAppearanceService.cs b/src/Files.Platform.Linux/Theme/LinuxSystemAppearanceService.cs index ee4f0b7c2c8d..0af92cb499b9 100644 --- a/src/Files.Platform.Linux/Theme/LinuxSystemAppearanceService.cs +++ b/src/Files.Platform.Linux/Theme/LinuxSystemAppearanceService.cs @@ -169,7 +169,7 @@ async Task AppendAsync(string path) { var info = new ProcessStartInfo("gsettings") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; foreach (var arg in new[] { "get", "org.gnome.desktop.interface", "gtk-theme" }) info.ArgumentList.Add(arg); - using var process = Process.Start(info); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(info); if (process is null) return null; try { diff --git a/src/Files.Platform.Linux/Windowing/CursorSettingsResolver.cs b/src/Files.Platform.Linux/Windowing/CursorSettingsResolver.cs index fcd3a81ebb00..aee6432111c1 100644 --- a/src/Files.Platform.Linux/Windowing/CursorSettingsResolver.cs +++ b/src/Files.Platform.Linux/Windowing/CursorSettingsResolver.cs @@ -100,7 +100,7 @@ text[0] is not ('\'' or '"') || text[^1] != text[0]) info.ArgumentList.Add("get"); info.ArgumentList.Add("org.gnome.desktop.interface"); info.ArgumentList.Add(key); - using var process = Process.Start(info); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(info); if (process is null) return null; diff --git a/tests/Files.Platform.Tests/SystemIntegration/RootActionModeTests.cs b/tests/Files.Platform.Tests/SystemIntegration/RootActionModeTests.cs index 9f2f0da19898..19da9f6a0340 100644 --- a/tests/Files.Platform.Tests/SystemIntegration/RootActionModeTests.cs +++ b/tests/Files.Platform.Tests/SystemIntegration/RootActionModeTests.cs @@ -6,6 +6,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; namespace Files.Platform.Tests.SystemIntegration @@ -78,6 +79,32 @@ public void RootEnvironmentReplacesInheritedDiscoveryAndExecutableOverrides(stri CollectionAssert.AreEqual(new[] { "/etc/xdg" }, new List(directories.ConfigDirs)); } + [TestMethod] + [DataRow(0u)] + [DataRow(1000u)] + public void ChildEnvironmentUsesKeepListOnlyForRoot(uint uid) + { + var info = new ProcessStartInfo("/usr/bin/env") { UseShellExecute = false }; + info.Environment.Clear(); + var rejected = new[] { "LD_PRELOAD", "LD_LIBRARY_PATH", "QT_PLUGIN_PATH", "GTK_MODULES", + "PYTHONPATH", "PERL5OPT", "BASH_ENV", "ENV", "UNKNOWN_FUTURE_INJECTION", "DBUS_SESSION_BUS_ADDRESS" }; + foreach (var name in rejected) info.Environment[name] = "untrusted"; + info.Environment["DISPLAY"] = ":99"; + info.Environment["XAUTHORITY"] = "/tmp/private-display-auth"; + info.Environment["LANG"] = "en_US.UTF-8"; + info.Environment["LC_MESSAGES"] = "C"; + info.Environment["HOME"] = "/home/user"; + info.Environment["PATH"] = "/home/user/bin"; + RootStartupEnvironment.ApplyChildEnvironment(info, uid, "/root"); + foreach (var name in rejected) Assert.AreEqual(uid != 0, info.Environment.ContainsKey(name), name); + Assert.AreEqual(":99", info.Environment["DISPLAY"]); + Assert.AreEqual("/tmp/private-display-auth", info.Environment["XAUTHORITY"]); + Assert.AreEqual("en_US.UTF-8", info.Environment["LANG"]); + Assert.AreEqual("C", info.Environment["LC_MESSAGES"]); + Assert.AreEqual(uid == 0 ? "/root" : "/home/user", info.Environment["HOME"]); + Assert.AreEqual(uid == 0 ? RootStartupEnvironment.GetOverrides("/root")["PATH"] : "/home/user/bin", info.Environment["PATH"]); + } + private sealed class Inspector : IFileOwnershipInspector { public Dictionary Entries { get; } = new()