Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions scripts/linux/tests/test_desktop_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
8 changes: 8 additions & 0 deletions scripts/linux/tests/test_install_root_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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), \
Expand Down
19 changes: 19 additions & 0 deletions src/Files.Platform.Linux/Elevation/RootStartupEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -24,6 +25,24 @@ public static void Apply()
Environment.SetEnvironmentVariable(entry.Key, entry.Value);
}

/// <summary>Keep only root storage, display connection and locale settings for child processes.</summary>
public static void ApplyChildEnvironment(ProcessStartInfo info, uint effectiveUserId, string rootHome)
{
if (effectiveUserId != 0) return;
var overrides = GetOverrides(rootHome);
var kept = new Dictionary<string, string?>();
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<string, string?> GetOverrides(string rootHome)
{
if (!Path.IsPathFullyQualified(rootHome) || rootHome == "/" || rootHome.Contains('\0'))
Expand Down
4 changes: 4 additions & 0 deletions src/Files.Platform.Linux/Launching/TracedProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -78,6 +79,32 @@ public void RootEnvironmentReplacesInheritedDiscoveryAndExecutableOverrides(stri
CollectionAssert.AreEqual(new[] { "/etc/xdg" }, new List<string>(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<string, FileEntryInfo> Entries { get; } = new()
Expand Down
Loading