diff --git a/.github/README.md b/.github/README.md index 8a64ce2086e4..05ed7097674d 100644 --- a/.github/README.md +++ b/.github/README.md @@ -30,7 +30,7 @@ Grab the assets from the [0.1.0-alpha2 release page](https://github.com/MemerGam yay -S linuxfiles-bin # or: paru -S linuxfiles-bin ``` -This is the only format that also installs the polkit helper for the optional [root actions](#root-actions). +This installs the polkit helper for optional [root actions](#root-actions); polkit and a session authentication agent are required. ### Nix / NixOS @@ -39,7 +39,17 @@ nix run github:MemerGamer/LinuxFiles # try it nix profile install github:MemerGamer/LinuxFiles ``` -The flake also exports `overlays.default` (adds `pkgs.linuxfiles`). It repackages the release tarball for x86_64-linux and does not include the polkit helper, and all [root actions](#root-actions) are off in this package. +The flake exports `overlays.default` (adds `pkgs.linuxfiles`) and `nixosModules.default`. Plain `nix run`/profile installs keep all [root actions](#root-actions) disabled. NixOS administrators can import the module and opt in: + +```nix +# Add inputs.linuxfiles.nixosModules.default to your NixOS modules. +programs.linuxfiles = { + enable = true; + rootActions = true; # default: false +}; +``` + +This installs a patched helper, a matching polkit action and trusted deployment manifest, and enables the pkexec wrapper. A session authentication agent is required. The current alpha2 release pin predates this runtime support: root file operations need the next release containing it and updated flake hashes. See [Nix packaging details](../docs/linux-port/packaging.md#nix-flake). ### AppImage @@ -49,6 +59,8 @@ chmod +x Files-x86_64.AppImage ./Files-x86_64.AppImage ``` +Root actions remain disabled in the AppImage. Administrators can separately [provision a matching native host helper](../docs/linux-port/packaging.md#companion-host-helper-opt-in-appimage--flatpak), but this alone does not enable AppImage elevation. + ### Flatpak bundle ```sh @@ -56,7 +68,7 @@ flatpak install --user Files-x86_64.flatpak flatpak run io.github.memergamer.LinuxFiles ``` -The bundle needs the `org.freedesktop.Platform//25.08` runtime; Flatpak offers to install it from Flathub. +The bundle needs the `org.freedesktop.Platform//25.08` runtime; Flatpak offers to install it from Flathub. Root actions remain disabled. An optional [companion host-helper installer](../docs/linux-port/packaging.md#companion-host-helper-opt-in-appimage--flatpak) provisions the native host only; this bundle has no host-spawn bridge and keeps its sandbox permissions unchanged. ### Tarball @@ -77,7 +89,7 @@ scripts/linux/install-local.sh --from /path/to/linux-x64 ### Root actions -Optional. **Open in terminal as root** works everywhere (it asks your terminal elevation tool: run0, sudo or pkexec). The polkit-authenticated Delete/Rename/Paste-as-root actions need the root helper, which only the AUR package installs; they are off in the AppImage and Flatpak. Start a root-mode window with: +Optional. **Open in terminal as root** uses a trusted run0, sudo or pkexec in native packages that allow elevation. Polkit-authenticated Delete/Rename/Paste-as-root requires the installed trusted helper: AUR, an opted-in local tarball install, or the NixOS module with a release containing its runtime support. AppImage, Flatpak and plain `nix run` keep all root actions disabled. In a supported native installation, start a root-mode window with: ```sh files --root diff --git a/docs/linux-port/packaging.md b/docs/linux-port/packaging.md index 9535a5e32803..d7048efb7286 100644 --- a/docs/linux-port/packaging.md +++ b/docs/linux-port/packaging.md @@ -17,6 +17,7 @@ App id (used everywhere): `io.github.memergamer.LinuxFiles`. Binary/launcher: `f | `scripts/linux/build-flatpak.sh`, `gen-aur.sh` | Build the Flatpak bundle; render PKGBUILD + `.SRCINFO` with real checksums. | | `scripts/linux/publish.sh` | `dotnet publish` to `artifacts/linux-/`. | | `scripts/linux/install-local.sh`, `uninstall-local.sh` | User-local install into `~/.local`. | +| `scripts/linux/install-host-root-helper.py` | Explicit companion host-helper install from a matching native release; does not alter sandbox permissions. | | `scripts/linux/gen-icons.sh` | Regenerates the icons. | | `flake.nix`, `scripts/linux/update-nix-flake.sh` | Nix flake (repackages the release tarball); the script bumps version and hashes. | | `.github/workflows/package-linux.yml` | Manual / `linux-v*` tag: publish, AppImage, Flatpak, AUR recipe; tags also create a GitHub release. | @@ -148,7 +149,24 @@ First used for `linux-v0.1.0-alpha1` (prerelease; install instructions are in `. ## Nix flake -`flake.nix` (with `flake.lock`, pinned to `nixos-unstable`) exposes `packages.x86_64-linux.{linuxfiles,default}`, `apps.x86_64-linux.default` and `overlays.default` (adds `pkgs.linuxfiles`). There is no NixOS module. The derivation `fetchurl`s the release's `files-linux-x64.tar.gz` and `files-packaging.tar.gz` (pinned version and SRI hashes), patches the ELF files with `autoPatchelfHook`, and installs like the AUR package: app in `$out/lib/linuxfiles`, a `makeWrapper` `bin/files`, desktop entry, metainfo, icons and licence. The libraries that are loaded with dlopen (fontconfig, freetype, libGL, libX11/Xcursor/Xrandr/Xi/Xext, ICU, OpenSSL, zlib, krb5, glib) are added to every ELF file's runpath through `appendRunpaths`; the wrapper sets no library environment variables, so programs the app starts do not inherit Nix libraries. The LTTng tracing provider (`libcoreclrtraceptprovider.so`) is left unsatisfied on purpose. The polkit root helper and policy are not packaged, and the package installs the `.root-actions-disabled` marker next to `Files` (the same gate the AppImage and Flatpak use), so all root actions, including "Open in terminal as root", are off. That item would not work on NixOS anyway: the trusted tool resolver only looks in `/usr/bin` and `/bin`, while NixOS keeps setuid wrappers (sudo, pkexec) in `/run/wrappers/bin`. +`flake.nix` (with `flake.lock`, pinned to `nixos-unstable`) exposes `packages.x86_64-linux.{linuxfiles,default}`, `apps.x86_64-linux.default`, `overlays.default` (adds `pkgs.linuxfiles`), and `nixosModules.default`. The package repackages the pinned release tarballs, patches all ELF files with `autoPatchelfHook` (including the retained Native AOT helper), and installs the app under `$out/lib/linuxfiles`. Runtime dlopen libraries are added to ELF runpaths rather than the launch environment, so child programs do not inherit Nix libraries. The unused CoreCLR LTTng tracing provider remains exempt from dependency checking. + +Plain `nix run` and `nix profile install` retain `.root-actions-disabled`: all root actions remain off. Installing a profile cannot activate host polkit. NixOS administrators may opt in through their configuration flake once a compatible runtime is packaged (the current alpha2 pin rejects this opt-in): + +```nix +# inputs.linuxfiles.url = "github:MemerGamer/LinuxFiles"; +# Add inputs.linuxfiles.nixosModules.default to nixosSystem.modules, then: +programs.linuxfiles = { + enable = true; + rootActions = true; # default: false +}; +``` + +The module selects the package's `enableRootActions` variant, removes its disable marker, enables `security.polkit`, and installs a generated action in `share/polkit-1/actions`. Its `exec.path` names exactly the invoked store helper, never a mutable profile alias. `/etc/linuxfiles/root-actions` is a root-controlled two-line deployment manifest (helper path, policy path, final newline). Discovery checks every manifest symlink traversal, immutable root-owned store entries, executable permissions, and the action's path and fresh `auth_admin` defaults. No user environment variable selects a helper or manifest. A changed helper path between preview and execution rejects the old confirmation; a malformed deployment never falls back to a native helper or a generic prompt. + +`pkexec` uses `/run/wrappers/bin` before the system profile and `/usr/bin`/`/bin`. The module enables `security.polkit.enablePkexecWrapper` when present; older nixpkgs uses `security.wrappers.pkexec`. Only pkexec is setuid, never the LinuxFiles helper. A session authentication agent and an administrator identity are still required. The narrow store exception accepts a root-owned sticky `/nix/store` with group write (1775), but rejects other write there, non-root ownership, and any writable entries beneath it. Native `/usr` helper/policy checks retain their existing restrictions. + +**Release integration:** the current pin is still `0.1.0-alpha2`, whose app predates deployment-manifest and Nix elevation-wrapper discovery. Its `passthru.supportsNixRootActions` marker is false, so the module rejects `rootActions = true` with an assertion. Packages without the marker are also rejected. Keep root actions disabled until a native release containing both runtime changes is published; update the version/hashes below and set the package marker to true only for that compatible release. Per release (after CI has attached `SHA256SUMS`; the flake's tag is `linux-v`): @@ -159,7 +177,7 @@ scripts/linux/update-nix-flake.sh X.Y.Z[-pre] SHA256SUMS # rewrites version + Commit `flake.nix` in a PR. It is deliberately not a CI step: the hashes only exist after the release job has uploaded the assets, and `main` takes changes through PRs. Run `nix flake update` separately to bump nixpkgs. -Verification so far: `nix flake check --no-build` and `nix build` succeeded on x86_64-linux with `nix-portable` (Nix 2.20, nixpkgs `e7439b6`), so evaluation, hashes and the autoPatchelf dependency check pass. The package has not been run (no GUI test on a Nix system), so a missing dlopen library would only show at runtime; report such cases as issues. +The earlier plain package passed `nix flake check --no-build` and `nix build` with nix-portable. The `checks.x86_64-linux.root-actions-module` check covers rejection of the incompatible pin and packages without the capability marker, opt-out defaults, and a marked fixture for compatible-runtime module wiring. When built, it also checks helper presence, marker state, and the generated policy path; the fixture does not establish alpha2 runtime compatibility. Re-run `nix flake check` against the locked revision after the release bump; sandboxed DNS failures cannot establish NixOS evaluation or packaged loader startup. See the headless checklist below. ## Nightly builds @@ -194,8 +212,31 @@ Native AUR packages install a root-owned Native AOT helper at `/usr/lib/linuxfil For local installation, publish normally and opt in with `scripts/linux/install-local.sh --install-root-helper`. This separately runs `sudo python3 scripts/linux/install-root-helper.py --from artifacts/linux-x64/elevation-helper --sha256 `; the app stays in the user prefix. This is equivalent to `sudo make install`: trust the installer checkout and build output. The policy is embedded; a private root-owned helper snapshot is hashed and checked before installation. Before writing system files, the installer queries available `/usr/bin/pacman -Qo`, `/usr/bin/dpkg-query -S`, and `/usr/bin/rpm -qf` tools for ownership of `/usr/lib/linuxfiles`, the helper, and the policy. It refuses to overwrite package-owned paths: omit `--install-root-helper` and use the distro package's helper instead. Tarball users without package-owned paths keep the same `/usr/lib/linuxfiles/files-elevation-helper` and `/usr/share/polkit-1/actions/` installation; the launcher and app's fixed helper/policy trust checks remain compatible. To inspect the package layout without privileges, run `python3 scripts/linux/install-root-helper.py --from --sha256 --destdir `. Remove the system helper and policy as administrator when uninstalling; the user-local uninstaller intentionally cannot remove system files. -AppImage and Flatpak omit the helper and the **Open in Root Mode** desktop action, install no policy, and disable Root actions. They cannot supply host elevation, even when the native helper is installed separately. See [the elevation threat model](threat-model-elevation.md) for protocol, failure semantics and limitations. +### Companion host-helper opt-in (AppImage / Flatpak) + +AppImage and Flatpak omit the helper and **Open in Root Mode** desktop action, and retain their full elevation disable gates. A separately installed host helper is an administrator opt-in for native host integration; installing it does **not** enable root actions in either current format. No sandbox permission or runtime gate is changed here. Flatpak still has no `org.freedesktop.Flatpak` permission and no `flatpak-spawn --host` bridge. AppImage still refuses its user-controlled extraction directory for privileged helpers. + +To provision only the host helper, verify and unpack the **matching native tarball** from the same release (the helper is not in the AppImage or Flatpak). Verify the tarball against the release `SHA256SUMS`, inspect the trusted installer checkout, and record the approved helper digest: + +```sh +sha256sum -- /path/to/linux-x64/elevation-helper/files-elevation-helper +python3 scripts/linux/install-host-root-helper.py --from /path/to/linux-x64 --sha256 +``` + +The companion script invokes the existing hardened installer through literal argv and sudo. It installs only `/usr/lib/linuxfiles/files-elevation-helper` (0755, never setuid) and the fixed-path policy (0644), verifies a private snapshot and digest, and refuses package-owned destinations. NixOS users must use the module instead of this `/usr` layout. For inspection without privileges, add `--destdir /tmp/linuxfiles-helper-stage`. Re-run explicitly for each matching release update; remove those two system files as administrator when retiring a manually installed helper. No installer grants persistent polkit authorization or changes the user's desktop settings. + +For root file operations today, run the matching native tarball/local install or enabled NixOS package. A future AppImage host discovery path or Flatpak transport needs separate implementation and review; a host helper alone is insufficient. See [the elevation threat model](threat-model-elevation.md) for protocol, failure semantics and limitations. Normal launches show only **Root actions → Open in terminal as root**, independently of helper installation; authentication happens through the terminal elevation tool. Launch `files --root` or choose **Open in Root Mode** from the desktop entry to additionally show Delete/Rename/Paste as root when the trusted helper is installed. Each action requests polkit authentication; the GUI remains unprivileged. Tabs and the title show **(Root mode)** only when helper actions are allowed by the package/disable gates. Each `--root` invocation opens its own process/window and bypasses normal single-instance forwarding, so an existing ordinary window never acquires root mode. **New Window** preserves `--root`. These separate processes never claim FileManager1. For an actual uid-0 launch (`sudo files`), tabs/title show **(Running as root)**, ordinary operations already run as root, and all helper/root-terminal actions are hidden. The normal terminal command remains available. Before app initialization, HOME and XDG config/data/cache/state are reset to root's account home/defaults; XDG_DATA_DIRS and XDG_CONFIG_DIRS are reset to `/usr/local/share:/usr/share` and `/etc/xdg`, and PATH to `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`. Inherited TERMINAL, EDITOR, VISUAL, BROWSER, SHELL, XDG_CURRENT_DESKTOP, user runtime/session-bus, GVfs and TMPDIR overrides are cleared. Unsafe root-owned directory configuration aborts startup before settings writes. This also protects the invoking user's settings when sudo preserves HOME or XDG variables. AppImage/Flatpak retain their full elevation disable gate, including the root-terminal item, even with `--root`, and show no root-mode indicator when helper actions are disabled. + +### Pending headless verification for Nix root actions + +Run app checks only with `FILES_SANDBOX_DRIVES=scripts/linux/showcase-drives.txt scripts/linux/headless-run.sh` (private Xvfb and throwaway HOME); never use the real display. The harness blocks the system bus, so authentication and privileged operations additionally require a disposable NixOS VM with private Xvfb, a controlled polkit agent, and disposable test files. + +- Plain Nix launch and `--root`: marker keeps all root actions and the root-mode indicator hidden. Enabled NixOS `files --root`: root-mode title/tabs, Delete/Rename/Paste menus and independent root-terminal action appear while GUI uid remains unprivileged; ordinary launch stays outside helper mode. +- Packaged helper starts with the runner's cleared environment: its patched loader and dependencies work, and polkit selects the action whose `exec.path` exactly matches the displayed/invoked store helper. Root-terminal elevation selects the trusted Nix wrapper. +- Confirmation shows the exact helper, sanitized paths/operation, stdin JSON summary and request SHA-256. Cancel/dismiss leaves files unchanged; approved delete, rename, copy and move on disposable protected files report complete/partial results correctly. +- Switch NixOS generations while a dialog is open: the old helper confirmation refuses execution; a fresh plan shows and uses the new helper/action. Disabling the module or breaking helper/policy/manifest trust keeps helper actions unavailable without fallback. +- AppImage and Flatpak with the companion installed still hide all root actions and root-mode indicators, including `--root`; ordinary browsing and existing portals continue working with unchanged sandbox permissions. diff --git a/flake.nix b/flake.nix index d5cedd2a10de..5a2abf83a12c 100644 --- a/flake.nix +++ b/flake.nix @@ -14,7 +14,7 @@ linuxfiles = final.callPackage ({ lib, stdenv, fetchurl, autoPatchelfHook, makeWrapper , fontconfig, freetype, libGL, libx11, libxcursor, libxrandr, libxi, libxext - , icu, openssl, zlib, krb5, glib }: + , icu, openssl, zlib, krb5, glib, enableRootActions ? false }: let # version and both hashes are rewritten by scripts/linux/update-nix-flake.sh version = "0.1.0-alpha2"; @@ -37,6 +37,8 @@ stdenv.mkDerivation { pname = "linuxfiles"; inherit version; + # Set true only after pinning a release with NixOS helper/tool discovery. + passthru.supportsNixRootActions = false; dontUnpack = true; dontConfigure = true; @@ -60,9 +62,18 @@ mkdir -p $out/lib/linuxfiles $out/bin cp -a app/. $out/lib/linuxfiles/ - # The polkit root helper is not packaged for Nix; the marker turns all root actions off. - rm -rf $out/lib/linuxfiles/elevation-helper - touch $out/lib/linuxfiles/.root-actions-disabled + # Keep the AOT helper so autoPatchelf patches its loader and dependencies too. + test -x $out/lib/linuxfiles/elevation-helper/files-elevation-helper + ${if enableRootActions then '' + rm -f $out/lib/linuxfiles/.root-actions-disabled + install -Dm644 ${./packaging/linux/io.github.memergamer.LinuxFiles.root-actions.policy} \ + $out/share/polkit-1/actions/${id}.root-actions.policy + substituteInPlace $out/share/polkit-1/actions/${id}.root-actions.policy \ + --replace-fail /usr/lib/linuxfiles/files-elevation-helper \ + $out/lib/linuxfiles/elevation-helper/files-elevation-helper + '' else '' + touch $out/lib/linuxfiles/.root-actions-disabled + ''} # No library environment: it would leak into programs the app starts. makeWrapper $out/lib/linuxfiles/Files $out/bin/files @@ -89,6 +100,112 @@ { }; }; + nixosModules.default = { config, lib, pkgs, options, ... }: + let + cfg = config.programs.linuxfiles; + package = cfg.package.override { enableRootActions = cfg.rootActions; }; + helper = "${package}/lib/linuxfiles/elevation-helper/files-elevation-helper"; + policy = "${package}/share/polkit-1/actions/io.github.memergamer.LinuxFiles.root-actions.policy"; + in + { + options.programs.linuxfiles = { + enable = lib.mkEnableOption "LinuxFiles"; + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.linuxfiles; + description = "LinuxFiles package accepting the enableRootActions override."; + }; + rootActions = lib.mkEnableOption "polkit-authenticated LinuxFiles root operations"; + }; + config = lib.mkIf cfg.enable (lib.mkMerge [ + { + environment.systemPackages = [ package ]; + assertions = [{ + assertion = !cfg.rootActions || (package.passthru.supportsNixRootActions or false); + message = "programs.linuxfiles.rootActions requires a runtime with NixOS deployment-manifest and elevation-wrapper discovery (passthru.supportsNixRootActions = true). Disable rootActions or select a compatible package; the pinned alpha2 release is incompatible."; + }]; + } + (lib.mkIf cfg.rootActions (lib.mkMerge [ + { + security.polkit.enable = true; + environment.etc."linuxfiles/root-actions".text = "${helper}\n${policy}\n"; + } + # Older nixpkgs creates pkexec with polkit.enable; newer revisions gate it separately. + (if options.security.polkit ? enablePkexecWrapper then { + security.polkit.enablePkexecWrapper = true; + } else { + security.wrappers.pkexec = { + source = "${pkgs.polkit.bin}/bin/pkexec"; + owner = "root"; + group = "root"; + setuid = true; + }; + }) + ])) + ]); + }; + + checks.${system}.root-actions-module = + let + # This fixture checks module/layout wiring, not the pinned runtime's capabilities. + compatible = self.packages.${system}.linuxfiles.overrideAttrs (old: { + passthru = (old.passthru or { }) // { supportsNixRootActions = true; }; + }); + unsupported = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ self.nixosModules.default { + programs.linuxfiles.enable = true; + programs.linuxfiles.rootActions = true; + } ]; + }; + unmarked = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ self.nixosModules.default { + programs.linuxfiles.enable = true; + programs.linuxfiles.rootActions = true; + programs.linuxfiles.package = compatible.overrideAttrs (old: { + passthru = builtins.removeAttrs old.passthru [ "supportsNixRootActions" ]; + }); + } ]; + }; + capabilityAssertion = evaluated: + nixpkgs.lib.findFirst + (entry: nixpkgs.lib.hasPrefix "programs.linuxfiles.rootActions requires" entry.message) + (throw "Missing root-actions runtime assertion") evaluated.config.assertions; + enabled = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ self.nixosModules.default { + programs.linuxfiles.enable = true; + programs.linuxfiles.rootActions = true; + programs.linuxfiles.package = compatible; + } ]; + }; + disabled = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ self.nixosModules.default { programs.linuxfiles.enable = true; } ]; + }; + # Pick our package explicitly; other modules also add system packages. + package = compatible.override { enableRootActions = true; }; + in + assert !(capabilityAssertion unsupported).assertion; + assert !(capabilityAssertion unmarked).assertion; + assert (capabilityAssertion enabled).assertion; + assert (capabilityAssertion disabled).assertion; + assert enabled.config.security.polkit.enable; + assert enabled.config.security.wrappers.pkexec.setuid; + assert enabled.config.environment.etc."linuxfiles/root-actions".text == + "${package}/lib/linuxfiles/elevation-helper/files-elevation-helper\n${package}/share/polkit-1/actions/io.github.memergamer.LinuxFiles.root-actions.policy\n"; + assert !(disabled.config.environment.etc ? "linuxfiles/root-actions"); + assert !disabled.config.security.polkit.enable; + pkgs.runCommand "linuxfiles-root-actions-layout" { } '' + test -x ${package}/lib/linuxfiles/elevation-helper/files-elevation-helper + test ! -e ${package}/lib/linuxfiles/.root-actions-disabled + grep -F '${package}/lib/linuxfiles/elevation-helper/files-elevation-helper' \ + ${package}/share/polkit-1/actions/io.github.memergamer.LinuxFiles.root-actions.policy + test -e ${self.packages.${system}.linuxfiles}/lib/linuxfiles/.root-actions-disabled + touch $out + ''; + packages.${system} = { linuxfiles = pkgs.linuxfiles; default = pkgs.linuxfiles; diff --git a/scripts/linux/install-host-root-helper.py b/scripts/linux/install-host-root-helper.py new file mode 100755 index 000000000000..e2524a681cbd --- /dev/null +++ b/scripts/linux/install-host-root-helper.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# Copyright (c) Files Community. Licensed under the MIT License. +"""Opt in to a host-only helper install from a verified matching native release. + +This does not enable root actions inside AppImage or Flatpak. Trust the checkout +and published build as for sudo make install; supply the approved helper digest. +""" +import argparse +from pathlib import Path +import subprocess + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--from", dest="source", type=Path, required=True, + help="unpacked native release directory (containing elevation-helper)") + parser.add_argument("--sha256", required=True, help="approved SHA-256 of files-elevation-helper") + parser.add_argument("--destdir", type=Path, help="stage without sudo or host system changes") + args = parser.parse_args(argv) + if len(args.sha256) != 64 or any(c not in "0123456789abcdefABCDEF" for c in args.sha256): + parser.error("expected a SHA-256 hex digest") + if args.destdir is not None and args.destdir.resolve() == Path("/"): + parser.error("omit --destdir to opt into a live administrator installation") + installer = Path(__file__).resolve().with_name("install-root-helper.py") + command = ["/usr/bin/python3", str(installer), "--from", str(args.source.resolve() / "elevation-helper"), + "--sha256", args.sha256] + if args.destdir is not None: + command += ["--destdir", str(args.destdir.resolve())] + else: + command = ["/usr/bin/sudo"] + command + subprocess.run(command, check=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/linux/tests/test_host_root_helper.py b/scripts/linux/tests/test_host_root_helper.py new file mode 100644 index 000000000000..d77071e7a5ac --- /dev/null +++ b/scripts/linux/tests/test_host_root_helper.py @@ -0,0 +1,42 @@ +# Copyright (c) Files Community. Licensed under the MIT License. +"""Verify companion installation argv without running sudo or changing the host.""" +import importlib.util +from pathlib import Path +import subprocess +import unittest +from unittest import mock + +SCRIPT = Path(__file__).resolve().parents[1] / "install-host-root-helper.py" +spec = importlib.util.spec_from_file_location("host_helper_installer", SCRIPT) +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) + + +class HostInstallerTests(unittest.TestCase): + def test_live_install_requires_explicit_digest_and_uses_literal_argv(self): + source = Path("/tmp/release ; $HOME") + digest = "a" * 64 + with mock.patch.object(installer.subprocess, "run") as run: + installer.main(["--from", str(source), "--sha256", digest]) + run.assert_called_once_with([ + "/usr/bin/sudo", "/usr/bin/python3", str(SCRIPT.resolve().with_name("install-root-helper.py")), + "--from", str(source / "elevation-helper"), "--sha256", digest], check=True) + + def test_staging_never_invokes_sudo(self): + with mock.patch.object(installer.subprocess, "run") as run: + installer.main(["--from", "/tmp/release", "--sha256", "a" * 64, "--destdir", "/tmp/staging"]) + command = run.call_args.args[0] + self.assertEqual("/usr/bin/python3", command[0]) + self.assertEqual(["--destdir", "/tmp/staging"], command[-2:]) + self.assertNotIn("shell", run.call_args.kwargs) + + def test_invalid_digest_and_root_staging_never_invoke_installer(self): + for arguments in (["--sha256", "not-a-hash"], ["--sha256", "a" * 64, "--destdir", "/"]): + with mock.patch.object(installer.subprocess, "run") as run, self.assertRaises(SystemExit): + installer.main(["--from", "/tmp/release"] + arguments) + run.assert_not_called() + + def test_installation_failure_is_not_reported_as_success(self): + with mock.patch.object(installer.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "installer")): + with self.assertRaises(subprocess.CalledProcessError): + installer.main(["--from", "/tmp/release", "--sha256", "a" * 64]) diff --git a/src/Files.Platform.Linux/Elevation/ElevationDeploymentPolicy.cs b/src/Files.Platform.Linux/Elevation/ElevationDeploymentPolicy.cs new file mode 100644 index 000000000000..f763f035daa1 --- /dev/null +++ b/src/Files.Platform.Linux/Elevation/ElevationDeploymentPolicy.cs @@ -0,0 +1,35 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; + +namespace Files.Platform.Linux.Elevation +{ + internal static class ElevationDeploymentPolicy + { + internal static bool Matches(string text, string helper) + { + if (text.Length > 8192) return false; + using var reader = XmlReader.Create(new StringReader(text), new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Ignore, XmlResolver = null, MaxCharactersInDocument = 8192, + }); + var document = XDocument.Load(reader); + var actions = document.Root?.Elements("action").ToArray(); + if (document.Root?.Name != "policyconfig" || actions is not { Length: 1 }) return false; + var action = actions[0]; + var annotations = action.Elements("annotate").ToArray(); + var defaults = action.Elements("defaults").ToArray(); + return (string?)action.Attribute("id") == "io.github.memergamer.LinuxFiles.root-actions" + && annotations is { Length: 1 } && (string?)annotations[0].Attribute("key") == "org.freedesktop.policykit.exec.path" + && annotations[0].Value == helper && defaults is { Length: 1 } + && defaults[0].Elements().Count() == 3 + && defaults[0].Element("allow_any")?.Value == "no" + && defaults[0].Element("allow_inactive")?.Value == "no" + && defaults[0].Element("allow_active")?.Value == "auth_admin"; + } + } +} diff --git a/src/Files.Platform.Linux/Elevation/ElevationPlanPreview.cs b/src/Files.Platform.Linux/Elevation/ElevationPlanPreview.cs index 084c3e42475d..9e2b25002000 100644 --- a/src/Files.Platform.Linux/Elevation/ElevationPlanPreview.cs +++ b/src/Files.Platform.Linux/Elevation/ElevationPlanPreview.cs @@ -77,7 +77,7 @@ public void Update(string input) foreach (var command in plan.Commands) { IReadOnlyList arguments = command.Arguments; - if (command.Program == ElevationHelperProtocol.HelperPath && arguments.Count == 1) + if (System.IO.Path.GetFileName(command.Program) == "files-elevation-helper" && arguments.Count == 1) { try { diff --git a/src/Files.Platform.Linux/Elevation/ElevationTrust.cs b/src/Files.Platform.Linux/Elevation/ElevationTrust.cs index 18e79e1e4da7..d3131035f72a 100644 --- a/src/Files.Platform.Linux/Elevation/ElevationTrust.cs +++ b/src/Files.Platform.Linux/Elevation/ElevationTrust.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; namespace Files.Platform.Linux.Elevation { @@ -29,12 +30,14 @@ public sealed class ElevationPathChecker private const int MaxLinkHops = 40; private readonly IFileOwnershipInspector inspector; private readonly uint userId; + private readonly Func readLink; /// Creates the checker. - public ElevationPathChecker(IFileOwnershipInspector inspector, uint userId) + public ElevationPathChecker(IFileOwnershipInspector inspector, uint userId, Func? readLink = null) { this.inspector = inspector; this.userId = userId; + this.readLink = readLink ?? (path => new FileInfo(path).LinkTarget); } /// Gets the inspector used for all lookups. @@ -45,8 +48,12 @@ public ElevationPathChecker(IFileOwnershipInspector inspector, uint userId) /// /// Resolves every symbolic link in , including the last component. Returns null for broken links or loops. /// - public string? Canonicalize(string absolutePath) + public string? Canonicalize(string absolutePath) => Canonicalize(absolutePath, null); + + internal string? Canonicalize(string absolutePath, Func? trust) { + if (!absolutePath.StartsWith('/')) return null; + if (trust is not null && (!inspector.TryGetInfo("/", out var root) || !trust("/", root, false))) return null; var pending = new Stack(); foreach (var segment in absolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries)) pending.Push(segment); @@ -69,7 +76,9 @@ public ElevationPathChecker(IFileOwnershipInspector inspector, uint userId) current.Add(segment); var path = "/" + string.Join('/', current); - if (!inspector.TryGetInfo(path, out var info) || !info.IsSymbolicLink) + var found = inspector.TryGetInfo(path, out var info); + if (trust is not null && (!found || !trust(path, info, ordered.Count == 0))) return null; + if (!found || !info.IsSymbolicLink) continue; if (++hops > MaxLinkHops) @@ -78,9 +87,9 @@ public ElevationPathChecker(IFileOwnershipInspector inspector, uint userId) string? target; try { - target = new FileInfo(path).LinkTarget; + target = readLink(path); } - catch (IOException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return null; } @@ -129,62 +138,112 @@ public ElevationPathChecker(IFileOwnershipInspector inspector, uint userId) } } - /// - /// Resolves tools from /usr/bin then /bin and accepts them only if the file is owned by root and not writable by group or others. - /// + /// Resolves privileged tools only through root-controlled system paths, never PATH. public sealed class SystemToolResolver : ITrustedToolResolver { + public const string DeploymentPath = "/etc/linuxfiles/root-actions"; private static readonly HashSet Allowed = new(StringComparer.Ordinal) { "run0", "sudo", "pkexec" }; - private static readonly string[] Directories = ["/usr/bin", "/bin"]; + private static readonly string[] Directories = ["/run/wrappers/bin", "/run/current-system/sw/bin", "/usr/bin", "/bin"]; private readonly ElevationPathChecker checker; + private readonly Func readDeploymentFile; - /// Creates the resolver. - public SystemToolResolver(ElevationPathChecker checker) + /// Creates the resolver. The optional reader is a test seam; path trust is always checked first. + public SystemToolResolver(ElevationPathChecker checker, Func? readDeploymentFile = null) { this.checker = checker; + this.readDeploymentFile = readDeploymentFile ?? ReadBoundedFile; } /// public string? Resolve(string name) { if (name == "files-elevation-helper") + { + // An installed deployment is authoritative: never fall back after a broken generation switch. + if (checker.Inspector.TryGetInfo(DeploymentPath, out _)) return ResolveDeployment(); return IsRootOwnedChain(ElevationHelperProtocol.HelperPath) && IsRootOwnedChain(ElevationHelperProtocol.PolicyPath) && checker.Inspector.TryGetInfo(ElevationHelperProtocol.HelperPath, out var helper) && (helper.Mode & UnixFileMode.UserExecute) != 0 ? ElevationHelperProtocol.HelperPath : null; + } - if (!Allowed.Contains(name)) - return null; - + if (!Allowed.Contains(name)) return null; foreach (var directory in Directories) { var candidate = directory + "/" + name; - var real = checker.Canonicalize(candidate); - if (real is null || !checker.Inspector.TryGetInfo(real, out var info) || info.IsDirectory || info.IsSymbolicLink) - continue; - - if (IsRootOwnedChain(real, allowSetIdFile: true) && (info.Mode & UnixFileMode.UserExecute) != 0) + var real = ResolveRootOwned(candidate, allowSetIdFile: true); + if (real is not null && checker.Inspector.TryGetInfo(real, out var info) && (info.Mode & UnixFileMode.UserExecute) != 0) return candidate; } - return null; } - private bool IsRootOwnedChain(string path, bool allowSetIdFile = false) + private string? ResolveDeployment() + { + try + { + var manifest = ResolveRootOwned(DeploymentPath); + if (manifest is null) return null; + var text = readDeploymentFile(manifest); + if (text.Length > 8192) return null; + var lines = text.Split('\n'); + if (lines.Length != 3 || lines[2].Length != 0) return null; + var helper = lines[0]; + var policy = lines[1]; + if (!IsStorePath(helper) || !IsStorePath(policy) + || !helper.EndsWith("/lib/linuxfiles/elevation-helper/files-elevation-helper", StringComparison.Ordinal) + || !policy.EndsWith("/share/polkit-1/actions/io.github.memergamer.LinuxFiles.root-actions.policy", StringComparison.Ordinal) + || ResolveRootOwned(helper) != helper || ResolveRootOwned(policy) != policy + || !checker.Inspector.TryGetInfo(helper, out var info) || (info.Mode & UnixFileMode.UserExecute) == 0) + return null; + return ElevationDeploymentPolicy.Matches(readDeploymentFile(policy), helper) ? helper : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or System.Xml.XmlException) + { + return null; + } + } + + private static bool IsStorePath(string path) => path.StartsWith("/nix/store/", StringComparison.Ordinal) + && !path.Contains("//", StringComparison.Ordinal) && !path.Split('/').Any(part => part is "." or ".."); + + private static string ReadBoundedFile(string path) + { + using var reader = new StreamReader(path); + var buffer = new char[8193]; + var count = reader.ReadBlock(buffer, 0, buffer.Length); + if (count == buffer.Length) throw new IOException("Deployment file exceeds size limit."); + return new string(buffer, 0, count); + } + + private string? ResolveRootOwned(string path, bool allowSetIdFile = false) + => checker.Canonicalize(path, (component, info, last) => IsTrustedComponent(component, info, last, allowSetIdFile, allowLinks: true)); + + private bool IsRootOwnedChain(string path) { var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries); var current = "/"; for (var index = -1; index < parts.Length; index++) { if (index >= 0) current = Path.Combine(current, parts[index]); - if (!checker.Inspector.TryGetInfo(current, out var info) || info.IsSymbolicLink || info.OwnerUserId != 0 - || (info.Mode & (UnixFileMode.GroupWrite | UnixFileMode.OtherWrite)) != 0 - || ((info.Mode & (UnixFileMode.SetUser | UnixFileMode.SetGroup)) != 0 && !(allowSetIdFile && index == parts.Length - 1)) - || (index < parts.Length - 1 && !info.IsDirectory) || (index == parts.Length - 1 && info.IsDirectory)) - return false; + if (!checker.Inspector.TryGetInfo(current, out var info) + || !IsTrustedComponent(current, info, index == parts.Length - 1, false, allowLinks: false)) return false; } return true; } + private static bool IsTrustedComponent(string path, FileEntryInfo info, bool last, bool allowSetIdFile, bool allowLinks) + { + if (info.OwnerUserId != 0) return false; + if (info.IsSymbolicLink) return allowLinks; + if (info.IsDirectory == last) return false; + if ((info.Mode & (UnixFileMode.SetUser | UnixFileMode.SetGroup)) != 0 && !(allowSetIdFile && last)) return false; + // Nix's root-owned sticky store may be 1775. Every entry below it must be immutable and root-owned. + if (path == "/nix/store" && info.IsDirectory && (info.Mode & UnixFileMode.StickyBit) != 0 + && (info.Mode & UnixFileMode.OtherWrite) == 0) return true; + var forbidden = UnixFileMode.GroupWrite | UnixFileMode.OtherWrite; + if (path.StartsWith("/nix/store/", StringComparison.Ordinal)) forbidden |= UnixFileMode.UserWrite; + return (info.Mode & forbidden) == 0; + } } } diff --git a/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs b/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs index 8aec117b86e2..4c10ad3049bc 100644 --- a/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs +++ b/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs @@ -79,7 +79,7 @@ private static void TryKill(Process process, Action? terminate) catch (AggregateException ex) when (ex.InnerExceptions.All(inner => inner is System.ComponentModel.Win32Exception or InvalidOperationException)) { } } - public async Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string json, CancellationToken cancellationToken) + public async Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string helper, string json, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var info = new ProcessStartInfo(pkexec) @@ -89,7 +89,7 @@ private static void TryKill(Process process, Action? terminate) }; info.Environment.Clear(); info.Environment["LANG"] = "C"; - info.ArgumentList.Add(ElevationHelperProtocol.HelperPath); + info.ArgumentList.Add(helper); foreach (var argument in HelperAuthorization.Arguments(json)) info.ArgumentList.Add(argument); using var process = Process.Start(info) ?? throw new IOException("Unable to start authorization."); var output = ReadBoundedAsync(process.StandardOutput, CancellationToken.None, Stop); @@ -146,7 +146,7 @@ private static async Task ReadBoundedAsync(StreamReader reader, Cancella public interface IRootHelperProcessRunner { - Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string json, CancellationToken cancellationToken); + Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string helper, string json, CancellationToken cancellationToken); } /// Plans root actions and sends the frozen plan to the installed fd-relative helper through pkexec. @@ -168,7 +168,7 @@ public PkexecElevationService(ElevationPathChecker checker, ITrustedToolResolver this.packagedWithoutHelper = packagedWithoutHelper ?? (() => RootActionsAvailability.IsDisabled); } - public bool IsAvailable => checker.CurrentUserId != 0 && !packagedWithoutHelper() && tools.Resolve("pkexec") is not null && tools.Resolve("files-elevation-helper") == ElevationHelperProtocol.HelperPath; + public bool IsAvailable => checker.CurrentUserId != 0 && !packagedWithoutHelper() && tools.Resolve("pkexec") is not null && tools.Resolve("files-elevation-helper") is not null; public ElevatedPlanResult PlanDelete(IReadOnlyList paths) => Plan(ElevatedOperation.Delete, paths, null); public ElevatedPlanResult PlanCopy(IReadOnlyList sources, string destinationFolder) => Plan(ElevatedOperation.Copy, sources, destinationFolder); @@ -185,7 +185,7 @@ private ElevatedPlanResult Plan(ElevatedOperation operation, IReadOnlyList { ElevationHelperProtocol.ValidatePath(path); @@ -207,7 +207,7 @@ private ElevatedPlanResult Plan(ElevatedOperation operation, IReadOnlyList RunAsync(ElevatedPlan plan, CancellationToken cancellationToken = default) { - if (!IsAvailable || tools.Resolve("pkexec") is not { } pkexec) return Failure("The privileged helper is unavailable."); + if (!IsAvailable || tools.Resolve("pkexec") is not { } pkexec || tools.Resolve("files-elevation-helper") is not { } helper) return Failure("The privileged helper is unavailable."); try { // Rebuild only the serialized data: filesystem authority and post-verification belong to the helper. @@ -226,9 +226,9 @@ public async Task RunAsync(ElevatedPlan plan, CancellationToken ElevationHelperProtocol.Validate(request); var json = ElevationHelperProtocol.Serialize(request); ElevationHelperProtocol.ParseRequest(json); - if (plan.Commands.Count != 1 || plan.Commands[0].Program != ElevationHelperProtocol.HelperPath || !plan.Commands[0].Arguments.SequenceEqual(new[] { json })) + if (plan.Commands.Count != 1 || plan.Commands[0].Program != helper || !plan.Commands[0].Arguments.SequenceEqual(new[] { json })) return Failure("The operation no longer matches what was confirmed."); - var (exitCode, output, error) = await runner.RunHelperAsync(pkexec, json, cancellationToken).ConfigureAwait(false); + var (exitCode, output, error) = await runner.RunHelperAsync(pkexec, helper, json, cancellationToken).ConfigureAwait(false); if (exitCode is 126 or 127) return new(false, true, exitCode, error); if (exitCode is not (0 or 1)) return new(false, false, exitCode, error); var response = ElevationHelperProtocol.ParseResponse(output); diff --git a/tests/Files.Platform.Tests/SystemIntegration/ElevationProcessRunnerTests.cs b/tests/Files.Platform.Tests/SystemIntegration/ElevationProcessRunnerTests.cs index 90efa5f84da0..7e02a367da3d 100644 --- a/tests/Files.Platform.Tests/SystemIntegration/ElevationProcessRunnerTests.cs +++ b/tests/Files.Platform.Tests/SystemIntegration/ElevationProcessRunnerTests.cs @@ -18,10 +18,11 @@ namespace Files.Platform.Tests.SystemIntegration public sealed class ElevationProcessRunnerTests { [TestMethod] - [DataRow(0, false)] - [DataRow(1, true)] - [DataRow(2, false)] - public async Task CancellationWithEpermWaitsAndReturnsActualExitAndOutput(int exitCode, bool processTree) + [DataRow(0, false, ElevationHelperProtocol.HelperPath)] + [DataRow(0, false, "/nix/store/00000000000000000000000000000000-linuxfiles/lib/linuxfiles/elevation-helper/files-elevation-helper")] + [DataRow(1, true, ElevationHelperProtocol.HelperPath)] + [DataRow(2, false, ElevationHelperProtocol.HelperPath)] + public async Task CancellationWithEpermWaitsAndReturnsActualExitAndOutput(int exitCode, bool processTree, string helper) { var directory = Path.Combine(Path.GetTempPath(), "files-auth-process-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); @@ -32,6 +33,7 @@ public async Task CancellationWithEpermWaitsAndReturnsActualExitAndOutput(int ex var script = "#!/usr/bin/python3\nimport sys, json, hashlib, pathlib, time\n" + "directory = pathlib.Path(__file__).resolve().parent\n" + "data = sys.stdin.buffer.read()\nassert len(sys.argv) == 4\n" + + $"assert sys.argv[1] == '{helper}'\n" + "assert hashlib.sha256(data).hexdigest().upper() == sys.argv[3]\n" + "request = json.loads(data)\n" + "(directory / 'started').touch()\n" @@ -51,7 +53,7 @@ public async Task CancellationWithEpermWaitsAndReturnsActualExitAndOutput(int ex throw processTree ? new AggregateException(denied) : denied; }); using var cancellation = new CancellationTokenSource(); - var execution = runner.RunHelperAsync(executable, json, cancellation.Token); + var execution = runner.RunHelperAsync(executable, helper, json, cancellation.Token); try { var deadline = DateTime.UtcNow.AddSeconds(5); diff --git a/tests/Files.Platform.Tests/SystemIntegration/ElevationServiceTests.cs b/tests/Files.Platform.Tests/SystemIntegration/ElevationServiceTests.cs index ae825f1b5f5a..a8be9736b221 100644 --- a/tests/Files.Platform.Tests/SystemIntegration/ElevationServiceTests.cs +++ b/tests/Files.Platform.Tests/SystemIntegration/ElevationServiceTests.cs @@ -69,9 +69,10 @@ private sealed class Runner : IRootHelperProcessRunner public int ExitCode; public string? OverrideOutput; public string? Payload; - public Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string json, CancellationToken cancellationToken) + public Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string helper, string json, CancellationToken cancellationToken) { Assert.AreEqual("/usr/bin/pkexec", pkexec); + Assert.AreEqual(ElevationHelperProtocol.HelperPath, helper); Calls++; Payload = json; var request = ElevationHelperProtocol.ParseRequest(json); return Task.FromResult((ExitCode, OverrideOutput ?? ElevationHelperProtocol.Serialize(new HelperResponse(1, request.Sources.Select(source => new HelperItemResult(source, true, "")).ToArray(), "")), "auth error")); diff --git a/tests/Files.Platform.Tests/SystemIntegration/NixElevationTrustTests.cs b/tests/Files.Platform.Tests/SystemIntegration/NixElevationTrustTests.cs new file mode 100644 index 000000000000..802e884bf89c --- /dev/null +++ b/tests/Files.Platform.Tests/SystemIntegration/NixElevationTrustTests.cs @@ -0,0 +1,220 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Abstractions.Elevation; +using Files.Platform.Linux.Elevation; +using Files.Platform.Linux.Native; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Files.Platform.Tests.SystemIntegration +{ + [TestClass] + public sealed class NixElevationTrustTests + { + private const string Package = "/nix/store/00000000000000000000000000000000-linuxfiles"; + private const string Helper = Package + "/lib/linuxfiles/elevation-helper/files-elevation-helper"; + private const string Policy = Package + "/share/polkit-1/actions/io.github.memergamer.LinuxFiles.root-actions.policy"; + private const string Pkexec = "/run/wrappers/bin/pkexec"; + private const UnixFileMode Immutable = (UnixFileMode)0x16D; // 0555 + + private sealed class Fs : IFileOwnershipInspector + { + public Dictionary Entries { get; } = []; + public Dictionary Contents { get; } = []; + public bool TryGetInfo(string path, out FileEntryInfo info) => Entries.TryGetValue(path, out info!); + public void Add(string path, bool directory, UnixFileMode mode = (UnixFileMode)0x1ED) + { + Entries[path] = new(directory, false, 0, mode); + for (var parent = Path.GetDirectoryName(path); parent is not null; parent = Path.GetDirectoryName(parent)) + Entries.TryAdd(parent, new(true, false, 0, parent.StartsWith("/nix/store/", StringComparison.Ordinal) ? Immutable : (UnixFileMode)0x1ED)); + } + public SystemToolResolver Resolver() => new(new ElevationPathChecker(this, 1000), path => Contents[path]); + public static Fs Deployment() + { + var fs = new Fs(); + fs.Add(Helper, false, Immutable); + fs.Add(Policy, false, (UnixFileMode)0x124); + fs.Add(SystemToolResolver.DeploymentPath, false); + fs.Add(Pkexec, false, (UnixFileMode)0x9ED); + fs.Add("/home/u", true); + fs.Entries["/nix/store"] = new(true, false, 0, (UnixFileMode)0x3FD); // 1775 + fs.Contents[SystemToolResolver.DeploymentPath] = Helper + "\n" + Policy + "\n"; + fs.Contents[Policy] = PolicyText(Helper); + return fs; + } + } + + private static string PolicyText(string helper) => "" + + "nonoauth_admin" + + "" + helper + ""; + + [TestMethod] + public void StickyRootStoreAllowsOnlyImmutableRootOwnedEntries() + { + var fs = Fs.Deployment(); + var resolver = fs.Resolver(); + Assert.AreEqual(Helper, resolver.Resolve("files-elevation-helper")); + foreach (var path in new[] { "/nix", "/nix/store", Package, Package + "/lib", Helper, Policy, "/etc", SystemToolResolver.DeploymentPath }) + { + var original = fs.Entries[path]; + fs.Entries[path] = original with { OwnerUserId = 1000 }; + Assert.IsNull(resolver.Resolve("files-elevation-helper"), path); + fs.Entries[path] = original; + foreach (var write in new[] { UnixFileMode.GroupWrite, UnixFileMode.OtherWrite, UnixFileMode.UserWrite }) + { + if (write == UnixFileMode.UserWrite && !path.StartsWith("/nix/store/", StringComparison.Ordinal)) continue; + if (path == "/nix/store" && write == UnixFileMode.GroupWrite) continue; + fs.Entries[path] = original with { Mode = original.Mode | write }; + Assert.IsNull(resolver.Resolve("files-elevation-helper"), path + " " + write); + fs.Entries[path] = original; + } + } + fs.Entries["/nix/store"] = fs.Entries["/nix/store"] with { Mode = (UnixFileMode)0x1FD }; // 0775 without sticky + Assert.IsNull(resolver.Resolve("files-elevation-helper")); + } + + [TestMethod] + public void BrokenDeploymentAndMismatchedOrRetainedAuthorizationPolicyFailClosed() + { + var fs = Fs.Deployment(); + // A bad deployment must not fall back to a native helper and a generic pkexec prompt. + fs.Add(ElevationHelperProtocol.HelperPath, false); + fs.Add(ElevationHelperProtocol.PolicyPath, false); + var resolver = fs.Resolver(); + foreach (var text in new[] { "", Helper + "\n", Helper + "\n" + Policy, Helper + "\n" + Policy + "\nextra\n", + ElevationHelperProtocol.HelperPath + "\n" + Policy + "\n", Helper.Replace("/lib/", "/../lib/") + "\n" + Policy + "\n" }) + { + fs.Contents[SystemToolResolver.DeploymentPath] = text; + Assert.IsNull(resolver.Resolve("files-elevation-helper")); + } + fs.Contents[SystemToolResolver.DeploymentPath] = Helper + "\n" + Policy + "\n"; + foreach (var policy in new[] { "no", "yes"), + PolicyText(Helper).Replace("", "") }) + { + fs.Contents[Policy] = policy; + Assert.IsNull(resolver.Resolve("files-elevation-helper")); + } + fs.Contents[Policy] = PolicyText(Helper); + fs.Entries[Helper] = fs.Entries[Helper] with { Mode = Immutable | UnixFileMode.SetUser }; + Assert.IsNull(resolver.Resolve("files-elevation-helper")); + } + + [TestMethod] + [DataRow("pkexec")] + [DataRow("sudo")] + [DataRow("run0")] + public void NixWrapperToolsPrecedeSystemProfilesAndUsrBin(string name) + { + var fs = new Fs(); + foreach (var directory in new[] { "/run/wrappers/bin", "/run/current-system/sw/bin", "/usr/bin" }) fs.Add(directory + "/" + name, false); + var resolver = fs.Resolver(); + Assert.AreEqual("/run/wrappers/bin/" + name, resolver.Resolve(name)); + fs.Entries.Remove("/run/wrappers/bin/" + name); + Assert.AreEqual("/run/current-system/sw/bin/" + name, resolver.Resolve(name)); + fs.Entries["/run/current-system/sw"] = fs.Entries["/run/current-system/sw"] with { OwnerUserId = 1000 }; + Assert.AreEqual("/usr/bin/" + name, resolver.Resolve(name)); + Assert.IsNull(resolver.Resolve("sh")); + } + + + [TestMethod] + public void SystemProfileSymlinksRequireTrustedTraversalAndResolvedTarget() + { + var fs = Fs.Deployment(); + fs.Entries.Remove(Pkexec); + var target = Package + "/bin/pkexec"; + fs.Add(target, false, Immutable); + fs.Add("/run/current-system", true); + fs.Entries["/run/current-system/sw"] = new(false, true, 0, (UnixFileMode)0x1FF); + var links = new Dictionary { ["/run/current-system/sw"] = Package }; + var resolver = new SystemToolResolver(new ElevationPathChecker(fs, 1000, path => links.GetValueOrDefault(path))); + Assert.AreEqual("/run/current-system/sw/bin/pkexec", resolver.Resolve("pkexec")); + foreach (var path in new[] { "/run", "/run/current-system", "/run/current-system/sw", Package, target }) + { + var original = fs.Entries[path]; + fs.Entries[path] = original with { OwnerUserId = 1000 }; + Assert.IsNull(resolver.Resolve("pkexec"), path); + fs.Entries[path] = original; + if (original.IsSymbolicLink) continue; + fs.Entries[path] = original with { Mode = original.Mode | UnixFileMode.GroupWrite }; + Assert.IsNull(resolver.Resolve("pkexec"), path); + fs.Entries[path] = original; + } + var executable = Package + "/real/pkexec"; + fs.Add(executable, false, Immutable); + fs.Entries[target] = new(false, true, 0, (UnixFileMode)0x1FF); + links[target] = "../real/pkexec"; + Assert.AreEqual("/run/current-system/sw/bin/pkexec", resolver.Resolve("pkexec")); + fs.Entries[target] = fs.Entries[target] with { OwnerUserId = 1000 }; + Assert.IsNull(resolver.Resolve("pkexec")); + fs.Entries[target] = fs.Entries[target] with { OwnerUserId = 0 }; + fs.Entries[executable] = fs.Entries[executable] with { Mode = Immutable | UnixFileMode.UserWrite }; + Assert.IsNull(resolver.Resolve("pkexec")); + fs.Entries[executable] = fs.Entries[executable] with { Mode = Immutable }; + links["/run/current-system/sw"] = "/missing"; + Assert.IsNull(resolver.Resolve("pkexec")); + links["/run/current-system/sw"] = "/run/current-system/sw"; + Assert.IsNull(resolver.Resolve("pkexec")); + } + + [TestMethod] + public void EtcDeploymentSymlinkMustResolveThroughRootControlledComponents() + { + var fs = Fs.Deployment(); + var manifest = Package + "/root-actions-manifest"; + fs.Add(manifest, false, (UnixFileMode)0x124); + fs.Contents[manifest] = fs.Contents[SystemToolResolver.DeploymentPath]; + fs.Entries[SystemToolResolver.DeploymentPath] = new(false, true, 0, (UnixFileMode)0x1FF); + var resolver = new SystemToolResolver(new ElevationPathChecker(fs, 1000, _ => manifest), path => fs.Contents[path]); + Assert.AreEqual(Helper, resolver.Resolve("files-elevation-helper")); + fs.Entries[manifest] = fs.Entries[manifest] with { Mode = (UnixFileMode)0x1A4 }; + Assert.IsNull(resolver.Resolve("files-elevation-helper")); + fs.Entries[manifest] = fs.Entries[manifest] with { Mode = (UnixFileMode)0x124 }; + fs.Entries[SystemToolResolver.DeploymentPath] = fs.Entries[SystemToolResolver.DeploymentPath] with { OwnerUserId = 1000 }; + Assert.IsNull(resolver.Resolve("files-elevation-helper")); + } + + private sealed class Runner : IRootHelperProcessRunner + { + public int Calls; + public Task<(int ExitCode, string Output, string Error)> RunHelperAsync(string pkexec, string helper, string json, CancellationToken cancellationToken) + { + Assert.AreEqual(Pkexec, pkexec); + Assert.AreEqual(Helper, helper); + Calls++; + var request = ElevationHelperProtocol.ParseRequest(json); + return Task.FromResult((0, ElevationHelperProtocol.Serialize(new HelperResponse(1, + request.Sources.Select(source => new HelperItemResult(source, true, "")).ToArray(), "")), "")); + } + } + + [TestMethod] + public async Task StoreHelperIsPreviewedAndInvokedExactlyAndGenerationSwitchRefusesOldPlan() + { + var fs = Fs.Deployment(); var runner = new Runner(); + var service = new PkexecElevationService(new ElevationPathChecker(fs, 1000), fs.Resolver(), runner, () => false); + var plan = service.PlanDelete(["/home/u/café"]).Plan!; + Assert.IsNotNull(plan); + Assert.AreEqual(Helper, plan.Commands[0].Program); + var preview = ElevationPlanPreview.Format(plan)!; + StringAssert.Contains(preview, Helper); + StringAssert.Contains(preview, HelperAuthorization.Arguments(plan.Commands[0].Arguments[0])[1]); + StringAssert.Contains(preview, "stdin (JSON)"); + Assert.IsTrue((await service.RunAsync(plan)).Succeeded); + var replacement = Helper.Replace("-linuxfiles/", "-linuxfiles-next/"); + fs.Add(replacement, false, Immutable); + fs.Contents[SystemToolResolver.DeploymentPath] = replacement + "\n" + Policy + "\n"; + fs.Contents[Policy] = PolicyText(replacement); + Assert.IsTrue(service.IsAvailable); + Assert.IsFalse((await service.RunAsync(plan)).Succeeded); + Assert.AreEqual(1, runner.Calls); + } + } +}