diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index c2bfbf1..e66c19d 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -327,6 +327,21 @@ jobs: exit 1 fi .venv/bin/python -c 'from PIL import Image; import sys; im=Image.open(sys.argv[1]); assert im.size == tuple(map(int,sys.argv[2].split("x"))) and any(lo < hi for lo,hi in im.convert("RGB").getextrema())' "$out/shot.png" "$size" + - name: Build and exercise the Ubuntu rack host + if: runner.os == 'Linux' + run: | + .venv/bin/python -m pytest -q tests/test_linux_host_policy.py tests/test_host_key_approval.py + .venv/bin/python packaging/linux-host/build.py + bash packaging/linux-host/check-package.sh + - name: Keep the verified Ubuntu host package + if: runner.os == 'Linux' && success() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: EtherlightingEvolved-rack-host-${{ github.sha }} + retention-days: 30 + compression-level: 0 + if-no-files-found: error + path: outputs/native/EtherlightingEvolved-*-linux-host-amd64.deb - name: Keep native verification evidence if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 @@ -339,6 +354,7 @@ jobs: outputs/native-check/*.png outputs/native-check/package/shot.png outputs/native-check/package/shot-error.txt + outputs/native-check/rack/shot.png outputs/native/*.log - name: Keep verified desktop client archives if: success() diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 724969b..c92a629 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -153,6 +153,11 @@ jobs: - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: global-json-file: global.json + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + if: runner.os == 'Linux' + with: + node-version-file: .node-version + package-manager-cache: false - name: Install pinned dependencies shell: bash run: | @@ -165,6 +170,12 @@ jobs: run: | $platform = if ($IsMacOS) { 'osx' } else { 'linux' } ./desktop/publish.ps1 -Runtime @("$platform-x64", "$platform-arm64") -PythonExe "$PWD/.venv/bin/python" + - name: Build and exercise the Ubuntu rack host + if: runner.os == 'Linux' + shell: bash + run: | + .venv/bin/python packaging/linux-host/build.py + bash packaging/linux-host/check-package.sh - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: release-${{ matrix.runner }} @@ -174,6 +185,7 @@ jobs: path: | outputs/native/EtherlightingEvolved-*-osx-*.zip outputs/native/EtherlightingEvolved-*-linux-*.tar.gz + outputs/native/EtherlightingEvolved-*-linux-host-amd64.deb release: name: Release diff --git a/CHANGELOG.md b/CHANGELOG.md index c5a59c3..0d745e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- Ubuntu 24.04 x64 can host switch lighting and the rack touchscreen on the same machine. The host starts at boot and checks the enrolled switch's SSH fingerprint at each connection. + ## 0.7.3 - When live updates slow down, the desktop and browser port maps show each new color as soon as the switch confirms it. Smooth transitions resume when updates arrive more frequently. diff --git a/README.md b/README.md index 2d0a8c3..6ec5c9d 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The Profiles page with three saved profiles: ## Requirements -- A computer with 64-bit Windows 10 or later. EE controls switches from Windows only. +- A computer with 64-bit Windows 10 or later, or an Ubuntu 24.04 x64 server with the [rack host](docs/LINUX-HOST.md). - A switch from the [hardware list](docs/HARDWARE.md), its IP address, and the SSH username and password set for your devices in UniFi Network. EE signs in with that username and password; no SSH key is needed. - UniFi Network, if you want device names and port telemetry. - Tailscale on the Windows computer and on each other device, only if you want to open EE from elsewhere over an encrypted connection. LAN access works on your own network without Tailscale. @@ -68,6 +68,7 @@ Download the files from the [releases page](https://github.com/Views2k/etherligh | `EtherlightingEvolved-Setup-.exe` | Windows installer: the desktop app, the workspace service and the lighting engine | | `EtherlightingEvolved--osx-arm64.zip`, `EtherlightingEvolved--osx-x64.zip` | macOS client for Apple silicon and for Intel | | `EtherlightingEvolved--linux-x64.tar.gz`, `EtherlightingEvolved--linux-arm64.tar.gz` | Linux client | +| `EtherlightingEvolved--linux-host-amd64.deb` | Ubuntu switch host and rack client | | `SHA256SUMS` | SHA-256 checksums of the installer and the client archives | | `package-verification.json` | Record of the checks the release build ran on the Windows package | @@ -200,7 +201,7 @@ $env:EE_PREVIEW_LIVE = '0' npm start ``` -Open [the local workspace](http://127.0.0.1:4180). `npm start` also prints an administration link that works once; a browser that opens it can change the Tailscale and LAN access settings until the browser session ends or `npm start` stops. The simulator keeps its own data in `outputs/browser-preview-data/`. Set `EE_PREVIEW_LIVE` to `1` to log in to a switch instead; live mode runs on Windows only. The [development guide](docs/DEVELOPMENT.md) covers macOS and Linux, tests and the [Windows installer build](docs/DEVELOPMENT.md#windows-installer). The [desktop guide](desktop/README.md#build-and-test) covers the desktop app. +Open [the local workspace](http://127.0.0.1:4180). `npm start` also prints an administration link that works once; a browser that opens it can change the Tailscale and LAN access settings until the browser session ends or `npm start` stops. The simulator keeps its own data in `outputs/browser-preview-data/`. On Windows, set `EE_PREVIEW_LIVE` to `1` to log in to a switch. For Ubuntu live control, install the [rack host](docs/LINUX-HOST.md). The [development guide](docs/DEVELOPMENT.md) covers macOS and Linux, tests and the [Windows installer build](docs/DEVELOPMENT.md#windows-installer). The [desktop guide](desktop/README.md#build-and-test) covers the desktop app. ## Repository layout diff --git a/SECURITY.md b/SECURITY.md index 709a706..6ef65b6 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,6 +57,10 @@ On a USW-Pro-XG-8-PoE, two programs can keep running after EE closes: Both directories are readable only by the SSH user and live in the switch's memory, so a switch restart removes them. **Handoff to UniFi** in Settings stops both, and **Switch control** on the Fans page stops fan control. +## Ubuntu rack host + +The Ubuntu host runs with a dedicated dynamic user, a private state directory, and hidden user home directories. The enrolled rack user opens a mode-0600 Unix socket. SSH connects to the enrolled switch address and port and checks the administrator-pinned host key before authentication. User SSH keys and agents are disabled for this connection. Switch and controller logins use separate encryption contexts with a systemd-protected service credential. The administrator enrolls an optional local controller HTTPS origin. See the [rack host guide](docs/LINUX-HOST.md). + ## Access model The engine listens on `127.0.0.1` on a port chosen at each start and accepts only requests that carry the engine token. The workspace gateway listens on `127.0.0.1:4180`. When that port is taken, the desktop app uses the next free port up to 4199; its demo starts at port 4190. The gateway adds the token to the requests it forwards. It accepts only requests addressed to `127.0.0.1` or `localhost` on its own port, refuses API and WebSocket requests that a browser marks as coming from another website (`Origin` and `Sec-Fetch-Site`), and refuses request bodies over 1 MiB. diff --git a/desktop/EtherlightingEvolved.Native/WorkspaceTransport.cs b/desktop/EtherlightingEvolved.Native/WorkspaceTransport.cs index f19b6f4..95994cb 100644 --- a/desktop/EtherlightingEvolved.Native/WorkspaceTransport.cs +++ b/desktop/EtherlightingEvolved.Native/WorkspaceTransport.cs @@ -8,6 +8,10 @@ namespace EtherlightingEvolved.Native; internal static class WorkspaceTransport { + internal static bool UsesSystemHost(Uri workspace) => + OperatingSystem.IsLinux() && Environment.GetEnvironmentVariable("EE_SYSTEMD_CLIENT") == "1" && + workspace.Scheme == "http" && workspace.Host == "127.0.0.1" && workspace.Port == 4180; + internal static bool UsesPeerLookup(Uri workspace, bool linux) => linux && workspace.Scheme == Uri.UriSchemeHttps && workspace.UserInfo.Length == 0 && workspace.HostNameType == UriHostNameType.Dns && workspace.IdnHost.EndsWith(".ts.net", StringComparison.OrdinalIgnoreCase) && @@ -16,6 +20,22 @@ internal static bool UsesPeerLookup(Uri workspace, bool linux) => internal static SocketsHttpHandler CreateHandler(Uri workspace, DecompressionMethods decompression = DecompressionMethods.None) { var handler = new SocketsHttpHandler { UseProxy = false, AutomaticDecompression = decompression }; + if (UsesSystemHost(workspace)) + { + handler.AllowAutoRedirect = false; + handler.ConnectCallback = async (context, token) => + { + if (!IsWorkspaceEndpoint(workspace, context.DnsEndPoint)) throw new IOException("Invalid local workspace address."); + var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); + try + { + await socket.ConnectAsync(new UnixDomainSocketEndPoint("/run/etherlighting-host.sock"), token).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch { socket.Dispose(); throw; } + }; + return handler; + } // A LAN workspace gets its device key only from EeApi, and no redirect can take the key to another address. if (Core.WorkspaceAddress.IsLan(workspace)) { @@ -111,7 +131,7 @@ internal static Task ConnectStreamAsync(ClientWebSocket socket, Uri workspace, H socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20); var address = new UriBuilder(workspace) { Scheme = workspace.Scheme == "https" ? "wss" : "ws", Path = "/api/ws" }.Uri; // A LAN stream carries the device key, so it uses the request handler, which has no proxy and no redirects. - return UsesPeerLookup(workspace, OperatingSystem.IsLinux()) || Core.WorkspaceAddress.IsLan(workspace) + return UsesSystemHost(workspace) || UsesPeerLookup(workspace, OperatingSystem.IsLinux()) || Core.WorkspaceAddress.IsLan(workspace) ? socket.ConnectAsync(address, http, token) : socket.ConnectAsync(address, token); } diff --git a/desktop/README.md b/desktop/README.md index 92adf09..ccc67d4 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -12,7 +12,7 @@ Fans controls the fans of a USW-Pro-XG-8-PoE. EE saves the fan mode for each swi The first connection to a switch that has no saved SSH key signs in with the username and password and saves the switch's key. Settings > Connection shows the connected switch's SSH key fingerprint and key type as selectable text. If a switch presents a different key, the Connect page shows the saved and the new fingerprints, and **Accept new key** appears only in the window on the computer that runs the workspace service. A window connected through a Tailscale or LAN address shows a message to review the key on that computer instead. If the key changes while EE is connected, choose **Quit** from the tray menu and open EE again to review it. -For macOS, extract the archive for your processor and open `EtherlightingEvolved.app`. On Linux, extract the archive into a folder and run `./EtherlightingEvolved` in that folder. Keep the application and its libraries together. These archives contain the desktop client and the .NET runtime, but no workspace service, and only the Windows app connects to a switch. Connect to the workspace of a Windows computer that runs EE through its Tailscale private HTTPS address, through its LAN address with a pairing code (see [Connect over your network without Tailscale](#connect-over-your-network-without-tailscale)), or to a simulator started from a source checkout on the same computer. Choose **Change workspace address** on the connection error screen or in Settings to save the address. An explicit `--url` argument takes precedence over the saved address, and the `EE_WORKSPACE_URL` environment variable sets the same address with lower precedence than `--url`. Each source accepts only the addresses the dialog accepts: an HTTPS origin, an HTTP origin on this computer, or an HTTP origin at a private IPv4 address, one that starts with 10, 172.16 to 172.31 or 192.168, with a port other than 80, without account details, a path or a query. Host names such as `.local` names and IPv6 addresses are not accepted for LAN access. A `--url` value that does not qualify opens the connection error screen with **Change workspace address**, and an environment value that does not qualify is ignored. The default local address is `http://127.0.0.1:4180/`. +For macOS, extract the archive for your processor and open `EtherlightingEvolved.app`. On Linux, extract the archive into a folder and run `./EtherlightingEvolved` in that folder. Keep the application and its libraries together. These archives contain the desktop client and the .NET runtime. The separate [Ubuntu rack host package](../docs/LINUX-HOST.md) runs the switch service and touchscreen together. Connect to the workspace of a Windows computer that runs EE through its Tailscale private HTTPS address, through its LAN address with a pairing code (see [Connect over your network without Tailscale](#connect-over-your-network-without-tailscale)), or to a simulator started from a source checkout on the same computer. Choose **Change workspace address** on the connection error screen or in Settings to save the address. An explicit `--url` argument takes precedence over the saved address, and the `EE_WORKSPACE_URL` environment variable sets the same address with lower precedence than `--url`. Each source accepts only the addresses the dialog accepts: an HTTPS origin, an HTTP origin on this computer, or an HTTP origin at a private IPv4 address, one that starts with 10, 172.16 to 172.31 or 192.168, with a port other than 80, without account details, a path or a query. Host names such as `.local` names and IPv6 addresses are not accepted for LAN access. A `--url` value that does not qualify opens the connection error screen with **Change workspace address**, and an environment value that does not qualify is ignored. The default local address is `http://127.0.0.1:4180/`. A window connected through a Tailscale or LAN address can use lighting, effects, automation, profiles, schedules, port names and fans, and can reconnect to the switch whose login is saved on the Windows computer. Its Connect page shows **Connect with saved login**, **Retry handoff** when a handoff waits, and **Change workspace address** instead of the login form, and Settings leaves out **Forget saved switch login** and UniFi Network setup. **Change workspace address** stays available on the Connect page while a connection or handoff is pending. A client connected by address, including the Windows app opened with `--url` or `EE_WORKSPACE_URL`, cannot change the Tailscale or LAN access settings or close a workspace it did not start. Use the Windows computer for those. diff --git a/docs/API.md b/docs/API.md index a0ab6a2..6711834 100644 --- a/docs/API.md +++ b/docs/API.md @@ -121,6 +121,8 @@ and port-name refusals carry `message` without `code`. | 403 | `private_access_denied` | The Tailscale identity is not approved, or the path cannot be opened through private access | | 403 | `lan_access_denied`, `lan_pairing_required`, `lan_pairing_failed` | LAN access refusals; see [LAN access](#lan-access) | | 404 | `not_found` | No such zone, rule, preset, schedule, history entry or paired device | +| 403 | `host_policy` | The Ubuntu host administrator manages the switch's SSH identity and the permitted controller HTTPS origin | +| 403 | `local_only` | The Ubuntu rack host uses the local socket for workspace access | | 409 | `not_logged_in` | Not logged in to a switch | | 409 | `workspace_changed` | The `X-EE-Workspace` header names another switch session than the current one | | 409 | `handoff_unconfirmed` | A Handoff to UniFi has not been confirmed; lighting changes and connections wait for it | diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 344b0a9..e4ecb1f 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -58,7 +58,7 @@ Start-Process "http://127.0.0.1:4180/?admin_code=$code" To use another existing Python environment, set `EE_PREVIEW_PYTHON` to its absolute executable path before starting. The runtime also searches the checkout's `.venv` and the existing `PATH`. The desktop app, run from a source checkout, passes `EE_PREVIEW_PYTHON` to the gateway it starts; a packaged app ignores it. -For a live workspace, set `EE_PREVIEW_LIVE` to `1` and start the same command. Enter credentials through the login screen. Close another live EE instance first; the live workspace takes the Windows application instance lock, so live mode runs on Windows only. Source startup does not automatically log in to the switch. +For a live Windows workspace, set `EE_PREVIEW_LIVE` to `1` and start the same command. Enter credentials through the login screen. Close another live EE instance first; the Windows workspace takes the application instance lock. On Ubuntu, use the [rack host service](LINUX-HOST.md). Source startup does not automatically log in to the switch. | Setting | Purpose | | --- | --- | diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index b31cc69..5eb4276 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -49,7 +49,7 @@ The effect catalog includes parameter types, ranges, units, choices, independent The workspace subscribes before restoring initial state so delayed connection results reach the login screen. Connecting, recovery, pending handoff, and failure states have separate handling. A successful HTTP response alone does not establish that cleanup or a physical lighting change occurred; use the corresponding engine result and device acceptance checks. -Source mode starts in an isolated simulator by default. Live mode uses the existing engine settings and credential store. It needs the Windows application instance lock, so live mode runs on Windows only. On macOS and Linux only the simulator works; with `EE_PREVIEW_LIVE=1` the engine cannot take the lock and the gateway stops at startup. Gateway preferences, engine data, and simulator data have separate locations described in [DEVELOPMENT.md](DEVELOPMENT.md#data-and-generated-files). +Source mode starts in an isolated simulator by default. Live mode uses the existing engine settings and credential store. Windows uses its named application mutex. On Ubuntu, the [system service](LINUX-HOST.md) holds a Linux instance lock and serves the rack account over a systemd-owned Unix socket. Gateway preferences, engine data, and simulator data have separate locations described in [DEVELOPMENT.md](DEVELOPMENT.md#data-and-generated-files). Closing the web session uses `/api/workspace/close` to coordinate engine shutdown, private access cleanup and the LAN listener. The gateway answers its Tailscale settings, LAN access settings and workspace close routes itself. diff --git a/docs/LINUX-HOST.md b/docs/LINUX-HOST.md new file mode 100644 index 0000000..b093e80 --- /dev/null +++ b/docs/LINUX-HOST.md @@ -0,0 +1,51 @@ +# Host EE on an Ubuntu rack + +The Ubuntu 24.04 amd64 package runs switch control as a system service. Open **Etherlighting Evolved Rack** on the attached display. Closing the rack window leaves lighting running. The service starts at boot and the rack account can open its workspace before signing in to the switch. + +## Install and enroll + +Install the host `.deb` from the EE build you intend to run. The separate Linux client archive opens a workspace that is already running. + +[WINUX] + +```bash +sudo dpkg -i ./EtherlightingEvolved-*-linux-host-amd64.deb +``` + +In an enrollment JSON file, set `rack_user` to the Linux account that operates the touchscreen, `switch_address` to the switch's numeric address, and `switch_fingerprint` to its trusted SHA256 SSH host-key fingerprint. Copy the fingerprint from the previously trusted EE installation or verify it through the switch's management console. The optional `switch_port` defaults to 22. Set `controller_origin` to the numeric HTTPS address and port of your local UniFi Network controller if you use one. Enrollment contains device identifiers only. Keep passwords in the EE sign-in screen. + +[WINUX] + +```bash +sudo /usr/bin/python3 -I /usr/lib/etherlighting-host/configure.py ./enrollment.json +systemctl is-active etherlighting-host.service etherlighting-host.socket +``` + +When moving from another EE host, select **Settings → Handoff to UniFi** on the old host and wait for confirmation. Open **Etherlighting Evolved Rack** on the new host, enter the switch login there, and select its lighting setup. Save the login there to reconnect after a reboot. Windows saved logins are bound to the Windows account. + +## Access and storage + +The rack client talks to a local Unix socket owned by the enrolled user, with mode `0600`. The engine's internal loopback API requires a fresh random token on each start. The service runs under a dedicated unprivileged account with home directories hidden. Switch SSH uses the enrolled address, port and host key, and authenticates with the switch login. Enrollment does not change the server's SSH daemon or router settings. + +The system service keeps lighting and settings under `/var/lib/etherlighting-host`. It encrypts saved logins with a key supplied by systemd. Keep `/etc/etherlighting-host` private. The authenticated rack desktop and server administrators are trusted. Lock the desktop when it is unattended. + +## Upgrade or stop + +For a package upgrade or planned removal, hand off lighting first. Stop both units, then install the replacement package. The enrollment and saved settings persist. Start the socket and service after upgrading. + +[WINUX] + +```bash +sudo systemctl stop etherlighting-host.socket etherlighting-host.service +sudo dpkg -i ./EtherlightingEvolved-*-linux-host-amd64.deb +sudo systemctl daemon-reload +sudo systemctl start etherlighting-host.socket etherlighting-host.service +``` + +To switch back to the previous host, confirm handoff on the rack and disable both units before reconnecting the previous host. + +[WINUX] + +```bash +sudo systemctl disable --now etherlighting-host.socket etherlighting-host.service +``` diff --git a/packaging/linux-host/build.py b/packaging/linux-host/build.py new file mode 100644 index 0000000..6eeb9cd --- /dev/null +++ b/packaging/linux-host/build.py @@ -0,0 +1,85 @@ +"""Build the Ubuntu x64 host from the pinned CI environment and published rack client.""" + +import os +import platform +import runpy +import shutil +import subprocess +import sys +import tempfile +import tomllib +from importlib.metadata import version as installed_version +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def main(): + if sys.platform != "linux" or platform.machine() != "x86_64": + raise SystemExit("Build the host on the Ubuntu x64 runner.") + node = Path(shutil.which("node") or "node").resolve(strict=True) + expected_python = (ROOT / ".python-version").read_text().strip() + expected_node = (ROOT / ".node-version").read_text().strip() + if (not (platform.python_version() + ".").startswith(expected_python + ".") + or subprocess.check_output([node, "-p", "process.versions.node"], text=True).strip() != expected_node): + raise SystemExit("Use the repository's Python and Node versions.") + for _, dep in runpy.run_path(str(ROOT / "tools/hash-requirements.py"))["read_requirements"](): + if (dep and (not dep.marker or dep.marker.evaluate()) + and not dep.specifier.contains(installed_version(dep.name))): + raise SystemExit(f"Install the pinned version of {dep.name}.") + output = ROOT / "outputs/native" + version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] + revision = subprocess.check_output(["git", "rev-parse", "--short=12", "HEAD"], cwd=ROOT, text=True).strip() + deb = output / f"EtherlightingEvolved-{version}-linux-host-amd64.deb" + with tempfile.TemporaryDirectory() as work: + tmp = Path(work) + package = tmp / "package" + app = package / "usr/lib/etherlighting-host" + app.mkdir(parents=True) + subprocess.run([sys.executable, "-m", "PyInstaller", "--noconfirm", "--distpath", tmp / "dist", + "--workpath", tmp / "build", ROOT / "packaging/native-service.spec"], cwd=ROOT, check=True) + shutil.copytree(tmp / "dist/EEEngine", app / "engine", symlinks=True) + shutil.copytree(output / "linux-x64", app / "client") + for name in ("src", "preview", "assets"): + target = app / name + target.mkdir() + for item in (ROOT / name).iterdir(): + if (item.is_file() and item.suffix in {".mjs", ".css", ".html", ".png", ".svg", ".ico", ".webmanifest"} + and not item.name.endswith(".test.mjs") and item.name != "logo.png"): + shutil.copyfile(item, target / item.name) + (app / "runtime").mkdir() + shutil.copy2(node, app / "runtime/node") + notices = app / "licenses" + notices.mkdir() + shutil.copyfile(node.parents[1] / "LICENSE", notices / "Node-LICENSE.txt") + shutil.copyfile(ROOT / "LICENSE", notices / "EE-LICENSE.txt") + index = ["Python components"] + runpy.run_path(str(ROOT / "tools/collect-package-notices.py"))["collect_python"](app, notices, index) + (notices / "COMPONENTS.txt").write_text("\n".join(index) + "\n") + for name in ("start.py", "configure.py"): + shutil.copyfile(HERE / name, app / name) + units = package / "usr/lib/systemd/system" + units.mkdir(parents=True) + for unit in ("etherlighting-host.service", "etherlighting-host.socket"): + shutil.copyfile(HERE / unit, units / unit) + applications = package / "usr/share/applications" + applications.mkdir(parents=True) + shutil.copyfile(HERE / "etherlighting-rack.desktop", applications / "etherlighting-rack.desktop") + control = package / "DEBIAN" + control.mkdir() + (control / "control").write_text( + f"Package: etherlighting-host\nVersion: {version}+git{revision}\nArchitecture: amd64\n" + "Maintainer: Views2k\nSection: net\nPriority: optional\n" + "Depends: systemd (>= 255), python3 (>= 3.12), libc6 (>= 2.39), libstdc++6, libicu74, " + "libx11-6, libice6, libsm6, libfontconfig1\n" + "Description: Etherlighting Evolved switch host and local rack client\n" + ) + for name in ("preinst", "prerm"): + shutil.copyfile(HERE / "check-stopped", control / name) + os.chmod(control / name, 0o755) + subprocess.run(["dpkg-deb", "--root-owner-group", "-Zzstd", "-z3", "--build", package, deb], check=True) + + +if __name__ == "__main__": + main() diff --git a/packaging/linux-host/check-package.sh b/packaging/linux-host/check-package.sh new file mode 100644 index 0000000..0978440 --- /dev/null +++ b/packaging/linux-host/check-package.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Exercise the installed package in a disposable Ubuntu CI runner. +set -euo pipefail +[[ "$GITHUB_ACTIONS" == true && "$RUNNER_OS" == Linux ]] +shopt -s failglob +packages=(outputs/native/EtherlightingEvolved-*-linux-host-amd64.deb) +[[ ${#packages[@]} == 1 ]] +sudo dpkg -i "${packages[0]}" +tmp=$(mktemp -d) +out="$PWD/outputs/native-check/rack" +mkdir -p "$out" +trap 'sudo systemctl stop etherlighting-host.socket etherlighting-host.service; rm -f "$tmp/enrollment.json"; rmdir "$tmp"' EXIT +jq -n --arg user "$(id -un)" '{rack_user:$user,switch_address:"192.0.2.1",switch_fingerprint:("SHA256:"+("A"*43))}' > "$tmp/enrollment.json" +sudo /usr/bin/python3 -I /usr/lib/etherlighting-host/configure.py "$tmp/enrollment.json" +socket=/run/etherlighting-host.sock +url=http://127.0.0.1:4180 +request=(curl --unix-socket "$socket" --fail --silent --show-error --max-time 45) +"${request[@]}" "$url/api/session" | jq -e '.logged_in == false' +[[ $(stat -c '%a:%u' "$socket") == "600:$(id -u)" ]] +pid=$(systemctl show -p MainPID --value etherlighting-host.service) +[[ "$pid" -gt 1 && $(ps -o uid= -p "$pid" | xargs) -ne 0 ]] +[[ $(systemctl show -p NoNewPrivileges --value etherlighting-host.service) == yes ]] +if sudo -u nobody curl --silent --unix-socket "$socket" --max-time 2 "$url/api/session"; then exit 1; fi +if curl --noproxy '*' --silent --connect-timeout 1 "$url/api/session"; then exit 1; fi +"${request[@]}" "$url/api/private-access" | jq -e '.enabled == false and .can_configure == false' +[[ $(curl --unix-socket "$socket" -s -o /dev/null -w '%{http_code}' -X POST "$url/api/private-access/refresh") == 403 ]] +"${request[@]}" -H 'Content-Type: application/json' --data '{"host":"demo"}' "$url/api/session/login" | jq -e '.logged_in and .simulated' +.venv/bin/python - <<'PY' +from websockets.sync.client import unix_connect +with unix_connect("/run/etherlighting-host.sock", uri="ws://127.0.0.1:4180/api/ws", open_timeout=10) as socket: + assert socket.recv(timeout=10) +PY +timeout 120 xvfb-run -a env EE_SYSTEMD_CLIENT=1 /usr/lib/etherlighting-host/client/EtherlightingEvolved --url "$url" --shot "$out" --page Lighting --size 1280x400 +.venv/bin/python -c 'from PIL import Image; import sys; im=Image.open(sys.argv[1]); assert im.size==(1280,400) and any(lo&2 + exit 1 + fi +done diff --git a/packaging/linux-host/configure.py b/packaging/linux-host/configure.py new file mode 100644 index 0000000..7a1c5dd --- /dev/null +++ b/packaging/linux-host/configure.py @@ -0,0 +1,90 @@ +"""Enroll a rack account and a switch, then enable the system service.""" + +import argparse +import ipaddress +import json +import os +import pwd +import re +import subprocess +import tempfile +from pathlib import Path +from urllib.parse import urlsplit + +CONFIG = Path("/etc/etherlighting-host") +UNITS = Path("/etc/systemd/system") + + +def address(value): + ip = ipaddress.ip_address(value) + if ip.is_multicast or ip.is_unspecified or "%" in str(ip): + raise ValueError("Use an individual numeric address.") + return str(ip) + + +def enrollment(data): + uid = pwd.getpwnam(data["rack_user"]).pw_uid + if uid < 1000 or uid == 65534: + raise ValueError("Choose the regular user who signs in to the rack.") + switch = address(data["switch_address"]) + port = data.get("switch_port", 22) + pin = data["switch_fingerprint"] + if type(port) is not int or not 1 <= port <= 65535 or not re.fullmatch(r"SHA256:[A-Za-z0-9+/]{43}", pin): + raise ValueError("Check the switch port and its trusted SSH fingerprint.") + hosts = [switch] + values = {"EE_RACK_UID": uid, "EE_SWITCH_ADDRESS": switch, "EE_SWITCH_PORT": port, "EE_SWITCH_FINGERPRINT": pin} + if data.get("controller_origin"): + url = urlsplit(data["controller_origin"]) + if (url.scheme != "https" or not url.hostname or url.username is not None or url.password is not None + or url.path not in ("", "/") or url.query or url.fragment or url.port == 0): + raise ValueError("Use the numeric HTTPS origin of the local controller.") + host = address(url.hostname) + hosts.append(host) + authority = f"[{host}]" if ":" in host else host + values["EE_CONTROLLER_ORIGIN"] = f"https://{authority}:{url.port or 443}" + return uid, values, sorted(set(hosts)) + + +def write_file(path, value, mode=0o644): + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream: + tmp = Path(stream.name) + try: + stream.write(value) + stream.flush() + os.fchmod(stream.fileno(), mode) + os.fsync(stream.fileno()) + os.replace(tmp, path) + finally: + tmp.unlink(missing_ok=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("enrollment", type=Path) + args = parser.parse_args() + if os.geteuid() != 0: + raise SystemExit("Run enrollment with sudo.") + uid, values, hosts = enrollment(json.loads(args.enrollment.read_text("utf-8"))) + for unit in ("etherlighting-host.socket", "etherlighting-host.service"): + if subprocess.run(["systemctl", "is-active", "--quiet", unit], check=False).returncode == 0: + raise SystemExit("Hand off lighting in EE and stop both EE units before changing enrollment.") + CONFIG.mkdir(mode=0o700, exist_ok=True) + credential = CONFIG / "login.cred" + if not credential.exists(): + encrypted = subprocess.run( + ["systemd-creds", "encrypt", "--name=ee-login.key", "-", "-"], + input=os.urandom(32), stdout=subprocess.PIPE, check=True, + ).stdout + write_file(credential, encrypted, 0o600) + write_file(UNITS / "etherlighting-host.socket.d/rack.conf", f"[Socket]\nSocketUser={uid}\n".encode()) + write_file(UNITS / "etherlighting-host.service.d/devices.conf", + ("[Service]\n" + "".join(f"IPAddressAllow={ip}\n" for ip in hosts)).encode()) + write_file(CONFIG / "enrollment.conf", "".join(f"{k}={v}\n" for k, v in values.items()).encode(), 0o600) + subprocess.run(["systemctl", "daemon-reload"], check=True) + subprocess.run(["systemctl", "enable", "--now", "etherlighting-host.socket", "etherlighting-host.service"], + check=True) + + +if __name__ == "__main__": + main() diff --git a/packaging/linux-host/etherlighting-host.service b/packaging/linux-host/etherlighting-host.service new file mode 100644 index 0000000..9945199 --- /dev/null +++ b/packaging/linux-host/etherlighting-host.service @@ -0,0 +1,43 @@ +[Unit] +Description=Etherlighting Evolved switch host +Requires=etherlighting-host.socket +After=etherlighting-host.socket network-online.target +Wants=network-online.target +ConditionPathExists=/etc/etherlighting-host/enrollment.conf + +[Service] +Sockets=etherlighting-host.socket +ExecStart=/usr/bin/python3 -I /usr/lib/etherlighting-host/start.py +Environment=HOME=/var/lib/etherlighting-host EE_SYSTEMD_HOST=1 EE_PREVIEW_LIVE=1 EE_RUNTIME_MODE=packaged +Environment=EE_WORKSPACE_DATA_DIR=/var/lib/etherlighting-host/workspace +EnvironmentFile=/etc/etherlighting-host/enrollment.conf +LoadCredentialEncrypted=ee-login.key:/etc/etherlighting-host/login.cred +DynamicUser=yes +StateDirectory=etherlighting-host +StateDirectoryMode=0700 +UMask=0077 +PrivateTmp=yes +PrivateDevices=yes +ProtectHome=yes +InaccessiblePaths=-/etc/ssh -/run/docker.sock -/run/containerd +ProtectSystem=strict +ProtectProc=invisible +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +NoNewPrivileges=yes +CapabilityBoundingSet= +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +IPAddressDeny=any +IPAddressAllow=localhost +LockPersonality=yes +LimitCORE=0 +KillMode=mixed +TimeoutStopSec=45 +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/packaging/linux-host/etherlighting-host.socket b/packaging/linux-host/etherlighting-host.socket new file mode 100644 index 0000000..76760af --- /dev/null +++ b/packaging/linux-host/etherlighting-host.socket @@ -0,0 +1,12 @@ +[Unit] +Description=Etherlighting Evolved rack workspace +ConditionPathExists=/etc/etherlighting-host/enrollment.conf + +[Socket] +ListenStream=/run/etherlighting-host.sock +FileDescriptorName=ee-workspace +SocketMode=0600 +RemoveOnStop=yes + +[Install] +WantedBy=sockets.target diff --git a/packaging/linux-host/etherlighting-rack.desktop b/packaging/linux-host/etherlighting-rack.desktop new file mode 100644 index 0000000..8eecaf3 --- /dev/null +++ b/packaging/linux-host/etherlighting-rack.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=Etherlighting Evolved Rack +Comment=Open the lighting workspace on this server +Exec=/usr/bin/env EE_SYSTEMD_CLIENT=1 /usr/lib/etherlighting-host/client/EtherlightingEvolved --url http://127.0.0.1:4180/ +Icon=/usr/lib/etherlighting-host/client/etherlighting-evolved.png +Categories=Network;Utility; +Terminal=false diff --git a/packaging/linux-host/start.py b/packaging/linux-host/start.py new file mode 100644 index 0000000..2490c8e --- /dev/null +++ b/packaging/linux-host/start.py @@ -0,0 +1,30 @@ +"""Check the local workspace socket before passing it to the gateway.""" + +import os +import socket +import stat +from pathlib import Path + + +def main(): + root = Path(__file__).resolve().parent + address = "/run/etherlighting-host.sock" + if (os.getuid() == 0 or os.environ.get("LISTEN_PID") != str(os.getpid()) + or os.environ.get("LISTEN_FDS") != "1" or os.environ.get("LISTEN_FDNAMES") != "ee-workspace"): + raise SystemExit("The EE host needs its socket and unprivileged service account.") + info = os.lstat(address) + if (not stat.S_ISSOCK(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 + or info.st_uid != int(os.environ["EE_RACK_UID"])): + raise SystemExit("Check the EE rack socket owner and permissions.") + with socket.socket(fileno=3) as inherited: + if (inherited.family != socket.AF_UNIX or inherited.getsockname() != address + or not inherited.getsockopt(socket.SOL_SOCKET, socket.SO_ACCEPTCONN)): + raise SystemExit("The EE service requires its local listening socket.") + inherited.set_inheritable(True) + inherited.detach() + node = root / "runtime/node" + os.execv(node, [str(node), str(root / "preview/server.mjs")]) + + +if __name__ == "__main__": + main() diff --git a/packaging/native-service.spec b/packaging/native-service.spec index 3557935..019d79c 100644 --- a/packaging/native-service.spec +++ b/packaging/native-service.spec @@ -38,6 +38,7 @@ a = Analysis( pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name="EEEngine", console=True, - icon=str(root / "src" / "etherlighting_evolved" / "assets" / "ee.ico"), version=str(version_file), + icon=str(root / "src/etherlighting_evolved/assets/ee.ico") if sys.platform == "win32" else None, + version=str(version_file) if sys.platform == "win32" else None, ) coll = COLLECT(exe, a.binaries, a.datas, name="EEEngine") diff --git a/packaging/native_service.py b/packaging/native_service.py index 8e6cb32..ab43a94 100644 --- a/packaging/native_service.py +++ b/packaging/native_service.py @@ -55,7 +55,7 @@ def preview_transport(**credentials): raise LoginError("preview_only", "Open the app normally to connect to a switch.", 409) return SimulatedTransport(lit_ports=config.switch.num_ports) - desktop = os.environ.get("EE_DESKTOP_HOST") == "1" + desktop = os.environ.get("EE_DESKTOP_HOST") == "1" or os.environ.get("EE_SYSTEMD_HOST") == "1" app = create_app(config, demo=demo, autoconnect=not demo and (desktop or not browser_live), transport_factory=preview_transport if demo else None) server = uvicorn.Server(uvicorn.Config( diff --git a/preview/server.mjs b/preview/server.mjs index a26ce0d..40041df 100644 --- a/preview/server.mjs +++ b/preview/server.mjs @@ -37,7 +37,7 @@ function lanRoute(url){ // The returned server is not listening yet. Every way the workspace closes (the close request, the desktop parent // exiting, a signal or a listen failure) goes through the same state, so private access cannot be reopened while // the engine is shutting down. -export function createWorkspaceServer({root,port,live,backendPort,token,child,diagnostics,privateAccess,lanAccess,admin,closeWorkspace,keepAvailable=keepPrivateAccessAvailable,exit=code=>process.exit(code)}) { +export function createWorkspaceServer({root,port,live,backendPort,token,child,diagnostics,privateAccess,lanAccess,admin,closeWorkspace,localOnly=false,keepAvailable=keepPrivateAccessAvailable,exit=code=>process.exit(code)}) { const allowed = new Set([`127.0.0.1:${port}`,`localhost:${port}`]); // Browsers omit Origin on simple cross-site GETs such as an source, but they still send Sec-Fetch-Site, and // some engine GET routes have side effects. API calls are accepted only from the workspace page or from clients @@ -62,8 +62,8 @@ export function createWorkspaceServer({root,port,live,backendPort,token,child,di // The LAN listener closes too; both keep their saved settings for the next start. async function closePrivate(){ privateRetry.stop(); - const [result]=await Promise.all([live?privateAccess.shutdown():privateAccess.close(),lanAccess.close()]); - if(live&&result.route==='unconfirmed')diagnostics.record('private_route_cleanup_unconfirmed'); + const [result]=await Promise.all([live&&!localOnly?privateAccess.shutdown():privateAccess.close(),lanAccess.close()]); + if(live&&!localOnly&&result.route==='unconfirmed')diagnostics.record('private_route_cleanup_unconfirmed'); } function stop(){workspaceClosing=true;void closePrivate().catch(()=>{});server.close();child.stdin.end('quit\n');} // For a desktop that quits after a close that was not confirmed: no further release is attempted. The engine is told @@ -88,6 +88,13 @@ export function createWorkspaceServer({root,port,live,backendPort,token,child,di } const server=http.createServer(async(req,res)=>{ if (!permitted(req,req.url.startsWith('/api/'))) {refuse(res,403,'forbidden','Requests from other websites are not allowed.');return;} + if(localOnly && (req.url.startsWith('/api/private-access') || req.url.startsWith('/api/lan-access'))){ + if(req.method==='GET' && ['/api/private-access','/api/lan-access'].includes(req.url)){ + res.writeHead(200,{'Content-Type':'application/json','Cache-Control':'no-store'}); + res.end(JSON.stringify({available:false,enabled:false,ready:false,can_configure:false,can_close_workspace:false,local:true})); + }else refuse(res,403,'local_only','This host uses a local system socket.'); + return; + } // A browser opened by the desktop app or with the printed link trades its code for the cookies, and the redirect // takes the code out of the address bar. The Tailscale and LAN gateways always send an Origin header, so a request // from a remote device never redeems a code. @@ -241,6 +248,11 @@ export function startupLines({port,desktopHost,admin}){ export async function startWorkspace() { const runtime=resolveRuntimeConfig(); const {root,port,live,directory}=runtime; + const systemHost=process.env.EE_SYSTEMD_HOST==='1'; + if(process.platform==='linux' && live && !systemHost) throw new Error('Use the EE Linux host service for live switch control.'); + if(systemHost && (process.platform!=='linux' || process.env.LISTEN_PID!==String(process.pid) || + process.env.LISTEN_FDS!=='1' || process.env.LISTEN_FDNAMES!=='ee-workspace' || + !process.env.CREDENTIALS_DIRECTORY || !live)) throw new Error('Start the Linux host with its system service and socket.'); // The Tailscale CLI inherits this process's environment, so the key leaves it before any child process starts. const adminKey=runtime.adminKey??randomBytes(32).toString('hex');delete process.env.EE_ADMIN_KEY; const admin=createAdminAccess({key:adminKey,port}); @@ -278,7 +290,7 @@ export async function startWorkspace() { upstream.setTimeout(20000,()=>upstream.destroy(new Error('release_timeout')));upstream.on('error',reject);upstream.end(); }) }); - const workspace=createWorkspaceServer({root,port,live,backendPort,token,child,diagnostics,privateAccess,lanAccess,admin,closeWorkspace}); + const workspace=createWorkspaceServer({root,port,live,backendPort,token,child,diagnostics,privateAccess,lanAccess,admin,closeWorkspace,localOnly:systemHost}); const {server}=workspace; // 'close' follows the end of the engine's output, so its last diagnostics are recorded before the gateway exits. child.once('close',workspace.engineExited); @@ -294,6 +306,12 @@ export async function startWorkspace() { process.exit(1); })}); for(const signal of ['SIGINT','SIGTERM'])process.on(signal,workspace.stop); + if(systemHost){ + // systemd owns the filesystem socket and grants access to the configured rack user only. + // Do not start TCP gateways or print an administration link in the service journal. + server.listen({fd:3}); + return; + } server.listen(port,'127.0.0.1',()=>{ for(const line of startupLines({port,desktopHost:process.env.EE_DESKTOP_HOST,admin}))console.log(line); if(live){ diff --git a/requirements-ci.txt b/requirements-ci.txt index 6132c57..daef54b 100644 --- a/requirements-ci.txt +++ b/requirements-ci.txt @@ -2,7 +2,7 @@ # Install with: python -m pip install --require-hashes --only-binary=:all: -r requirements-ci.txt # The hashes cover the wheels that the Python version in .python-version installs on the CI runners. After changing # a pin, run python tools/hash-requirements.py to read the new hashes from PyPI. -altgraph==0.17.5 ; sys_platform == "win32" \ +altgraph==0.17.5 ; sys_platform != "darwin" \ --hash=sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597 annotated-doc==0.0.7 \ --hash=sha256:6bc31bbbec6dfaaedc1676dbc11dbda96fe22a2b5c400e9ebad113fec44a9dc6 @@ -71,11 +71,11 @@ pydantic_core==2.50.5 \ --hash=sha256:e8fe516a4b3b06e4ff83b9adee4a786d28a617e5fb5fe90bda49fb6f52a5ac19 Pygments==2.21.0 \ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 -pyinstaller==6.22.3 ; sys_platform == "win32" \ +pyinstaller==6.22.3 ; sys_platform != "darwin" \ --hash=sha256:052f4a1cd4f81092ccb7a18fe8ebc9ecf832a5917317e39fb3775af4e959b253 \ --hash=sha256:451a4ae14b719365bf1a2f0a99dae7b3463060061c3a394c70d5264cfb439528 \ --hash=sha256:500bd58c7bf7e584a8435adccbd763a0b918d5c12b08d74ff50fd79b2915458b -pyinstaller-hooks-contrib==2026.10 ; sys_platform == "win32" \ +pyinstaller-hooks-contrib==2026.10 ; sys_platform != "darwin" \ --hash=sha256:dfc3cde20a7ce6c92e803016e66eed4b7050467e2c5f886a3745d89b258c6d6d pytest==9.2.0 \ --hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 diff --git a/src/etherlighting_evolved/app_lock.py b/src/etherlighting_evolved/app_lock.py index 2529790..e8b992d 100644 --- a/src/etherlighting_evolved/app_lock.py +++ b/src/etherlighting_evolved/app_lock.py @@ -3,6 +3,9 @@ from __future__ import annotations import ctypes +import errno +import os +import socket import sys from ctypes import wintypes @@ -25,6 +28,20 @@ def __init__(self, name: str = APP_MUTEX) -> None: self._kernel = None def __enter__(self): + if sys.platform == "linux" and os.environ.get("EE_SYSTEMD_HOST") == "1": + if self._handle is not None: + raise AppLockError("The app lock is already held.") + lock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + try: + # The kernel releases this name on exit, including after a crash. + lock.bind("\0" + self.name) + except OSError as exc: + lock.close() + if exc.errno == errno.EADDRINUSE: + raise AlreadyRunningError("Another EE engine already controls this host.") from exc + raise AppLockError("Could not reserve switch control.") from exc + self._handle = lock + return self if sys.platform != "win32": raise AppLockError("Switch control requires the Windows app lock.") if self._handle is not None: @@ -47,6 +64,8 @@ def __enter__(self): def __exit__(self, *_): handle, self._handle = self._handle, None - if handle is not None: + if isinstance(handle, socket.socket): + handle.close() + elif handle is not None: self._kernel.CloseHandle(handle) self._kernel = None diff --git a/src/etherlighting_evolved/controller.py b/src/etherlighting_evolved/controller.py index 2f11f17..3da390b 100644 --- a/src/etherlighting_evolved/controller.py +++ b/src/etherlighting_evolved/controller.py @@ -7,6 +7,7 @@ import http.client import ipaddress import json +import os import re import socket import ssl @@ -38,7 +39,12 @@ def controller_origin(value: str) -> str: host = parsed.hostname.encode("idna").decode("ascii").lower() if ":" in host: host = f"[{host}]" - return f"https://{host}" + (f":{port}" if port is not None else "") + origin = f"https://{host}" + (f":{port}" if port is not None else "") + if os.environ.get("EE_SYSTEMD_HOST") == "1": + expected = urlsplit(os.environ.get("EE_CONTROLLER_ORIGIN", "")) + if expected.hostname != parsed.hostname or (expected.port or 443) != (port or 443): + raise ControllerError("host_policy", "Use the UniFi controller enrolled on the Linux host.", 403) + return origin except (AttributeError, UnicodeError, ValueError) as exc: raise ControllerError("invalid_url", "Enter the controller's HTTPS address, including its port.") from exc diff --git a/src/etherlighting_evolved/controller_credentials.py b/src/etherlighting_evolved/controller_credentials.py index 591036a..598e712 100644 --- a/src/etherlighting_evolved/controller_credentials.py +++ b/src/etherlighting_evolved/controller_credentials.py @@ -1,4 +1,4 @@ -"""Explicit controller reconnect credentials protected for the current Windows user.""" +"""Opt-in UniFi reconnect login protected for the Windows user or Linux host service.""" from __future__ import annotations @@ -15,7 +15,7 @@ validate_api_key, validate_controller_kind, ) -from .credentials import CredentialStoreError, _dpapi +from .credentials import CredentialStoreError, _dpapi, protect_record, protection_name from .storage import atomic_write_bytes @@ -81,12 +81,12 @@ def load(self) -> dict | None: raise CredentialStoreError("Could not read the saved controller login. Connect and save it again.") from exc if (not isinstance(envelope, dict) or set(envelope) != {"version", "protection", "purpose", "data"} - or envelope.get("version") != 1 or envelope.get("protection") != "windows-dpapi" + or envelope.get("version") != 1 or envelope.get("protection") != protection_name() or envelope.get("purpose") != "unifi-controller-login"): raise CredentialStoreError("The saved controller login is invalid. Connect and save it again.") try: encrypted = base64.b64decode(envelope["data"], validate=True) - payload = json.loads(_dpapi(encrypted, decrypt=True).decode("utf-8")) + payload = json.loads(protect_record(encrypted, b"ee-controller-login", _dpapi, decrypt=True)) return self._validate(payload) except (CredentialStoreError, TypeError, ValueError, UnicodeError) as exc: raise CredentialStoreError( @@ -95,10 +95,11 @@ def load(self) -> dict | None: def save(self, record: dict) -> None: payload = self._validate(record) try: - encrypted = _dpapi(json.dumps(payload, ensure_ascii=False).encode("utf-8")) + encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8") + encrypted = protect_record(encoded, b"ee-controller-login", _dpapi) except CredentialStoreError as exc: - raise CredentialStoreError("Windows could not protect the controller login. Try saving it again.") from exc - envelope = json.dumps({"version": 1, "protection": "windows-dpapi", "purpose": "unifi-controller-login", + raise CredentialStoreError("Could not protect the controller login. Try saving it again.") from exc + envelope = json.dumps({"version": 1, "protection": protection_name(), "purpose": "unifi-controller-login", "data": base64.b64encode(encrypted).decode("ascii")}).encode("utf-8") try: atomic_write_bytes(self.path, envelope) diff --git a/src/etherlighting_evolved/credentials.py b/src/etherlighting_evolved/credentials.py index 15edc09..4f2f4c2 100644 --- a/src/etherlighting_evolved/credentials.py +++ b/src/etherlighting_evolved/credentials.py @@ -1,4 +1,4 @@ -"""Opt-in saved login protected for the current Windows user.""" +"""Opt-in switch login protected for the Windows user or Linux host service.""" from __future__ import annotations @@ -6,6 +6,7 @@ import binascii import ctypes import json +import os import sys from pathlib import Path @@ -16,6 +17,34 @@ class CredentialStoreError(RuntimeError): """A saved login could not be protected, read or removed.""" +def protection_name() -> str: + if sys.platform == "linux" and os.environ.get("EE_SYSTEMD_HOST") == "1": + return "linux-systemd-aesgcm" + return "windows-dpapi" + + +def protect_record(data: bytes, purpose: bytes, windows_protect, *, decrypt: bool = False) -> bytes: + if protection_name() == "windows-dpapi": + return windows_protect(data, decrypt=True) if decrypt else windows_protect(data) + from cryptography.exceptions import InvalidTag + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + try: + directory = Path(os.environ["CREDENTIALS_DIRECTORY"]) + if not directory.is_absolute(): + raise ValueError("invalid credential directory") + key = (directory / "ee-login.key").read_bytes() + if len(key) != 32: + raise ValueError("invalid credential") + cipher = AESGCM(key) + if decrypt: + return cipher.decrypt(data[:12], data[12:], purpose) + nonce = os.urandom(12) + return nonce + cipher.encrypt(nonce, data, purpose) + except (KeyError, OSError, InvalidTag, ValueError) as exc: + raise CredentialStoreError("EE could not unlock its saved login. Check the host service credential.") from exc + + def _dpapi(data: bytes, *, decrypt: bool = False) -> bytes: if sys.platform != "win32": raise CredentialStoreError("Save login requires Windows protection. Sign in with Save login turned off.") @@ -82,23 +111,25 @@ def load(self) -> dict | None: if not isinstance(envelope, dict): raise CredentialStoreError("The saved login has an invalid format. Forget it and sign in again.") if "protection" in envelope or "version" in envelope: - if envelope.get("version") != 1 or envelope.get("protection") != "windows-dpapi": + if envelope.get("version") != 1 or envelope.get("protection") != protection_name(): raise CredentialStoreError("The saved login format is not supported. Sign in again.") try: encrypted = base64.b64decode(envelope["data"], validate=True) - payload = json.loads(_dpapi(encrypted, decrypt=True).decode("utf-8")) + payload = json.loads(protect_record(encrypted, b"ee-switch-login", _dpapi, decrypt=True)) except (KeyError, TypeError, ValueError, UnicodeError, binascii.Error) as exc: raise CredentialStoreError("Could not unlock the saved login. Forget it and sign in again.") from exc return self._validate(payload) # An older opt-in record is usable only after protection and atomic replacement succeed. + if protection_name() != "windows-dpapi": + raise CredentialStoreError("Use an encrypted login saved on this host.") legacy = self._validate(envelope) self.save(**legacy) return legacy def save(self, host: str, port: int, username: str, password: str) -> None: payload = self._validate({"host": host, "port": port, "username": username, "password": password}) - encrypted = _dpapi(json.dumps(payload, ensure_ascii=False).encode("utf-8")) - envelope = json.dumps({"version": 1, "protection": "windows-dpapi", + encrypted = protect_record(json.dumps(payload, ensure_ascii=False).encode("utf-8"), b"ee-switch-login", _dpapi) + envelope = json.dumps({"version": 1, "protection": protection_name(), "data": base64.b64encode(encrypted).decode("ascii")}).encode("utf-8") try: atomic_write_bytes(self.path, envelope) diff --git a/src/etherlighting_evolved/session.py b/src/etherlighting_evolved/session.py index 91051f5..678eb25 100644 --- a/src/etherlighting_evolved/session.py +++ b/src/etherlighting_evolved/session.py @@ -41,6 +41,7 @@ Transport, TransportError, UnreachableError, + enrolled_fingerprint, ) log = logging.getLogger(__name__) @@ -970,6 +971,12 @@ async def replace_host_key(self, host: str, port: int, saved_key: str, fingerpri host = host.strip() if not host: raise LoginError("missing_host", "Enter the switch's IP address", 400) + try: + enrolled = enrolled_fingerprint(host, port) + except TransportError as exc: + raise LoginError("host_policy", str(exc), 403) from exc + if enrolled and enrolled != fingerprint: + raise LoginError("host_policy", "Switch identity is managed by the Linux host administrator.", 403) async with self._lock: pinned = self._saved_host_key(host, port) if pinned == fingerprint: diff --git a/src/etherlighting_evolved/transport.py b/src/etherlighting_evolved/transport.py index 07fe08a..80fa265 100644 --- a/src/etherlighting_evolved/transport.py +++ b/src/etherlighting_evolved/transport.py @@ -9,8 +9,10 @@ import asyncio import contextlib +import ipaddress import json import logging +import os import random import re import secrets @@ -80,6 +82,21 @@ class HostKeyStoreError(TransportError): UNREADABLE_HOST_KEYS = "The saved SSH host keys in known_switches.json could not be read. Check the EE data folder." +def enrolled_fingerprint(host: str, port: int) -> str | None: + if os.environ.get("EE_SYSTEMD_HOST") != "1": + return None + try: + allowed = ipaddress.ip_address(os.environ["EE_SWITCH_ADDRESS"]) + target = ipaddress.ip_address(host) + allowed_port = int(os.environ["EE_SWITCH_PORT"]) + fingerprint = os.environ["EE_SWITCH_FINGERPRINT"] + except (KeyError, ValueError) as exc: + raise TransportError("Configure the switch address, port and SSH fingerprint on Linux.") from exc + if target != allowed or port != allowed_port or not re.fullmatch(SSH_FINGERPRINT, fingerprint): + raise TransportError("The Linux host permits only its configured switch and SSH identity.") + return fingerprint + + def _key_type(key) -> str | None: """The key's algorithm name for display, or None when it is unavailable or not a plain name.""" try: @@ -475,6 +492,9 @@ async def _connect(self) -> None: store = self.host_keys # Read before any network I/O, so an unreadable store ends the attempt before the switch is contacted. pinned = store.get(self.host, self.port) if store is not None else None + enrolled = enrolled_fingerprint(self.host, self.port) + if enrolled and self.key_file: + raise TransportError("The Linux host permits only switch password authentication.") rejection: TransportError | None = None class PinnedHostClient(asyncssh.SSHClient): @@ -485,6 +505,9 @@ def validate_host_public_key(self, host, addr, port, key): # Without a store the key could be neither checked nor saved. rejection = TransportError("EE has no place to save SSH host keys, so it did not connect.") return False + if enrolled is not None and fingerprint != enrolled: + rejection = TransportError("SSH identity differs from the fingerprint enrolled on the Linux host.") + return False if pinned is None or pinned == fingerprint: store.clear_presented(transport.host, transport.port) return True diff --git a/tests/test_host_key_approval.py b/tests/test_host_key_approval.py index 259fd85..59c1d5d 100644 --- a/tests/test_host_key_approval.py +++ b/tests/test_host_key_approval.py @@ -73,6 +73,30 @@ def ssh(port, store): return SSHTransport("127.0.0.1", port=port, host_keys=store, username="fixture", password="fixture") +@pytest.mark.anyio +async def test_enrolled_host_checks_ssh_target_and_identity_before_login(tmp_path, monkeypatch): + key, events = asyncssh.generate_private_key("ssh-ed25519"), [] + store = HostKeyStore(tmp_path / "known_switches.json") + monkeypatch.setenv("EE_SYSTEMD_HOST", "1") + async with ssh_server(key, events) as port: + monkeypatch.setenv("EE_SWITCH_ADDRESS", "127.0.0.1") + monkeypatch.setenv("EE_SWITCH_PORT", str(port)) + monkeypatch.setenv("EE_SWITCH_FINGERPRINT", FP_B) + with pytest.raises(TransportError, match="fingerprint enrolled"): + await ssh(port, store).connect() + assert not events and store.get("127.0.0.1", port) is None + monkeypatch.setenv("EE_SWITCH_FINGERPRINT", key.get_fingerprint("sha256")) + for target in (SSHTransport("192.0.2.45", port=port, host_keys=store), ssh(1, store), + SSHTransport("127.0.0.1", port=port, key_file="unused", host_keys=store)): + with pytest.raises(TransportError, match="permits only"): + await target.connect() + assert not events + transport = ssh(port, store) + await transport.connect() + await transport.close() + assert [kind for kind, _ in events] == ["begin_auth", "password"] + + @pytest.mark.anyio async def test_first_connection_sends_the_password_and_saves_the_key(tmp_path, caplog): key, events = asyncssh.generate_private_key("ssh-ed25519"), [] diff --git a/tests/test_linux_host_policy.py b/tests/test_linux_host_policy.py new file mode 100644 index 0000000..297570b --- /dev/null +++ b/tests/test_linux_host_policy.py @@ -0,0 +1,55 @@ +import os +import sys +import uuid + +import pytest + +from etherlighting_evolved import credentials +from etherlighting_evolved.app_lock import AlreadyRunningError, AppInstanceLock +from etherlighting_evolved.controller import ControllerError, controller_origin +from etherlighting_evolved.credentials import CredentialStoreError, SavedLogin + + +def test_host_credentials_are_scoped_to_host_and_login_type(monkeypatch, tmp_path): + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setenv("EE_SYSTEMD_HOST", "1") + monkeypatch.setenv("CREDENTIALS_DIRECTORY", str(tmp_path)) + key = tmp_path / "ee-login.key" + key.write_bytes(os.urandom(32)) + store = SavedLogin(tmp_path / "switch.json") + login = dict(host="192.0.2.1", port=22, username="test", password="fixture-password") + store.save(**login) + assert login["password"] not in store.path.read_text() + assert store.load() == login + wrapped = credentials.protect_record(b"fixture", b"ee-controller-login", None) + with pytest.raises(CredentialStoreError): + credentials.protect_record(wrapped, b"ee-switch-login", None, decrypt=True) + for replacement in (os.urandom(32), b""): + key.write_bytes(replacement) + with pytest.raises(CredentialStoreError): + store.load() + key.unlink() + with pytest.raises(CredentialStoreError): + store.save(**login) + + +def test_linux_host_controller_uses_only_enrolled_https_endpoint(monkeypatch): + monkeypatch.setenv("EE_SYSTEMD_HOST", "1") + monkeypatch.delenv("EE_CONTROLLER_ORIGIN", raising=False) + with pytest.raises(ControllerError, match="enrolled"): + controller_origin("https://192.0.2.3") + monkeypatch.setenv("EE_CONTROLLER_ORIGIN", "https://192.0.2.3:443") + assert controller_origin("https://192.0.2.3") == "https://192.0.2.3" + for other in ("https://localhost", "https://192.0.2.4", "https://192.0.2.3:8443"): + with pytest.raises(ControllerError, match="enrolled"): + controller_origin(other) + + +@pytest.mark.skipif(sys.platform != "linux", reason="Linux abstract Unix sockets") +def test_linux_lock_releases_and_rejects_a_second_writer(monkeypatch): + monkeypatch.setenv("EE_SYSTEMD_HOST", "1") + name = "ee-test-" + uuid.uuid4().hex + with AppInstanceLock(name), pytest.raises(AlreadyRunningError), AppInstanceLock(name): + pytest.fail("Two writers acquired the lock") + with AppInstanceLock(name): + pass diff --git a/tools/collect-package-notices.py b/tools/collect-package-notices.py index a9cf16d..75183b2 100644 --- a/tools/collect-package-notices.py +++ b/tools/collect-package-notices.py @@ -10,6 +10,7 @@ import re import shutil import sys +import sysconfig from pathlib import Path NOTICE_WORDS = ('license', 'licence', 'copying', 'notice') @@ -40,7 +41,8 @@ def collect_python(app: Path, destination: Path, index: list[str]) -> int: mapping = importlib.metadata.packages_distributions() names = set() - archive = CArchiveReader(str(app / 'engine/EEEngine.exe')).open_embedded_archive('PYZ.pyz') + engine = app / 'engine' / ('EEEngine.exe' if sys.platform == 'win32' else 'EEEngine') + archive = CArchiveReader(str(engine)).open_embedded_archive('PYZ.pyz') for module in archive.toc: if not module.startswith('etherlighting_evolved'): names.update(mapping.get(module.split('.')[0], [])) @@ -60,7 +62,10 @@ def collect_python(app: Path, destination: Path, index: list[str]) -> int: if doc and any(word in doc.lower() for word in ('copyright', 'license')): details.append(doc) (folder / 'SOURCE-NOTICE.txt').write_text('\n\n'.join(details) + '\n', encoding='utf-8') - shutil.copyfile(Path(sys.base_prefix) / 'LICENSE.txt', destination / 'Python-LICENSE.txt') + license_file = Path(sys.base_prefix) / 'LICENSE.txt' + if not license_file.is_file(): + license_file = Path(sysconfig.get_path('stdlib')) / 'LICENSE.txt' + shutil.copyfile(license_file, destination / 'Python-LICENSE.txt') return len(names)