diff --git a/.env.example b/.env.example index 6797b11..109f75a 100644 --- a/.env.example +++ b/.env.example @@ -62,14 +62,30 @@ NATS_WS_PORT=19222 PUBLIC_SERVER_URL=https://control.example.com # ── Reverse proxy trust ──────────────────────────────────────────────────── -# At least one of TRUSTED_PROXIES / TRUSTED_NETWORKS is required when -# TRUST_PROXY=1 outside development mode. +# Forwarded headers are trusted BY DEFAULT from private address space +# (loopback, RFC1918, CGNAT), so no configuration is needed behind a typical +# cloud or LAN reverse proxy. Setting TRUSTED_PROXIES / TRUSTED_NETWORKS +# replaces those defaults with an explicit allow-list — narrow this when +# untrusted peers share your private network. TRUST_PROXY=0 disables +# forwarded-header processing entirely. TRUST_PROXY=1 TRUSTED_PROXIES= -TRUSTED_NETWORKS=172.16.0.0/12 +TRUSTED_NETWORKS= TRUSTED_HOSTS=control.example.com FORWARD_LIMIT=1 +# ── Built-in encryption (self-signed) ────────────────────────────────────── +# TLS_SELF_SIGNED=1 makes the backend serve HTTPS with a chain it manages +# itself (root > intermediate > leaf, auto-renewed). Reverse proxies then +# either SKIP verification — not insecure: the hop is still encrypted, the +# roots simply are not distributed — or import root.crt + intermediate.crt +# to establish trust (re-import when they rotate at expiry). Always follow +# your organization's security standards. The chain is PEM files under +# /tls (TLS_CERT_DIR overrides; keep it on a persisted volume, and +# switch the proxy upstream + health checks to https accordingly). +TLS_SELF_SIGNED=0 +TLS_CERT_DIR= + # ── Initial local admin (first startup only) ─────────────────────────────── INITIAL_ADMIN_USERNAME=admin # Generate: openssl rand -base64 24 diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 78480ac..0a995d2 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,10 +1,34 @@ name: CI +# Runs only when something buildable changes — docs-only commits (README, +# docs/, compose examples) skip the queue entirely. on: pull_request: branches: [main] + paths: + - 'src/**' + - 'tests/**' + - 'scripts/**' + - 'assets/**' + - '.gitea/workflows/**' + - 'ExecuteR.slnx' + - 'Directory.Build.props' + - 'Directory.Packages.props' + - 'global.json' + - 'dotnet-tools.json' push: branches: [dev, main] + paths: + - 'src/**' + - 'tests/**' + - 'scripts/**' + - 'assets/**' + - '.gitea/workflows/**' + - 'ExecuteR.slnx' + - 'Directory.Build.props' + - 'Directory.Packages.props' + - 'global.json' + - 'dotnet-tools.json' jobs: build-test: @@ -92,6 +116,10 @@ jobs: $zip = "artifacts/Agent-${{ steps.ver.outputs.version }}-win-x64.zip" if (Test-Path $msi) { Copy-Item $msi "$stage/Agent.msi" } if (Test-Path $zip) { Copy-Item $zip "$stage/Agent.zip" } + foreach ($rid in 'linux-x64','linux-arm64','osx-x64','osx-arm64') { + $unix = "artifacts/Agent-${{ steps.ver.outputs.version }}-$rid.zip" + if (Test-Path $unix) { Copy-Item $unix "$stage/Agent-$rid.zip" } + } '${{ steps.ver.outputs.version }}' | Set-Content "$stage/VERSION" -NoNewline Get-ChildItem $stage | Select-Object Name, Length diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index c100e74..b8aeec5 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,8 +1,21 @@ name: Release +# Docs-only merges to main skip the release build the same way CI skips +# docs-only commits — a release only makes sense when shippable bits changed. on: push: branches: [main] + paths: + - 'src/**' + - 'tests/**' + - 'scripts/**' + - 'assets/**' + - '.gitea/workflows/**' + - 'ExecuteR.slnx' + - 'Directory.Build.props' + - 'Directory.Packages.props' + - 'global.json' + - 'dotnet-tools.json' jobs: agent-artifacts: diff --git a/README.md b/README.md index 7742768..7f928a6 100644 --- a/README.md +++ b/README.md @@ -35,25 +35,25 @@ updates with **no SignalR, SSE, or polling**. 7. [Generating local secrets](#generating-local-secrets) 8. [Docker Compose](#docker-compose) 9. [Standalone server binary](#standalone-server-binary) -10. [Reverse proxy routes](#reverse-proxy-routes) -11. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle) -12. [MSI public properties](#msi-public-properties) -13. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence) -14. [Bootstrap and URL install](#bootstrap-and-url-install) -15. [Local login and OIDC](#local-login-and-oidc) -16. [Custom roles and permissions](#custom-roles-and-permissions) -17. [Typed script parameters and Functions](#typed-script-parameters-and-functions) -18. [Script engines](#script-engines) -19. [Secrets providers and $Secrets](#secrets-providers-and-secrets) -20. [Device groups and script triggers](#device-groups-and-script-triggers) -21. [Group runs and schedules](#group-runs-and-schedules) -22. [Database providers](#database-providers) -23. [Logging](#logging) -24. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan) -25. [S3 file delivery](#s3-file-delivery) -26. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables) -27. [Versioning](#versioning) -28. [MVP demo sequence](#mvp-demo-sequence) +10. [Networking and TLS](#networking-and-tls) +11. [Reverse proxy routes](#reverse-proxy-routes) +12. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle) +13. [MSI public properties](#msi-public-properties) +14. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence) +15. [Bootstrap and URL install](#bootstrap-and-url-install) +16. [Local login and OIDC](#local-login-and-oidc) +17. [Custom roles and permissions](#custom-roles-and-permissions) +18. [Typed script parameters and Functions](#typed-script-parameters-and-functions) +19. [Script engines](#script-engines) +20. [Secrets providers and $Secrets](#secrets-providers-and-secrets) +21. [Device groups and script triggers](#device-groups-and-script-triggers) +22. [Group runs and schedules](#group-runs-and-schedules) +23. [Database providers](#database-providers) +24. [Logging](#logging) +25. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan) +26. [S3 file delivery](#s3-file-delivery) +27. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables) +28. [Versioning](#versioning) 29. [Troubleshooting](#troubleshooting) --- @@ -348,16 +348,120 @@ the same reset. ![First sign-in password reset](docs/screenshots/login-reset.png) -The **Windows MSI** wraps the same flow: an Administrator account page in the -wizard (defaults admin / admin; `ADMINUSERNAME=… ADMINPASSWORD=…` for silent -installs) then the binary's own `setup` + `service install`. Upgrades never -overwrite existing configuration, and uninstall stops and removes the service. +The **Windows MSI** wraps the same flow with two wizard pages — the +Administrator account (defaults admin / admin) and **Network settings**: bind +address (0.0.0.0 default, explained inline), the HTTP port (9080), the +three loopback-only NATS ports, and an **Enable Self-Signed TLS** checkbox, +checked by default (see [Networking and TLS](#networking-and-tls) — proxies +skip verification or import the exported roots), each described in place so +a next-next-next install just works. Silent installs pass the same values +as properties (`ADMINUSERNAME ADMINPASSWORD BINDADDRESS HTTPPORT NATSPORT +NATSWSPORT NATSMONITORPORT ENABLETLS`), then the binary's own `setup` + +`service install` run. +The finish page offers to **open the console in the browser** (checked by +default) — a wildcard bind (`0.0.0.0` / `::`) opens `http://localhost:`, +a specific bind address opens that address directly. +Upgrades never overwrite existing configuration, and uninstall stops and +removes the service. The MSI installs exactly one instance — multi-instance +boxes use the ZIP with distinct ports and service names. Bundles ship the **agent installers** (`agent-package/` with `Agent.msi`, -`Agent.zip`, `VERSION`), so the URL install command works immediately — no -seeding, no S3. Agents enroll against the same base URL. Put a TLS-terminating -reverse proxy in front for production use; the compose stack remains the -recommended deployment for anything long-lived. +`Agent.zip`, the unix zips and `VERSION`), so the URL install command works +immediately — no seeding, no S3. Agents enroll against the same base URL. Put +a TLS-terminating reverse proxy in front for production use; the compose stack +remains the recommended deployment for anything long-lived. + +The standalone binary is configured through **flat keys in the generated +`appsettings.json`** next to the binary, or the same names as **environment +variables** (env wins). It honors the default proxy trust (loopback / RFC1918 +/ CGNAT), so it works behind a typical reverse proxy untouched; `setup` +pre-writes the optional knobs — `TLS_SELF_SIGNED`, `TLS_CERT_DIR`, +`PUBLIC_SERVER_URL`, `TRUSTED_NETWORKS`, `TRUSTED_HOSTS`, `TRUST_PROXY` — as +placeholders ready to fill. + +**Multiple instances on one box**: one directory per instance, distinct ports +at setup, distinct service names at install: + +```text +ExecuteR-Server setup --http-port 9081 --nats-port 4223 --nats-ws-port 9223 --nats-monitor-port 8223 +ExecuteR-Server service install --name ExecuteRServer2 +``` + +`--bind ` controls the HTTP bind address (default `0.0.0.0`; e.g. +`--bind 127.0.0.1` to serve only to a local reverse proxy). The NATS sidecar +always binds loopback — its ports are never exposed. Ports and bind land in +`appsettings.json` (`Urls`), so they can also be edited there afterwards. + +Everything an instance owns — config, database, keys, NATS state, agent +packages — lives inside its own directory, so instances never share state. + +--- + +## Networking and TLS + +ExecuteR serves **plain HTTP only — SSL/TLS termination is not supported in +the service itself and will not be added**. Terminating TLS inside every +application is yesterday's pattern; the state of the art is a dedicated edge +appliance or service that terminates TLS once, renews certificates +automatically (ACME/Let's Encrypt) and gives you layer-7 visibility — access +logs, request metrics, rate limiting, WAF hooks — for everything behind it: + +| Edge | Notes | +|------|-------| +| [Caddy](https://caddyserver.com) | Automatic HTTPS out of the box; single binary, runs fine on **Windows** or Linux | +| [nginx](https://nginx.org) + [Nginx UI](https://nginxui.com) | The classic; Nginx UI adds a web console with ACME renewal and also installs on **Windows** | +| [HAProxy](https://www.haproxy.org) | High-throughput L4/L7 balancing and fine-grained traffic policy | +| [Zoraxy](https://zoraxy.aroz.org) | All-in-one reverse proxy with a friendly UI | + +Put any of these in front on `:443` and forward to ExecuteR over HTTP. +Because forwarded headers are trusted from private address space by default +(next section), this works with zero ExecuteR-side configuration — the edge +handles certificates and encryption, ExecuteR handles the rest. For the +standalone Windows server the shortest path is installing Caddy (or Nginx UI +if you want a console) on the same host and proxying `localhost:9080`. + +### Self-Signed TLS (on by default) + +The server encrypts its own listener **by default**: HTTPS with a chain it +manages itself — root CA → intermediate → leaf, issued on first boot and +**auto-renewed** in the background (leaf yearly, re-issued 30 days early and +hot-swapped without a restart). Opt out with `TLS_SELF_SIGNED=0`, `setup +--tls 0`, or by unchecking **Enable Self-Signed TLS** in the server MSI +wizard (`ENABLETLS=""` silently). + +The reverse proxy then has two equally valid options — **pick per your +organization's security standards**: + +- **Skip verification** (nginx `proxy_ssl_verify off`, Caddy + `tls_insecure_skip_verify`, HAProxy `ssl verify none`). This is **not + insecure**: the traffic on the hop is still fully encrypted — the + self-signed roots simply are not distributed, so there is nothing for the + proxy to verify against. +- **Establish trust**: import the root and intermediate certificates into + the proxy's trust store (`fullchain.crt` sits next to the PEMs for + pinning). Be aware this adds a rotation duty — when the chain rotates at + expiry, the proxy needs the new roots re-imported. + +On **Windows** the chain lives in the machine certificate stores exactly +where each link belongs — root in *Trusted Root Certification Authorities*, +intermediate in *Intermediate Certification Authorities*, leaf in +*Personal* — so browsers on the server itself trust it with no warning. +The same chain is **also mirrored as PEM files** (certs, keys and +`fullchain.crt` under `/tls`), refreshed on every renewal, so a local +Caddy / Nginx UI / nginx can bind or trust the files directly and stay +current. On **Linux/macOS/containers** the PEM files are the primary store +(`TLS_CERT_DIR` overrides; keep it on a persisted volume in containers). + +**Agents** follow automatically: when the server serves the self-signed +chain directly (no proxy in between), the Add-Device one-liners and install +scripts include TLS skip-verify and set the agent's `TlsSkipVerify` registry +value (`/etc/executer/agent.json` on unix) so enrollment and the persistent +connection work out of the box — still fully encrypted. The value is +GPO-manageable (`Skip TLS certificate verification` in the ADMX template, +policy key beats local config), `configure --skip-tls-verify` sets it by +hand, and the agent MSI wizard has a matching checkbox — unchecked by +default (`SKIPTLSVERIFY=1` silently). Behind a proxy with a real +certificate none of this engages — agents validate normally. --- @@ -375,14 +479,30 @@ and forwarding to the host ports above: The proxy must preserve the WebSocket upgrade and send `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Prefix`. The backend -processes forwarded headers before auth and trusts them only from configured -`TRUSTED_PROXIES` / `TRUSTED_NETWORKS`. If path-based proxying conflicts with -your NATS WebSocket config, use dedicated hostnames behind the same `:443` edge. +processes forwarded headers before auth and **trusts them by default from +private address space** — loopback, RFC1918 (10/8, 172.16/12, 192.168/16) and +CGNAT (100.64/10) — so dropping the stack behind a cloud or LAN reverse proxy +needs zero trust configuration. Setting `TRUSTED_PROXIES` / +`TRUSTED_NETWORKS` **replaces** those defaults with an explicit allow-list +(narrow this when untrusted peers share your private network), and +`TRUST_PROXY=0` disables forwarded-header processing entirely. If path-based +proxying conflicts with your NATS WebSocket config, use dedicated hostnames +behind the same `:443` edge. -A ready-to-adapt single-file nginx site (nginx-ui style, edge rate limiting, -long-lived WebSocket timeouts and commented IP allow-lists) is in -[src/Infra/nginx](src/Infra/nginx). The OIDC callback (`/api/auth/oidc/callback`) -rides the `/api/*` location — no extra route is needed. +Ready-to-adapt single-file edge samples ship for all three common choices — +each with the same shape: banner header, BEFORE-USE placeholders, forwarded +headers, WebSocket handling, commented IP allow-lists and the self-signed +upstream variant: + +- [src/Infra/nginx](src/Infra/nginx) — nginx-ui friendly site with edge rate + limiting and long-lived WebSocket timeouts +- [src/Infra/caddy](src/Infra/caddy) — automatic HTTPS via ACME, runs on + Windows too +- [src/Infra/haproxy](src/Infra/haproxy) — stick-table rate limits and + tunnel timeouts for the WebSocket sessions + +The OIDC callback (`/api/auth/oidc/callback`) rides the `/api/*` route in +all of them — no extra route is needed. --- @@ -429,6 +549,7 @@ msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN=' -UseBasicParsing | iex +``` + +```bash +# Linux +curl -fsSL 'https://control.example.com/api/enrollment/install?token=&type=linux' | sudo bash +# macOS +curl -fsSL 'https://control.example.com/api/enrollment/install?token=&type=osx' | sudo bash +``` + +The unix script detects the architecture (x64/arm64), downloads the matching +agent zip from the same origin, unpacks to `/opt/executer/agent`, configures +enrollment through the agent's own `configure --url --token` CLI and registers +the systemd unit / launchd daemon. Tokens can also be minted under +**Settings**, and the MSI installs directly: ```text msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN= ``` -URL one-liner (elevated PowerShell on the target; requires `Agent.msi` in the -backend's `AGENT_PACKAGE_PATH`): - -```powershell -iwr https://control.example.com/api/enrollment/install?token= -UseBasicParsing | iex -``` - The agent generates its NKey locally (the private seed never leaves the device), bootstraps over HTTPS, receives a scoped NATS JWT, erases the token, and connects over WSS. The device appears in the UI within seconds. +![Add device](docs/screenshots/add-device.png) + --- ## Local login and OIDC @@ -1064,22 +1200,6 @@ metadata), and the frontend build metadata. --- -## MVP demo sequence - -1. `docker compose up -d` — backend, NATS and WebUI become healthy. -2. Sign in locally as the initial admin. -3. Generate a one-time bootstrap token (Settings). -4. Install the agent (`SERVERURL`, `BOOTSTRAPTOKEN`) via MSI or the URL one-liner. -5. The device appears within seconds; presence keeps status live without refresh. -6. Inventory populates the device detail tabs. -7. Author/save a PowerShell script; select the device; run. -8. Job state goes Running, output and a progress bar advance live; job Succeeds. -9. Open the remote shell; run `hostname`, `whoami`, `Get-Process | Select -First 5`. -10. Resize and disconnect cleanly; restart the service — it reconnects without a - token; rerun and verify no duplicate execution from redelivery. - ---- - ## Troubleshooting | Symptom | Check | diff --git a/docker-compose.yml b/docker-compose.yml index 1fb1a13..94a2378 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -111,6 +111,8 @@ services: TRUSTED_PROXIES: '${TRUSTED_PROXIES:-}' TRUSTED_NETWORKS: '${TRUSTED_NETWORKS:-}' TRUSTED_HOSTS: '${TRUSTED_HOSTS:-}' + TLS_SELF_SIGNED: '${TLS_SELF_SIGNED:-0}' + TLS_CERT_DIR: '${TLS_CERT_DIR:-}' FORWARD_LIMIT: '${FORWARD_LIMIT:-1}' PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}' INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}' diff --git a/docs/screenshots/add-device.png b/docs/screenshots/add-device.png new file mode 100644 index 0000000..8d20fe0 Binary files /dev/null and b/docs/screenshots/add-device.png differ diff --git a/docs/screenshots/devices.png b/docs/screenshots/devices.png index 4d64c35..06a867f 100644 Binary files a/docs/screenshots/devices.png and b/docs/screenshots/devices.png differ diff --git a/scripts/Package-Server.ps1 b/scripts/Package-Server.ps1 index 2f1a903..a455e68 100644 --- a/scripts/Package-Server.ps1 +++ b/scripts/Package-Server.ps1 @@ -82,6 +82,10 @@ foreach ($rid in $Runtimes) { $staged = $false if (Test-Path $agentMsi) { Copy-Item $agentMsi (Join-Path $agentStage 'Agent.msi'); $staged = $true } if (Test-Path $agentZip) { Copy-Item $agentZip (Join-Path $agentStage 'Agent.zip'); $staged = $true } + foreach ($unixRid in 'linux-x64', 'linux-arm64', 'osx-x64', 'osx-arm64') { + $unixZip = Join-Path $artifacts "Agent-$Version-$unixRid.zip" + if (Test-Path $unixZip) { Copy-Item $unixZip (Join-Path $agentStage "Agent-$unixRid.zip"); $staged = $true } + } if ($staged) { $Version | Set-Content (Join-Path $agentStage 'VERSION') -NoNewline } @@ -130,7 +134,17 @@ ExecuteR standalone server $Version ($rid) 1. $exeName setup Generates NATS keys, the sidecar config and appsettings.json with the admin/admin sign-in (override with --admin-user/--admin-password; - change the password after the first sign-in either way). + change the password after the first sign-in either way). For extra + instances on the same box use one directory each with distinct ports + (--http-port/--nats-port/--nats-ws-port/--nats-monitor-port) and + `service install --name `. + Self-Signed TLS is ON by default: the server serves HTTPS with a + managed, auto-renewed chain so this hop is encrypted (--tls 0 opts + out). Reverse proxies either skip verification (not insecure — the + roots simply are not distributed, the traffic is still encrypted) or + import the root and intermediate to establish trust, re-importing when + they rotate at expiry. Follow your organization's security standards. + Install commands generated by the UI configure agents accordingly. 2. $exeName Serves the UI + API on http://0.0.0.0:9080 with the NATS sidecar. ...or run in the background: @@ -140,6 +154,15 @@ ExecuteR standalone server $Version ($rid) Agent installers ship in ./agent-package, so the URL install command works immediately. Put a TLS-terminating reverse proxy in front for production use; agents enroll against the same base URL. + +Configuration = flat keys in appsettings.json next to the binary, or +environment variables (either works; env wins). Forwarded headers are +trusted by default from private networks (loopback/RFC1918/CGNAT) — +behind a typical proxy nothing needs setting. Optional keys generated +for you: TLS_SELF_SIGNED (built-in hop encryption, on by default — 0 +disables), TLS_CERT_DIR, PUBLIC_SERVER_URL (pin the public base URL), +TRUSTED_NETWORKS (replace the default trust with an allow-list), +TRUSTED_HOSTS, TRUST_PROXY=0 to disable. "@ # ── Zip it ─────────────────────────────────────────────────────────────── diff --git a/src/Agent/Commands/AgentCli.cs b/src/Agent/Commands/AgentCli.cs index 75b03f1..14a51ba 100644 --- a/src/Agent/Commands/AgentCli.cs +++ b/src/Agent/Commands/AgentCli.cs @@ -65,6 +65,12 @@ public static class AgentCli case "status": return Lifecycle.Status(); + // Cross-platform enrollment configuration (registry on Windows, + // /etc/executer/agent.json elsewhere) — what the MSI does via + // properties, expressed as a CLI for the unix install scripts. + case "configure": + return Configure(args[1..]); + case "ensure-pwsh": await Agent.PowerShell.PwshBootstrap.EnsureInstalledAsync( Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, @@ -107,6 +113,52 @@ public static class AgentCli #endif } + private static int Configure(string[] args) + { + string? url = null; + string? token = null; + for (var i = 0; i < args.Length - 1; i++) + { + switch (args[i]) + { + case "--url": + url = args[++i]; + break; + case "--token": + token = args[++i]; + break; + } + } + + var skipTlsVerify = args.Contains("--skip-tls-verify"); + if (url is null && token is null && !skipTlsVerify) + { + Console.Error.WriteLine("Usage: configure --url [--token ] [--skip-tls-verify]"); + return 1; + } + + var registry = Agent.Platform.PlatformServices.CreateRegistryStore(); + if (url is not null) + { + registry.WriteString(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.ServerUrl, url); + } + + if (token is not null) + { + registry.WriteString(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.BootstrapToken, token); + } + + if (skipTlsVerify) + { + // For servers on the managed self-signed chain without a proxy: + // the connection stays TLS-encrypted, validation is skipped. + registry.WriteDword(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.TlsSkipVerify, 1); + } + + Console.WriteLine("Configuration saved. The agent enrolls on next start (`initialize`)."); + return 0; + } + private static int PurgeCredentials() { var runtimeState = new Storage.RuntimeStateStore(Platform.PlatformServices.CreateRegistryStore()); diff --git a/src/Agent/Configuration/AgentConfiguration.cs b/src/Agent/Configuration/AgentConfiguration.cs index 30da32a..a683a21 100644 --- a/src/Agent/Configuration/AgentConfiguration.cs +++ b/src/Agent/Configuration/AgentConfiguration.cs @@ -18,6 +18,7 @@ public sealed class AgentConfiguration public required ConfigurationValue ReconnectMaxDelay { get; init; } public required ConfigurationValue AllowRemoteShell { get; init; } public required ConfigurationValue AllowScriptExecution { get; init; } + public required ConfigurationValue TlsSkipVerify { get; init; } /// Parsed ServerURL; null when unset or invalid. public ServerUrl? ServerUrl => @@ -46,6 +47,7 @@ public sealed class AgentConfigurationLoader(IRegistryStore registry, bool allow ReconnectMaxDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMaxDelay, ProtocolDefaults.ReconnectMaxDelay), AllowRemoteShell = ResolveBool(AgentConfigurationKeys.AllowRemoteShell, defaultValue: false), AllowScriptExecution = ResolveBool(AgentConfigurationKeys.AllowScriptExecution, defaultValue: true), + TlsSkipVerify = ResolveBool(AgentConfigurationKeys.TlsSkipVerify, defaultValue: false), }; } diff --git a/src/Agent/Configuration/AgentConfigurationKeys.cs b/src/Agent/Configuration/AgentConfigurationKeys.cs index db78ac7..796368f 100644 --- a/src/Agent/Configuration/AgentConfigurationKeys.cs +++ b/src/Agent/Configuration/AgentConfigurationKeys.cs @@ -12,6 +12,14 @@ public static class AgentConfigurationKeys public const string AllowRemoteShell = "AllowRemoteShell"; public const string AllowScriptExecution = "AllowScriptExecution"; + /// + /// DWORD 1: accept the server's certificate without validation — for + /// servers running the managed self-signed chain without a proxy. The + /// connection is still TLS-encrypted; the roots just aren't distributed. + /// GPO (policy key) overrides the normal value like every other setting. + /// + public const string TlsSkipVerify = "TlsSkipVerify"; + /// Development-only environment variable names (never override GPO). public static class EnvironmentNames { diff --git a/src/Agent/Configuration/FileRegistryStore.cs b/src/Agent/Configuration/FileRegistryStore.cs index 2f979e8..672f517 100644 --- a/src/Agent/Configuration/FileRegistryStore.cs +++ b/src/Agent/Configuration/FileRegistryStore.cs @@ -62,6 +62,18 @@ public sealed class FileRegistryStore(string? path = null) : IRegistryStore } } + public void WriteDword(string keyPath, string valueName, int value) + { + lock (gate) + { + var root = Load(); + var section = Section(root, keyPath) ?? new JsonObject(); + section[valueName] = value; + root[Normalize(keyPath)] = section; + Save(root); + } + } + public void DeleteValue(string keyPath, string valueName) { lock (gate) diff --git a/src/Agent/Configuration/RegistryStore.cs b/src/Agent/Configuration/RegistryStore.cs index 9031414..300b69c 100644 --- a/src/Agent/Configuration/RegistryStore.cs +++ b/src/Agent/Configuration/RegistryStore.cs @@ -14,6 +14,7 @@ public interface IRegistryStore string? ReadString(string keyPath, string valueName); int? ReadDword(string keyPath, string valueName); void WriteString(string keyPath, string valueName, string value); + void WriteDword(string keyPath, string valueName, int value); void DeleteValue(string keyPath, string valueName); void DeleteKeyTree(string keyPath); } @@ -40,6 +41,12 @@ public sealed class WindowsRegistryStore : IRegistryStore key.SetValue(valueName, value, RegistryValueKind.String); } + public void WriteDword(string keyPath, string valueName, int value) + { + using var key = Registry.LocalMachine.CreateSubKey(keyPath); + key.SetValue(valueName, value, RegistryValueKind.DWord); + } + public void DeleteValue(string keyPath, string valueName) { using var key = Registry.LocalMachine.OpenSubKey(keyPath, writable: true); diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs index a6bd4a0..fcfdeb5 100644 --- a/src/Agent/Enrollment/EnrollmentService.cs +++ b/src/Agent/Enrollment/EnrollmentService.cs @@ -80,7 +80,16 @@ public sealed class EnrollmentService( AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly), Device: ReadDeviceInfo()); - using var http = new HttpClient(); + // TlsSkipVerify (registry/GPO): servers on the managed self-signed + // chain without a proxy — the connection stays TLS-encrypted. + using var handler = new HttpClientHandler(); + if (configuration.TlsSkipVerify.Value) + { + handler.ServerCertificateCustomValidationCallback = + HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + } + + using var http = new HttpClient(handler); var endpoint = serverUrl.ApiEndpoint(ApiRoutes.Bootstrap); logger.LogInformation("Bootstrapping client {ClientId} against {Endpoint}", clientId, endpoint); diff --git a/src/Agent/Messaging/AgentNatsOptionsFactory.cs b/src/Agent/Messaging/AgentNatsOptionsFactory.cs index 87da97e..bffaaf9 100644 --- a/src/Agent/Messaging/AgentNatsOptionsFactory.cs +++ b/src/Agent/Messaging/AgentNatsOptionsFactory.cs @@ -19,7 +19,7 @@ public static class AgentNatsOptionsFactory AgentConfiguration configuration, ILoggerFactory loggerFactory) { - return NatsOpts.Default with + var options = NatsOpts.Default with { Url = serverUrl.AgentWebSocketEndpoint.ToString(), Name = $"agent-{credentials.ClientId}", @@ -36,5 +36,25 @@ public static class AgentNatsOptionsFactory DrainSubscriptionsOnDispose = true, LoggerFactory = loggerFactory, }; + + // TlsSkipVerify (registry/GPO): accept the managed self-signed chain + // on the wss connection — the traffic stays TLS-encrypted. + if (configuration.TlsSkipVerify.Value) + { + options = options with + { + TlsOpts = NatsTlsOpts.Default with { InsecureSkipVerify = true }, + WebSocketOpts = NatsWebSocketOpts.Default with + { + ConfigureClientWebSocketOptions = (_, clientOptions, _) => + { + clientOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; + return ValueTask.CompletedTask; + }, + }, + }; + } + + return options; } } diff --git a/src/Backend/Api/BootstrapTokenEndpoints.cs b/src/Backend/Api/BootstrapTokenEndpoints.cs index e5b8938..6e5cbb8 100644 --- a/src/Backend/Api/BootstrapTokenEndpoints.cs +++ b/src/Backend/Api/BootstrapTokenEndpoints.cs @@ -27,7 +27,14 @@ public static class BootstrapTokenEndpoints var lifetime = request?.ValidMinutes is > 0 ? TimeSpan.FromMinutes(request.ValidMinutes.Value) : ProtocolDefaults.BootstrapTokenDefaultLifetime; - var maxUses = request?.MaxUses is > 0 ? request.MaxUses.Value : ProtocolDefaults.BootstrapTokenDefaultMaxUses; + + // 0 means unlimited uses (expiry and revocation still apply). + if (request?.MaxUses is < 0 or > 9999) + { + return Results.BadRequest(new { error = "maxUses must be between 0 (unlimited) and 9999." }); + } + + var maxUses = request?.MaxUses ?? ProtocolDefaults.BootstrapTokenDefaultMaxUses; // Plaintext exists exactly once: in this response. Only the hash is stored. var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes); diff --git a/src/Backend/Enrollment/EnrollmentEndpoints.cs b/src/Backend/Enrollment/EnrollmentEndpoints.cs index 0b5507a..a8f6b86 100644 --- a/src/Backend/Enrollment/EnrollmentEndpoints.cs +++ b/src/Backend/Enrollment/EnrollmentEndpoints.cs @@ -70,7 +70,9 @@ public static class EnrollmentEndpoints var now = DateTimeOffset.UtcNow; var token = await db.BootstrapTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, cancellationToken); - if (token is null || token.Revoked || token.ExpiresUtc <= now || token.Uses >= token.MaxUses) + // MaxUses 0 = unlimited (expiry and revocation still gate it). + if (token is null || token.Revoked || token.ExpiresUtc <= now + || (token.MaxUses > 0 && token.Uses >= token.MaxUses)) { await audit.LogAsync(AuditCategories.Enrollment, "bootstrap-rejected", clientId: request.ClientId, detail: "invalid, expired or consumed token", remoteIp: remoteIp, diff --git a/src/Backend/Enrollment/InstallEndpoints.cs b/src/Backend/Enrollment/InstallEndpoints.cs index ff083b3..581bdb3 100644 --- a/src/Backend/Enrollment/InstallEndpoints.cs +++ b/src/Backend/Enrollment/InstallEndpoints.cs @@ -26,7 +26,8 @@ public static class InstallEndpoints .AllowAnonymous(); } - private static IResult GetInstallScript(HttpContext context, IConfiguration configuration, string? token, string? type) + private static IResult GetInstallScript( + HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, string? token, string? type) { if (string.IsNullOrWhiteSpace(token)) { @@ -34,14 +35,21 @@ public static class InstallEndpoints } var baseUrl = ResolveBaseUrl(context, configuration); - var packageType = type?.ToLowerInvariant() == "zip" ? "zip" : "msi"; - var packageUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type={packageType}"; + + // Direct self-signed serving: the roots aren't distributed, so the + // installer must skip verification and configure the agent to do the + // same (TlsSkipVerify — the hop stays encrypted either way). + var skipVerify = tls.IsSelfSignedDirect(context); // Token is embedded so the operator can paste one command; knowledge of a // valid token is itself the enrollment gate. - var script = packageType == "zip" - ? BuildZipScript(baseUrl, token!, packageUrl) - : BuildMsiScript(baseUrl, token!, packageUrl); + var script = type?.ToLowerInvariant() switch + { + "linux" => BuildUnixScript(baseUrl, token!, "linux", skipVerify), + "osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipVerify), + "zip" => BuildZipScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip", skipVerify), + _ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", skipVerify), + }; return Results.Text(script, "text/plain; charset=utf-8"); } @@ -50,7 +58,7 @@ public static class InstallEndpoints Files.AgentPackageService packages, string? type, CancellationToken cancellationToken) { var packageType = Files.AgentPackageService.NormalizeType(type); - var fileName = packageType == "zip" ? "Agent.zip" : "Agent.msi"; + var fileName = Files.AgentPackageService.FileNameFor(packageType); // When S3 offload is on, hand the endpoint a presigned URL so the // transfer never touches the control plane. Falls through to local @@ -72,7 +80,7 @@ public static class InstallEndpoints }); } - var contentType = packageType == "zip" ? "application/zip" : "application/x-msi"; + var contentType = packageType == "msi" ? "application/x-msi" : "application/zip"; var stream = File.OpenRead(path); return Results.Stream(stream, contentType, fileDownloadName: fileName, enableRangeProcessing: true); } @@ -80,17 +88,23 @@ public static class InstallEndpoints private static string ResolveBaseUrl(HttpContext context, IConfiguration configuration) => Backend.Proxy.PublicUrl.Resolve(context, configuration); + // The PS5.1-safe global callback is used instead of -SkipCertificateCheck + // (PowerShell 7 only) so the same script works everywhere. + private const string PsSkipVerify = + "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }"; + // NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell. - private static string BuildMsiScript(string baseUrl, string token, string packageUrl) => $$""" + private static string BuildMsiScript(string baseUrl, string token, string packageUrl, bool skipVerify) => $$""" #Requires -RunAsAdministrator $ErrorActionPreference = 'Stop' Write-Host 'Installing ExecuteR Agent...' + {{(skipVerify ? PsSkipVerify : "")}} $server = '{{baseUrl}}' $token = '{{token}}' $msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi') try { Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $msi -UseBasicParsing - $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token") + $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token"{{(skipVerify ? ", 'SKIPTLSVERIFY=1'" : "")}}) $p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" } Write-Host 'ExecuteR Agent installed. It will enroll and start automatically.' @@ -100,10 +114,45 @@ public static class InstallEndpoints } """; - private static string BuildZipScript(string baseUrl, string token, string packageUrl) => $$""" + /// + /// linux/macOS installer: detects the architecture, downloads the matching + /// agent zip, unpacks to /opt/executer/agent, configures enrollment via + /// the agent's own CLI and registers the systemd unit / launchd daemon. + /// + private static string BuildUnixScript(string baseUrl, string token, string os, bool skipVerify) => $$""" + #!/usr/bin/env bash + set -euo pipefail + if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi + server='{{baseUrl}}' + token='{{token}}' + case "$(uname -m)" in + x86_64|amd64) arch=x64 ;; + aarch64|arm64) arch=arm64 ;; + *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;; + esac + pkg="{{baseUrl}}{{ApiRoutes.AgentPackage}}?type={{os}}-${arch}" + dest=/opt/executer/agent + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + echo "Installing ExecuteR Agent ({{os}}-${arch})..." + curl -fsSL{{(skipVerify ? "k" : "")}} "$pkg" -o "$tmp/agent.zip" + mkdir -p "$dest" + if command -v unzip >/dev/null 2>&1; then + unzip -oq "$tmp/agent.zip" -d "$dest" + else + python3 -m zipfile -e "$tmp/agent.zip" "$dest" + fi + chmod +x "$dest/executer-agent" + "$dest/executer-agent" configure --url "$server" --token "$token"{{(skipVerify ? " --skip-tls-verify" : "")}} + "$dest/executer-agent" initialize + echo 'ExecuteR Agent installed. It will enroll and start automatically.' + """; + + private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipVerify) => $$""" #Requires -RunAsAdministrator $ErrorActionPreference = 'Stop' Write-Host 'Installing ExecuteR Agent (portable)...' + {{(skipVerify ? PsSkipVerify : "")}} $server = '{{baseUrl}}' $token = '{{token}}' $dest = Join-Path $env:ProgramFiles 'ExecuteR Agent' @@ -117,6 +166,7 @@ public static class InstallEndpoints New-Item -Path 'HKLM:\SOFTWARE\ExecuteR' -Force | Out-Null Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'ServerURL' -Value $server Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'BootstrapToken' -Value $token + {{(skipVerify ? "Set-ItemProperty -Path 'HKLM:\\SOFTWARE\\ExecuteR' -Name 'TlsSkipVerify' -Value 1 -Type DWord" : "")}} & $exe initialize Write-Host 'ExecuteR Agent installed and starting.' } diff --git a/src/Backend/Files/AgentPackageService.cs b/src/Backend/Files/AgentPackageService.cs index 0dd17f3..eb90527 100644 --- a/src/Backend/Files/AgentPackageService.cs +++ b/src/Backend/Files/AgentPackageService.cs @@ -28,10 +28,19 @@ public sealed class AgentPackageService( public const string BakedInPath = "/opt/executer/agent"; public const string SeededPath = "/data/agent"; - private static string FileNameFor(string packageType) => packageType == "zip" ? "Agent.zip" : "Agent.msi"; + public static string FileNameFor(string packageType) => packageType switch + { + "zip" => "Agent.zip", + "linux-x64" or "linux-arm64" or "osx-x64" or "osx-arm64" => $"Agent-{packageType}.zip", + _ => "Agent.msi", + }; - public static string NormalizeType(string? type) - => string.Equals(type, "zip", StringComparison.OrdinalIgnoreCase) ? "zip" : "msi"; + public static string NormalizeType(string? type) => type?.ToLowerInvariant() switch + { + "zip" => "zip", + "linux-x64" or "linux-arm64" or "osx-x64" or "osx-arm64" => type.ToLowerInvariant(), + _ => "msi", + }; /// Directories searched, most specific first. private IEnumerable CandidateDirectories() diff --git a/src/Backend/Program.cs b/src/Backend/Program.cs index 3e501ad..4534ea5 100644 --- a/src/Backend/Program.cs +++ b/src/Backend/Program.cs @@ -13,6 +13,7 @@ using Backend.Scripts; using Backend.Security; using Backend.Settings; using Backend.Shell; +using Backend.Tls; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; @@ -81,6 +82,28 @@ builder.Services.ConfigureHttpJsonOptions(options => var proxySettings = ProxySettings.FromConfiguration(builder.Configuration); builder.Services.AddSingleton(proxySettings); +// ── Built-in encryption (self-signed, on by default) ───────────────────── +// The listener serves HTTPS with a locally managed chain (root > +// intermediate > leaf, auto-renewed, hot-swapped) so the proxy-to-server +// hop cannot be sniffed; TLS_SELF_SIGNED=0 opts out. Proxies either skip +// verification (the hop is still encrypted — the roots just aren't +// distributed) or import root+intermediate. Public TLS stays at the edge. +var tlsSettings = TlsSettings.FromConfiguration(builder.Configuration); +builder.Services.AddSingleton(tlsSettings); +SelfSignedTlsManager? tlsManager = null; +if (tlsSettings.Enabled) +{ + tlsManager = new SelfSignedTlsManager(tlsSettings); + builder.Services.AddSingleton(tlsManager); + builder.Services.AddHostedService(); + builder.WebHost.ConfigureKestrel(kestrel => kestrel.ConfigureHttpsDefaults(https => + https.ServerCertificateSelector = (_, _) => tlsManager.ServerCertificate)); + var listenUrls = builder.Configuration["urls"] is { Length: > 0 } configured + ? configured + : "http://0.0.0.0:8080"; + builder.WebHost.UseUrls(listenUrls.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)); +} + // ── Persistence ────────────────────────────────────────────────────────── // SQLite by default; Postgres and SQL Server are selected with // DATABASE_PROVIDER + DATABASE_CONNECTION_STRING. Each provider carries its @@ -174,6 +197,23 @@ builder.Services.AddRateLimiter(options => var app = builder.Build(); +// The chain must exist before Kestrel accepts the first TLS handshake. +if (tlsManager is not null) +{ + tlsManager.EnsureChain(app.Logger); + if (tlsManager.UsesWindowsStore) + { + app.Logger.LogInformation( + "Built-in TLS: serving HTTPS with the managed self-signed chain from the Windows certificate stores (proxies: skip verification or import the root+intermediate)"); + } + else + { + app.Logger.LogInformation( + "Built-in TLS: serving HTTPS with the managed self-signed chain in {Directory} (proxies: skip verification or pin fullchain.crt)", + tlsSettings.CertificateDirectory); + } +} + // Apply EF migrations at startup; seed the demo script in development. using (var scope = app.Services.CreateScope()) { @@ -227,16 +267,16 @@ using (var scope = app.Services.CreateScope()) } // Forwarded headers must run before anything that inspects scheme/host/IP. +// Trust defaults to private address space (loopback/RFC1918/CGNAT) so the +// stack drops behind any reverse proxy with zero configuration; explicit +// TRUSTED_PROXIES/TRUSTED_NETWORKS narrows it, TRUST_PROXY=0 disables. if (proxySettings.TrustProxy) { - if (!proxySettings.HasExplicitTrustSources && !app.Environment.IsDevelopment()) - { - throw new InvalidOperationException( - "TRUST_PROXY=1 requires TRUSTED_PROXIES or TRUSTED_NETWORKS outside development mode. " + - "Refusing to trust X-Forwarded-* headers from anywhere."); - } - app.UseForwardedHeaders(proxySettings.ToForwardedHeadersOptions()); + app.Logger.LogInformation( + proxySettings.HasExplicitTrustSources + ? "Forwarded headers trusted from the configured proxies/networks" + : "Forwarded headers trusted from private networks (loopback, RFC1918, CGNAT) — set TRUSTED_NETWORKS to narrow"); } // Structured request logging: one line per request, enriched with the diff --git a/src/Backend/Proxy/ProxySettings.cs b/src/Backend/Proxy/ProxySettings.cs index 0333da5..d8bbd2b 100644 --- a/src/Backend/Proxy/ProxySettings.cs +++ b/src/Backend/Proxy/ProxySettings.cs @@ -4,12 +4,26 @@ using Microsoft.AspNetCore.HttpOverrides; namespace Backend.Proxy; /// -/// Reverse-proxy trust configuration. TRUST_PROXY=1 alone is not enough: -/// outside development mode at least one trusted proxy or network must be -/// configured, otherwise forwarded headers are ignored. +/// Reverse-proxy trust configuration. Forwarded headers are trusted BY DEFAULT +/// from private address space — loopback, RFC1918 and CGNAT — so slapping the +/// stack behind a reverse proxy (cloud or LAN) needs zero configuration. +/// Setting TRUSTED_PROXIES / TRUSTED_NETWORKS replaces those defaults with an +/// explicit allow-list (narrow this on networks where peers are untrusted), +/// and TRUST_PROXY=0 disables forwarded-header processing entirely. /// public sealed class ProxySettings { + /// Private ranges a reverse proxy realistically lives in. + public static readonly IReadOnlyList<(IPAddress Prefix, int PrefixLength)> DefaultTrustedNetworks = + [ + (IPAddress.Parse("127.0.0.0"), 8), // loopback + (IPAddress.IPv6Loopback, 128), // ::1 + (IPAddress.Parse("10.0.0.0"), 8), // RFC1918 + (IPAddress.Parse("172.16.0.0"), 12), // RFC1918 + (IPAddress.Parse("192.168.0.0"), 16), // RFC1918 + (IPAddress.Parse("100.64.0.0"), 10), // CGNAT (RFC6598) + ]; + public bool TrustProxy { get; init; } public IReadOnlyList TrustedProxies { get; init; } = []; public IReadOnlyList<(IPAddress Prefix, int PrefixLength)> TrustedNetworks { get; init; } = []; @@ -18,9 +32,14 @@ public sealed class ProxySettings public bool HasExplicitTrustSources => TrustedProxies.Count > 0 || TrustedNetworks.Count > 0; + /// The networks actually applied: explicit config, or the private-range defaults. + public IReadOnlyList<(IPAddress Prefix, int PrefixLength)> EffectiveNetworks + => HasExplicitTrustSources ? TrustedNetworks : DefaultTrustedNetworks; + public static ProxySettings FromConfiguration(IConfiguration configuration) { - var trustProxy = configuration["TRUST_PROXY"] == "1"; + // Trust is the default; TRUST_PROXY=0 opts out entirely. + var trustProxy = configuration["TRUST_PROXY"] != "0"; var proxies = SplitList(configuration["TRUSTED_PROXIES"]) .Select(value => IPAddress.TryParse(value, out var ip) ? ip : null) @@ -63,7 +82,9 @@ public sealed class ProxySettings ForwardLimit = ForwardLimit, }; - // Do NOT trust every source: clear defaults, add configured ones only. + // Never trust every source: clear the framework defaults, then apply + // the explicit allow-list — or the private-range defaults when none + // was configured. options.KnownProxies.Clear(); options.KnownIPNetworks.Clear(); foreach (var proxy in TrustedProxies) @@ -71,7 +92,7 @@ public sealed class ProxySettings options.KnownProxies.Add(proxy); } - foreach (var (prefix, length) in TrustedNetworks) + foreach (var (prefix, length) in EffectiveNetworks) { options.KnownIPNetworks.Add(new System.Net.IPNetwork(prefix, length)); } diff --git a/src/Backend/Settings/SettingsEndpoints.cs b/src/Backend/Settings/SettingsEndpoints.cs index 4bb515d..056dac4 100644 --- a/src/Backend/Settings/SettingsEndpoints.cs +++ b/src/Backend/Settings/SettingsEndpoints.cs @@ -28,11 +28,14 @@ public static class SettingsEndpoints /// The externally reachable base URL for display and generated commands: /// PUBLIC_SERVER_URL when set, else derived from trusted forwarded headers. /// - private static IResult GetServerInfo(HttpContext context, IConfiguration configuration) + private static IResult GetServerInfo(HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls) => Results.Ok(new { baseUrl = Backend.Proxy.PublicUrl.Resolve(context, configuration), fromEnvironment = Backend.Proxy.PublicUrl.IsConfigured(configuration), + // Direct self-signed serving: generated commands must skip TLS + // verification (the hop is still encrypted). + selfSignedDirect = tls.IsSelfSignedDirect(context), }); private static async Task GetS3Async(S3SettingsService settings, CancellationToken cancellationToken) diff --git a/src/Backend/Standalone/NatsSidecar.cs b/src/Backend/Standalone/NatsSidecar.cs index 2741242..e645014 100644 --- a/src/Backend/Standalone/NatsSidecar.cs +++ b/src/Backend/Standalone/NatsSidecar.cs @@ -144,12 +144,16 @@ public sealed class NatsSidecar(IConfiguration configuration, ILoggerPolls the monitor endpoint so callers connect to a live server. private async Task WaitForReadyAsync(CancellationToken cancellationToken) { + var monitor = configuration["NATS_MONITOR_URL"] is { Length: > 0 } url + ? url.TrimEnd('/') + : "http://127.0.0.1:8222"; + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) }; for (var attempt = 0; attempt < 40; attempt++) { try { - var response = await http.GetAsync("http://127.0.0.1:8222/healthz", cancellationToken); + var response = await http.GetAsync($"{monitor}/healthz", cancellationToken); if (response.IsSuccessStatusCode) { logger.LogInformation("NATS sidecar is ready"); diff --git a/src/Backend/Standalone/ServerCli.cs b/src/Backend/Standalone/ServerCli.cs index a566e75..e4d55e6 100644 --- a/src/Backend/Standalone/ServerCli.cs +++ b/src/Backend/Standalone/ServerCli.cs @@ -9,7 +9,7 @@ namespace Backend.Standalone; /// /// Standalone-server commands for the combined single-binary deployment: /// -/// setup [--admin-user U] [--admin-password P] +/// setup [--admin-user U] [--admin-password P] [--tls 0] /// — generate NATS keys + sidecar config + appsettings, /// downloading nats-server for this platform if absent /// service install — register as a Windows service / systemd unit @@ -29,14 +29,50 @@ public static class ServerCli { // Bare `setup` fully configures the server: admin/admin unless the // flags override — and the defaulted password forces a reset prompt - // on the first sign-in. + // on the first sign-in. Port flags let several instances share a box + // (one directory per instance; pair with `service install --name`). var adminUser = "admin"; var adminPassword = "admin"; var passwordDefaulted = true; + var httpPort = 9080; + var bindAddress = "0.0.0.0"; + var natsPort = 4222; + var natsWsPort = 9222; + var natsMonitorPort = 8222; + // Self-signed TLS is on by default; --tls 0 (or an unchecked MSI + // checkbox, which passes an empty value) opts out. + var selfSignedTls = true; for (var i = 0; i < args.Length - 1; i++) { switch (args[i]) { + case "--tls": + // The MSI always passes a value ("" unchecked, "1" + // checked); humans may use the bare flag or --tls 0. + var tlsValue = args[++i]; + if (tlsValue.StartsWith("--", StringComparison.Ordinal)) + { + selfSignedTls = true; + i--; + } + else + { + selfSignedTls = tlsValue == "1"; + } + + break; + case "--bind": + var candidate = args[++i]; + if (!System.Net.IPAddress.TryParse(candidate, out var parsed)) + { + throw new ArgumentException($"--bind must be an IP address (got '{candidate}')."); + } + + // IPv6 literals need brackets in the Urls syntax. + bindAddress = parsed.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 + ? $"[{parsed}]" + : parsed.ToString(); + break; case "--admin-user": adminUser = args[++i]; break; @@ -46,9 +82,32 @@ public static class ServerCli // kept: a literal "admin" password always forces the reset. passwordDefaulted = adminPassword == "admin"; break; + // Short aliases keep the MSI's custom-action command inside + // the 255-character CustomAction table column (ICE03). + case "--http-port": + case "--http": + httpPort = ParsePort(args[++i], "--http-port"); + break; + case "--nats-port": + case "--nats": + natsPort = ParsePort(args[++i], "--nats-port"); + break; + case "--nats-ws-port": + case "--ws": + natsWsPort = ParsePort(args[++i], "--nats-ws-port"); + break; + case "--nats-monitor-port": + case "--monitor": + natsMonitorPort = ParsePort(args[++i], "--nats-monitor-port"); + break; } } + if (args.Length > 0 && args[^1] == "--tls") + { + selfSignedTls = true; + } + var baseDir = AppContext.BaseDirectory; var natsDir = Path.Combine(baseDir, "nats"); var secretsDir = Path.Combine(baseDir, "secrets", "nats"); @@ -85,21 +144,21 @@ public static class ServerCli { // Paths are RELATIVE to the config file: nats-server mangles // Windows drive-letter absolutes in `include` directives. - File.WriteAllText(natsConf, """ + File.WriteAllText(natsConf, $$""" # Generated by `setup` for the standalone ExecuteR server. server_name: executer-standalone # Local-only listeners: the server binary proxies /messaging/* # to the websocket port; nothing here is exposed publicly. - listen: 127.0.0.1:4222 - http: 127.0.0.1:8222 + listen: 127.0.0.1:{{natsPort}} + http: 127.0.0.1:{{natsMonitorPort}} jetstream { store_dir: "../data/jetstream" } websocket { - listen: 127.0.0.1:9222 + listen: 127.0.0.1:{{natsWsPort}} no_tls: true } @@ -107,6 +166,10 @@ public static class ServerCli """); Console.WriteLine($"Wrote {natsConf}"); } + else + { + Console.WriteLine($"Existing {natsConf} kept — delete it and appsettings.json to apply new ports."); + } // Server settings: the default configuration for standalone mode. var appsettings = Path.Combine(baseDir, "appsettings.json"); @@ -116,19 +179,27 @@ public static class ServerCli var accountPublic = File.ReadAllText(Path.Combine(secretsDir, "account.pub")).Trim(); File.WriteAllText(appsettings, $$""" { - "Urls": "http://0.0.0.0:9080", + "Urls": "http://{{bindAddress}}:{{httpPort}}", "DATABASE_PATH": "{{Path.Combine(dataDir, "app.db").Replace('\\', '/')}}", "DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}", "LOG_PATH": "{{Path.Combine(dataDir, "logs").Replace('\\', '/')}}", "AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}", - "NATS_URL": "nats://127.0.0.1:4222", + "NATS_URL": "nats://127.0.0.1:{{natsPort}}", "NATS_SIDECAR": "1", - "NATS_WS_PROXY": "ws://127.0.0.1:9222", + "NATS_WS_PROXY": "ws://127.0.0.1:{{natsWsPort}}", + "NATS_MONITOR_URL": "http://127.0.0.1:{{natsMonitorPort}}", "NATS_ACCOUNT_SIGNING_SEED": "{{signingSeed}}", "NATS_ACCOUNT_PUBLIC_KEY": "{{accountPublic}}", "INITIAL_ADMIN_USERNAME": "{{adminUser}}", "INITIAL_ADMIN_PASSWORD": "{{adminPassword}}", - "INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}" + "INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}", + + "TLS_SELF_SIGNED": "{{(selfSignedTls ? "1" : "0")}}", + "TLS_CERT_DIR": "", + "PUBLIC_SERVER_URL": "", + "TRUST_PROXY": "1", + "TRUSTED_NETWORKS": "", + "TRUSTED_HOSTS": "" } """); Console.WriteLine($"Wrote {appsettings}"); @@ -139,11 +210,26 @@ public static class ServerCli Console.WriteLine(passwordDefaulted ? $" - First sign-in: {adminUser} / admin — a new password is required immediately." : $" - First sign-in: {adminUser} / ."); - Console.WriteLine(" - Run the binary directly, or `service install` to run in the background."); + var scheme = selfSignedTls ? "https" : "http"; + Console.WriteLine($" - UI + API on {scheme}://{bindAddress}:{httpPort} (NATS local-only on {natsPort}/{natsWsPort}/{natsMonitorPort})."); + if (selfSignedTls) + { + Console.WriteLine(" - Self-signed TLS: the hop is encrypted; reverse proxies either skip"); + Console.WriteLine(" verification (not insecure — the roots just aren't distributed) or"); + Console.WriteLine(" import the root+intermediate to establish trust (re-import when they"); + Console.WriteLine(" rotate at expiry). Follow your organization's security standards."); + } + + Console.WriteLine(" - Run the binary directly, or `service install` (add --name for extra instances)."); Console.WriteLine(" - Put a TLS-terminating proxy in front for production use."); return 0; } + private static int ParsePort(string value, string flag) + => int.TryParse(value, out var port) && port is >= 1 and <= 65535 + ? port + : throw new ArgumentException($"{flag} must be a port between 1 and 65535."); + /// /// Downloads and unpacks nats-server for the current OS/architecture when /// it is not already next to the binary. Idempotent; packaged bundles ship @@ -243,45 +329,61 @@ public static class ServerCli { if (args.Length == 0) { - Console.Error.WriteLine("Usage: service install|uninstall"); + Console.Error.WriteLine("Usage: service install|uninstall [--name ]"); return 1; } var exe = Environment.ProcessPath ?? throw new InvalidOperationException("Cannot determine the executable path."); + // --name lets several instances (one directory each, distinct ports + // from `setup`) register side by side on the same box. + var name = OperatingSystem.IsWindows() ? WindowsServiceName : SystemdUnitName; + for (var i = 1; i < args.Length - 1; i++) + { + if (args[i] == "--name" && args[i + 1] is { Length: > 0 } custom) + { + if (!System.Text.RegularExpressions.Regex.IsMatch(custom, "^[A-Za-z0-9._-]+$")) + { + return Fail("--name may only contain letters, digits, dot, underscore and dash."); + } + + name = custom; + } + } + return args[0] switch { - "install" => OperatingSystem.IsWindows() ? InstallWindows(exe) : InstallSystemd(exe), - "uninstall" => OperatingSystem.IsWindows() ? UninstallWindows() : UninstallSystemd(), + "install" => OperatingSystem.IsWindows() ? InstallWindows(exe, name) : InstallSystemd(exe, name), + "uninstall" => OperatingSystem.IsWindows() ? UninstallWindows(name) : UninstallSystemd(name), _ => Fail($"Unknown service command '{args[0]}'."), }; } - private static int InstallWindows(string exe) + private static int InstallWindows(string exe, string name) { // Idempotent: create may fail when the service exists (repair or MSI // upgrade); config then points it at the current binary either way. - Run("sc.exe", $"create {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server\"", ignoreErrors: true); - Run("sc.exe", $"config {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto"); - Run("sc.exe", $"description {WindowsServiceName} \"ExecuteR control plane (UI, API, messaging).\""); - Run("sc.exe", $"failure {WindowsServiceName} reset= 86400 actions= restart/30000/restart/30000/restart/30000"); - Run("sc.exe", $"start {WindowsServiceName}", ignoreErrors: true); - Console.WriteLine($"Service {WindowsServiceName} installed and started."); + Run("sc.exe", $"create {name} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server ({name})\"", ignoreErrors: true); + Run("sc.exe", $"config {name} binPath= \"\\\"{exe}\\\"\" start= delayed-auto"); + Run("sc.exe", $"description {name} \"ExecuteR control plane (UI, API, messaging).\""); + Run("sc.exe", $"failure {name} reset= 86400 actions= restart/30000/restart/30000/restart/30000"); + Run("sc.exe", $"start {name}", ignoreErrors: true); + Console.WriteLine($"Service {name} installed and started."); return 0; } - private static int UninstallWindows() + private static int UninstallWindows(string name) { - Run("sc.exe", $"stop {WindowsServiceName}", ignoreErrors: true); - Run("sc.exe", $"delete {WindowsServiceName}"); - Console.WriteLine($"Service {WindowsServiceName} stopped and removed."); + Run("sc.exe", $"stop {name}", ignoreErrors: true); + Run("sc.exe", $"delete {name}"); + Console.WriteLine($"Service {name} stopped and removed."); return 0; } - private static int InstallSystemd(string exe) + private static int InstallSystemd(string exe, string name) { - var unit = $"/etc/systemd/system/{SystemdUnitName}.service"; + var unit = $"/etc/systemd/system/{name}.service"; File.WriteAllText(unit, $""" [Unit] Description=ExecuteR Server (control plane: UI, API, messaging) @@ -299,22 +401,22 @@ public static class ServerCli WantedBy=multi-user.target """); Run("systemctl", "daemon-reload"); - Run("systemctl", $"enable --now {SystemdUnitName}"); - Console.WriteLine($"systemd unit {SystemdUnitName} installed and started."); + Run("systemctl", $"enable --now {name}"); + Console.WriteLine($"systemd unit {name} installed and started."); return 0; } - private static int UninstallSystemd() + private static int UninstallSystemd(string name) { - Run("systemctl", $"disable --now {SystemdUnitName}", ignoreErrors: true); - var unit = $"/etc/systemd/system/{SystemdUnitName}.service"; + Run("systemctl", $"disable --now {name}", ignoreErrors: true); + var unit = $"/etc/systemd/system/{name}.service"; if (File.Exists(unit)) { File.Delete(unit); } Run("systemctl", "daemon-reload"); - Console.WriteLine($"systemd unit {SystemdUnitName} stopped and removed."); + Console.WriteLine($"systemd unit {name} stopped and removed."); return 0; } diff --git a/src/Backend/Tls/SelfSignedTlsManager.cs b/src/Backend/Tls/SelfSignedTlsManager.cs new file mode 100644 index 0000000..0de3374 --- /dev/null +++ b/src/Backend/Tls/SelfSignedTlsManager.cs @@ -0,0 +1,208 @@ +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Backend.Tls; + +/// Chain lifetimes and how early each link is re-issued. +public sealed record TlsLifetimes( + TimeSpan Root, + TimeSpan Intermediate, + TimeSpan Leaf, + TimeSpan RootRenewalMargin, + TimeSpan IntermediateRenewalMargin, + TimeSpan LeafRenewalMargin) +{ + public static readonly TlsLifetimes Default = new( + Root: TimeSpan.FromDays(3650), + Intermediate: TimeSpan.FromDays(1825), + Leaf: TimeSpan.FromDays(365), + RootRenewalMargin: TimeSpan.FromDays(365), + IntermediateRenewalMargin: TimeSpan.FromDays(180), + LeafRenewalMargin: TimeSpan.FromDays(30)); +} + +/// +/// Owns the managed self-signed chain: ECDSA root > intermediate > leaf, +/// created on first boot, re-issued ahead of expiry, hot-swapped into the +/// live listener through (Kestrel's +/// certificate selector reads it on every handshake — renewals need no +/// restart). Windows persists to the machine certificate stores; everywhere +/// else (or with TLS_CERT_DIR set) the chain is PEM files. +/// +public sealed class SelfSignedTlsManager +{ + private readonly Lock gate = new(); + private readonly TlsSettings settings; + private readonly TlsLifetimes lifetimes; + private readonly ITlsPersistence persistence; + private X509Certificate2? leaf; + + public SelfSignedTlsManager(TlsSettings settings, TlsLifetimes? lifetimes = null) + { + this.settings = settings; + this.lifetimes = lifetimes ?? TlsLifetimes.Default; + persistence = CreatePersistence(settings); + } + + private static ITlsPersistence CreatePersistence(TlsSettings settings) + { + if (OperatingSystem.IsWindows() && settings.UseWindowsStore && WindowsStoreTlsPersistence.IsAvailable()) + { + return new WindowsStoreTlsPersistence(settings.CertificateDirectory); + } + + return new FileTlsPersistence(settings.CertificateDirectory); + } + + public bool UsesWindowsStore => persistence is WindowsStoreTlsPersistence; + + /// The current server certificate; null until the first EnsureChain. + public X509Certificate2? ServerCertificate => Volatile.Read(ref leaf); + + /// + /// Creates or re-issues whatever links are missing, expiring, or no + /// longer signed by the current parent (a rotated root cascades down). + /// Idempotent; returns true when anything was issued. + /// + public bool EnsureChain(ILogger logger) + { + lock (gate) + { + var now = DateTimeOffset.UtcNow; + var changed = false; + + var root = persistence.Load(TlsRole.Root); + if (!IsUsable(root, now, lifetimes.RootRenewalMargin)) + { + root = persistence.Save(TlsRole.Root, CreateRoot(now)); + logger.LogInformation( + "Self-signed TLS: issued a new root CA (valid to {NotAfter:u})", + root.NotAfter.ToUniversalTime()); + changed = true; + } + + var intermediate = persistence.Load(TlsRole.Intermediate); + if (!IsUsable(intermediate, now, lifetimes.IntermediateRenewalMargin) + || !IsIssuedBy(intermediate, root)) + { + intermediate = persistence.Save(TlsRole.Intermediate, CreateIntermediate(root, now)); + logger.LogInformation( + "Self-signed TLS: issued a new intermediate CA (valid to {NotAfter:u})", + intermediate.NotAfter.ToUniversalTime()); + changed = true; + } + + var current = persistence.Load(TlsRole.Leaf); + if (!IsUsable(current, now, lifetimes.LeafRenewalMargin) + || !IsIssuedBy(current, root, intermediate)) + { + current = persistence.Save(TlsRole.Leaf, CreateLeaf(intermediate, now)); + logger.LogInformation( + "Self-signed TLS: issued a new server certificate for {DnsNames} (valid to {NotAfter:u})", + string.Join(", ", settings.DnsNames), current.NotAfter.ToUniversalTime()); + changed = true; + } + + persistence.Complete(root, intermediate, current); + Volatile.Write(ref leaf, current); + return changed; + } + } + + private static bool IsUsable( + [NotNullWhen(true)] X509Certificate2? certificate, DateTimeOffset now, TimeSpan renewalMargin) + => certificate is not null + && certificate.HasPrivateKey + && certificate.NotBefore.ToUniversalTime() <= now.AddMinutes(5) + && certificate.NotAfter.ToUniversalTime() > now + renewalMargin; + + /// Real signature validation, so a rotated parent re-issues the children. + private static bool IsIssuedBy(X509Certificate2 child, X509Certificate2 root, X509Certificate2? intermediate = null) + { + using var chain = new X509Chain(); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + chain.ChainPolicy.CustomTrustStore.Add(root); + if (intermediate is not null) + { + chain.ChainPolicy.ExtraStore.Add(intermediate); + } + + return chain.Build(child); + } + + private X509Certificate2 CreateRoot(DateTimeOffset now) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP384); + var request = new CertificateRequest(TlsSubjects.Root, key, HashAlgorithmName.SHA384); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension( + certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 1, critical: true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension( + X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true)); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); + return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root); + } + + private X509Certificate2 CreateIntermediate(X509Certificate2 root, DateTimeOffset now) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP384); + var request = new CertificateRequest(TlsSubjects.Intermediate, key, HashAlgorithmName.SHA384); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension( + certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 0, critical: true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension( + X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true)); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); + request.CertificateExtensions.Add( + X509AuthorityKeyIdentifierExtension.CreateFromCertificate( + root, includeKeyIdentifier: true, includeIssuerAndSerial: false)); + using var issued = request.Create(root, now.AddMinutes(-5), NotAfter(now + lifetimes.Intermediate, root), Serial()); + return issued.CopyWithPrivateKey(key); + } + + private X509Certificate2 CreateLeaf(X509Certificate2 intermediate, DateTimeOffset now) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest(TlsSubjects.Leaf, key, HashAlgorithmName.SHA256); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension( + certificateAuthority: false, hasPathLengthConstraint: false, pathLengthConstraint: 0, critical: true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension( + X509KeyUsageFlags.DigitalSignature, critical: true)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + [new Oid("1.3.6.1.5.5.7.3.1")], critical: false)); // TLS server authentication + + var san = new SubjectAlternativeNameBuilder(); + foreach (var name in settings.DnsNames) + { + san.AddDnsName(name); + } + + foreach (var address in settings.IpAddresses) + { + san.AddIpAddress(address); + } + + request.CertificateExtensions.Add(san.Build()); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); + request.CertificateExtensions.Add( + X509AuthorityKeyIdentifierExtension.CreateFromCertificate( + intermediate, includeKeyIdentifier: true, includeIssuerAndSerial: false)); + using var issued = request.Create( + intermediate, now.AddMinutes(-5), NotAfter(now + lifetimes.Leaf, intermediate), Serial()); + return issued.CopyWithPrivateKey(key); + } + + /// A child must not outlive its issuer. + private static DateTimeOffset NotAfter(DateTimeOffset requested, X509Certificate2 issuer) + { + var issuerNotAfter = new DateTimeOffset(issuer.NotAfter).AddMinutes(-1); + return requested < issuerNotAfter ? requested : issuerNotAfter; + } + + private static byte[] Serial() + { + var serial = RandomNumberGenerator.GetBytes(16); + serial[0] &= 0x7F; + return serial; + } +} diff --git a/src/Backend/Tls/TlsPersistence.cs b/src/Backend/Tls/TlsPersistence.cs new file mode 100644 index 0000000..a83220d --- /dev/null +++ b/src/Backend/Tls/TlsPersistence.cs @@ -0,0 +1,226 @@ +using System.Runtime.Versioning; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Backend.Tls; + +internal enum TlsRole +{ + Root, + Intermediate, + Leaf, +} + +internal static class TlsSubjects +{ + public const string Root = "CN=ExecuteR Self-Signed Root CA"; + public const string Intermediate = "CN=ExecuteR Self-Signed Intermediate CA"; + public const string Leaf = "CN=ExecuteR Server"; + + public static string For(TlsRole role) => role switch + { + TlsRole.Root => Root, + TlsRole.Intermediate => Intermediate, + _ => Leaf, + }; +} + +/// +/// Where the managed chain lives. Save replaces any previous certificate for +/// the role and returns the instance to keep using (backends may need to +/// re-import the key into an OS-appropriate container). +/// +internal interface ITlsPersistence +{ + X509Certificate2? Load(TlsRole role); + + X509Certificate2 Save(TlsRole role, X509Certificate2 fresh); + + /// Called after the chain settles so backends can write derived material. + void Complete(X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 leaf); +} + +/// +/// PEM files (root/intermediate/server .crt + .key, keys chmod 600 on unix) +/// — the mode for Linux, macOS, containers, and TLS_CERT_DIR overrides. +/// +internal sealed class FileTlsPersistence(string directory) : ITlsPersistence +{ + private static readonly Dictionary Names = new() + { + [TlsRole.Root] = ("root.crt", "root.key"), + [TlsRole.Intermediate] = ("intermediate.crt", "intermediate.key"), + [TlsRole.Leaf] = ("server.crt", "server.key"), + }; + + public X509Certificate2? Load(TlsRole role) + { + var (certName, keyName) = Names[role]; + var certPath = Path.Combine(directory, certName); + var keyPath = Path.Combine(directory, keyName); + if (!File.Exists(certPath) || !File.Exists(keyPath)) + { + return null; + } + + try + { + using var pem = X509Certificate2.CreateFromPemFile(certPath, keyPath); + return WithUsableKey(pem); + } + catch (CryptographicException) + { + // Corrupt or mismatched pair: treat as absent and regenerate. + return null; + } + } + + public X509Certificate2 Save(TlsRole role, X509Certificate2 fresh) + { + WritePem(role, fresh); + return WithUsableKey(fresh); + } + + /// Writes the cert (and its key when exportable) as PEM. + public void WritePem(TlsRole role, X509Certificate2 certificate) + { + Directory.CreateDirectory(directory); + var (certName, keyName) = Names[role]; + using var key = certificate.GetECDsaPrivateKey(); + if (key is not null) + { + WriteSecret(Path.Combine(directory, keyName), key.ExportPkcs8PrivateKeyPem()); + } + + File.WriteAllText(Path.Combine(directory, certName), certificate.ExportCertificatePem()); + } + + public void Complete(X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 leaf) + { + // For proxies that prefer pinning the chain over skipping verification. + File.WriteAllText(Path.Combine(directory, "fullchain.crt"), + leaf.ExportCertificatePem() + '\n' + + intermediate.ExportCertificatePem() + '\n' + + root.ExportCertificatePem() + '\n'); + } + + /// SChannel rejects ephemeral PEM keys; round-trip through PFX on Windows. + private static X509Certificate2 WithUsableKey(X509Certificate2 certificate) + => OperatingSystem.IsWindows() + ? X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null) + : certificate; + + private static void WriteSecret(string path, string content) + { + File.WriteAllText(path, content); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } +} + +/// +/// The Windows machine certificate stores: root in Trusted Root Certification +/// Authorities, intermediate in Intermediate Certification Authorities, leaf +/// in Personal — each with its private key persisted in the machine key set +/// so renewal can re-sign without files on disk. Browsers on the server +/// itself trust the chain automatically. The stores stay authoritative, but +/// every chain settle also mirrors the PEM files (certs + keys + fullchain) +/// to the certificate directory so a local proxy — Caddy, Nginx UI, nginx — +/// can bind or trust them, and renewals keep that mirror current. +/// +[SupportedOSPlatform("windows")] +internal sealed class WindowsStoreTlsPersistence(string mirrorDirectory) : ITlsPersistence +{ + private readonly FileTlsPersistence mirror = new(mirrorDirectory); + + private static StoreName StoreFor(TlsRole role) => role switch + { + TlsRole.Root => StoreName.Root, + TlsRole.Intermediate => StoreName.CertificateAuthority, + _ => StoreName.My, + }; + + /// Machine stores need elevation; unelevated runs fall back to files. + public static bool IsAvailable() + { + if (!OperatingSystem.IsWindows()) + { + return false; + } + + try + { + using var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); + store.Open(OpenFlags.ReadWrite); + return true; + } + catch (Exception) + { + return false; + } + } + + public X509Certificate2? Load(TlsRole role) + { + using var store = new X509Store(StoreFor(role), StoreLocation.LocalMachine); + store.Open(OpenFlags.ReadOnly); + return store.Certificates + .Find(X509FindType.FindBySubjectDistinguishedName, TlsSubjects.For(role), validOnly: false) + .Where(certificate => certificate.HasPrivateKey) + .MaxBy(certificate => certificate.NotAfter); + } + + public X509Certificate2 Save(TlsRole role, X509Certificate2 fresh) + { + // Exportable keeps the PEM mirror refreshable from the store alone. + var persisted = X509CertificateLoader.LoadPkcs12( + fresh.Export(X509ContentType.Pfx), null, + X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet + | X509KeyStorageFlags.Exportable); + persisted.FriendlyName = "ExecuteR self-signed (managed)"; + + using var store = new X509Store(StoreFor(role), StoreLocation.LocalMachine); + store.Open(OpenFlags.ReadWrite); + foreach (var existing in store.Certificates.Find( + X509FindType.FindBySubjectDistinguishedName, TlsSubjects.For(role), validOnly: false)) + { + store.Remove(existing); + } + + store.Add(persisted); + return persisted; + } + + public void Complete(X509Certificate2 root, X509Certificate2 intermediate, X509Certificate2 leaf) + { + // SChannel serves the chain from the stores; the PEM mirror exists + // for local proxies. Keys from a pre-Exportable install cannot be + // exported — certs still mirror so trust-by-import keeps working. + foreach (var (role, certificate) in new[] + { + (TlsRole.Root, root), (TlsRole.Intermediate, intermediate), (TlsRole.Leaf, leaf), + }) + { + try + { + mirror.WritePem(role, certificate); + } + catch (CryptographicException) + { + Directory.CreateDirectory(mirrorDirectory); + File.WriteAllText( + Path.Combine(mirrorDirectory, role switch + { + TlsRole.Root => "root.crt", + TlsRole.Intermediate => "intermediate.crt", + _ => "server.crt", + }), + certificate.ExportCertificatePem()); + } + } + + mirror.Complete(root, intermediate, leaf); + } +} diff --git a/src/Backend/Tls/TlsRenewalService.cs b/src/Backend/Tls/TlsRenewalService.cs new file mode 100644 index 0000000..8dfadb2 --- /dev/null +++ b/src/Backend/Tls/TlsRenewalService.cs @@ -0,0 +1,33 @@ +namespace Backend.Tls; + +/// +/// Background renewal for the managed self-signed chain: re-runs the +/// idempotent EnsureChain periodically so the leaf (and eventually the CAs) +/// are re-issued well before expiry and hot-swapped without a restart. +/// +public sealed class TlsRenewalService(SelfSignedTlsManager manager, ILogger logger) + : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromHours(6)); + try + { + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + try + { + manager.EnsureChain(logger); + } + catch (Exception ex) + { + logger.LogError(ex, "Self-signed TLS renewal check failed; will retry"); + } + } + } + catch (OperationCanceledException) + { + // Shutdown. + } + } +} diff --git a/src/Backend/Tls/TlsSettings.cs b/src/Backend/Tls/TlsSettings.cs new file mode 100644 index 0000000..19034c1 --- /dev/null +++ b/src/Backend/Tls/TlsSettings.cs @@ -0,0 +1,115 @@ +using System.Net; + +namespace Backend.Tls; + +/// +/// Built-in encryption, ON by default (opt out with TLS_SELF_SIGNED=0): the +/// listener serves HTTPS with a locally managed self-signed chain (root > +/// intermediate > leaf, auto-renewed) so the hop between the reverse proxy +/// and the server cannot be sniffed. This is NOT public TLS termination — +/// that stays at the edge; proxies connect with verification off or import +/// the exported root+intermediate. +/// +public sealed class TlsSettings +{ + public bool Enabled { get; init; } + + /// PEM storage directory (file mode). Defaults to <data>/tls. + public required string CertificateDirectory { get; init; } + + /// + /// Persist the chain in the Windows machine certificate stores (root in + /// Trusted Roots, intermediate in Intermediate CAs, leaf in Personal) + /// instead of PEM files. Setting TLS_CERT_DIR forces file mode anywhere. + /// + public bool UseWindowsStore { get; init; } + + public IReadOnlyList DnsNames { get; init; } = []; + + public IReadOnlyList IpAddresses { get; init; } = []; + + /// + /// True when this request reached the self-signed listener directly — + /// HTTPS served here with no forwarded headers consumed (a proxied + /// request carries X-Original-* after UseForwardedHeaders). Generated + /// install commands then include TLS skip-verify so enrollment works + /// against the undistributed roots. + /// + public bool IsSelfSignedDirect(HttpContext context) + => Enabled + && context.Request.IsHttps + && !context.Request.Headers.ContainsKey("X-Original-Proto") + && !context.Request.Headers.ContainsKey("X-Original-For"); + + public static TlsSettings FromConfiguration(IConfiguration configuration) + { + var certDir = configuration["TLS_CERT_DIR"]; + var dataDir = Path.GetDirectoryName(Path.GetFullPath( + configuration["DATABASE_PATH"] is { Length: > 0 } db ? db : "data/app.db")) ?? "data"; + + var dnsNames = new List { "localhost" }; + var ipAddresses = new List { IPAddress.Loopback, IPAddress.IPv6Loopback }; + + // Verification is off at the proxy, so the SAN set only needs to be + // friendly for direct browsing: hostname, FQDN and the bind address. + try + { + var host = Dns.GetHostName(); + AddDns(dnsNames, host); + try + { + AddDns(dnsNames, Dns.GetHostEntry(host).HostName); + } + catch (Exception) + { + // No resolvable FQDN — hostname and localhost suffice. + } + } + catch (Exception) + { + // Hostname unavailable; localhost suffices. + } + + foreach (var url in (configuration["urls"] ?? string.Empty) + .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + // Kestrel wildcard hosts (*, +) are not valid URI hosts. + if (!Uri.TryCreate(url.Replace("//*", "//wildcard").Replace("//+", "//wildcard"), + UriKind.Absolute, out var uri)) + { + continue; + } + + if (IPAddress.TryParse(uri.Host, out var ip)) + { + if (!ip.Equals(IPAddress.Any) && !ip.Equals(IPAddress.IPv6Any) + && !ipAddresses.Contains(ip)) + { + ipAddresses.Add(ip); + } + } + else if (uri.Host != "wildcard") + { + AddDns(dnsNames, uri.Host); + } + } + + return new TlsSettings + { + Enabled = configuration["TLS_SELF_SIGNED"] != "0", + CertificateDirectory = certDir is { Length: > 0 } ? certDir : Path.Combine(dataDir, "tls"), + UseWindowsStore = OperatingSystem.IsWindows() && certDir is not { Length: > 0 }, + DnsNames = dnsNames, + IpAddresses = ipAddresses, + }; + } + + private static void AddDns(List names, string candidate) + { + if (!string.IsNullOrWhiteSpace(candidate) + && !names.Contains(candidate, StringComparer.OrdinalIgnoreCase)) + { + names.Add(candidate); + } + } +} diff --git a/src/Infra/caddy/Caddyfile b/src/Infra/caddy/Caddyfile new file mode 100644 index 0000000..478809b --- /dev/null +++ b/src/Infra/caddy/Caddyfile @@ -0,0 +1,91 @@ +#============================================================================= +# ExecuteR - Caddy site (single self-contained Caddyfile) +#============================================================================= +# +# Fronts the three stack services on one public TLS edge: +# / -> WebUI (host port 13080) +# /api/ -> Backend API (host port 19080) +# /messaging/agent -> NATS WebSocket (host port 19222) +# /messaging/browser -> NATS WebSocket (host port 19222) +# +# BEFORE USE, replace: +# control.example.com your public hostname +# 10.0.0.10 the Docker host running the ExecuteR stack +# +# Caddy terminates TLS itself: certificates are obtained and renewed +# automatically via ACME - no certificate paths to manage. The :80 listener +# (redirect + ACME challenge) is automatic as well. Runs on Windows and +# Linux alike: https://caddyserver.com/docs/install +# +# Standalone server instead of the compose stack? Point all three handles +# at the single binary (default https://10.0.0.10:9080 with the +# skip-verify transport shown at the bottom). +#============================================================================= + +control.example.com { + + # --- Forwarded headers --------------------------------------------------- + # Caddy sends X-Forwarded-For / -Proto / -Host on its own. The backend + # only honors them from trusted proxy addresses (private networks by + # default), so make sure THIS host is covered by TRUSTED_PROXIES / + # TRUSTED_NETWORKS. Change the prefix only when mounting under a + # sub-path instead of the site root. + request_header X-Forwarded-Prefix / + + # Security headers (the app is same-origin; adjust if you embed it). + header { + X-Content-Type-Options "nosniff" + X-Frame-Options "SAMEORIGIN" + Referrer-Policy "same-origin" + Strict-Transport-Security "max-age=31536000" + } + + # ---------------------------------------------------------------------- + # Optional: restrict the whole site to known networks. + # Uncomment and edit, then reload Caddy. + # ---------------------------------------------------------------------- + # @outside { + # not remote_ip 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 203.0.113.0/24 + # } + # respond @outside 403 + + # ── NATS WebSocket: agents and browsers ─────────────────────────────── + # WebSocket upgrades pass through reverse_proxy automatically and are + # not timed out mid-stream. + handle /messaging/* { + reverse_proxy 10.0.0.10:19222 + } + + # ── Backend API (enrollment, sign-in, OIDC callback included) ───────── + # Edge rate limiting needs the caddy-ratelimit plugin + # (github.com/mholt/caddy-ratelimit); the backend rate limits + # enrollment and sign-in itself, so the edge layer is optional here. + handle /api/* { + reverse_proxy 10.0.0.10:19080 + } + + # ── WebUI (everything else) ─────────────────────────────────────────── + handle { + reverse_proxy 10.0.0.10:13080 + } + + # ---------------------------------------------------------------------- + # Backend running with TLS_SELF_SIGNED=1? Proxy the API upstream over + # https instead - the hop stays encrypted; the self-signed roots simply + # are not distributed. Either skip verification: + # + # handle /api/* { + # reverse_proxy https://10.0.0.10:19080 { + # transport http { + # tls + # tls_insecure_skip_verify + # } + # } + # } + # + # ...or import root.crt + intermediate.crt from /tls and pin them + # (transport http > tls_trust_pool file ...), re-importing when the + # chain rotates at expiry. Follow your organization's security + # standards. + # ---------------------------------------------------------------------- +} diff --git a/src/Infra/haproxy/haproxy.cfg b/src/Infra/haproxy/haproxy.cfg new file mode 100644 index 0000000..1ee756d --- /dev/null +++ b/src/Infra/haproxy/haproxy.cfg @@ -0,0 +1,111 @@ +#============================================================================= +# ExecuteR - HAProxy edge (single self-contained file) +#============================================================================= +# +# Fronts the three stack services on one public TLS edge: +# / -> WebUI (host port 13080) +# /api/ -> Backend API (host port 19080) +# /messaging/agent -> NATS WebSocket (host port 19222) +# /messaging/browser -> NATS WebSocket (host port 19222) +# +# BEFORE USE, replace: +# control.example.com your public hostname +# 10.0.0.10 the Docker host running the stack +# /etc/haproxy/certs/control.example.com.pem full chain + key in ONE pem +# +# HAProxy does not obtain certificates itself - renew with your ACME tooling +# (acme.sh, certbot) and reload. The :80 frontend passes HTTP-01 challenges +# through un-redirected for that. +#============================================================================= + +global + log stdout format raw local0 + maxconn 4096 + +defaults + mode http + log global + option httplog + option forwardfor + timeout connect 5s + timeout client 60s + timeout server 120s + # WebSockets are long-lived; after the upgrade the tunnel timeout + # governs them - do not let the edge cut agent sessions. + timeout tunnel 1h + +# --- HTTP: ACME passthrough + redirect to HTTPS ------------------------------ +frontend http_in + bind :80 + acl acme path_beg /.well-known/acme-challenge/ + use_backend acme_challenge if acme + http-request redirect scheme https code 301 unless acme + +backend acme_challenge + # Point at wherever your ACME client serves webroot challenges. + server acme 127.0.0.1:8402 + +# --- HTTPS ------------------------------------------------------------------- +frontend https_in + bind :443 ssl crt /etc/haproxy/certs/control.example.com.pem alpn h2,http/1.1 + + # --- Forwarded headers --------------------------------------------------- + # option forwardfor (defaults) adds X-Forwarded-For. The backend only + # honors forwarded headers from trusted proxy addresses (private + # networks by default), so make sure THIS host is covered by + # TRUSTED_PROXIES / TRUSTED_NETWORKS. + http-request set-header X-Forwarded-Proto https + http-request set-header X-Forwarded-Host %[req.hdr(host)] + http-request set-header X-Forwarded-Port 443 + # Change only when mounting under a sub-path instead of the site root. + http-request set-header X-Forwarded-Prefix / + + # Security headers (the app is same-origin; adjust if you embed it). + http-response set-header X-Content-Type-Options "nosniff" + http-response set-header X-Frame-Options "SAMEORIGIN" + http-response set-header Referrer-Policy "same-origin" + http-response set-header Strict-Transport-Security "max-age=31536000" + + # ---------------------------------------------------------------------- + # Optional: restrict the whole site to known networks. + # Uncomment and edit, then reload HAProxy. + # ---------------------------------------------------------------------- + # acl internal src 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 203.0.113.0/24 + # http-request deny unless internal + + # --- Edge rate limits: enrollment and sign-in ------------------------ + stick-table type ip size 100k expire 10m store http_req_rate(1m) + acl enroll_path path_beg /api/enrollment/ + acl auth_path path_beg /api/auth/ + http-request track-sc0 src if enroll_path or auth_path + http-request deny deny_status 429 if enroll_path { sc_http_req_rate(0) gt 10 } + http-request deny deny_status 429 if auth_path { sc_http_req_rate(0) gt 20 } + + # --- Routing ---------------------------------------------------------- + acl messaging path /messaging/agent /messaging/browser + acl api path_beg /api/ + + use_backend executer_nats if messaging + use_backend executer_api if api + default_backend executer_webui + +# --- Upstreams ---------------------------------------------------------------- +# Backend running with TLS_SELF_SIGNED=1? Switch the executer_api server +# line to ssl - the hop stays encrypted; the self-signed roots simply are +# not distributed. Either skip verification: +# server api 10.0.0.10:19080 ssl verify none +# ...or import root.crt + intermediate.crt from /tls and pin them: +# server api 10.0.0.10:19080 ssl verify required ca-file /etc/haproxy/executer-roots.pem +# re-importing when the chain rotates at expiry. Follow your organization's +# security standards. + +backend executer_webui + server webui 10.0.0.10:13080 check + +backend executer_api + # Agent packages can be tens of MB; give downloads room. + timeout server 300s + server api 10.0.0.10:19080 check + +backend executer_nats + server nats 10.0.0.10:19222 check diff --git a/src/Infra/nginx/executer-http.conf b/src/Infra/nginx/executer-http.conf new file mode 100644 index 0000000..15b0e1c --- /dev/null +++ b/src/Infra/nginx/executer-http.conf @@ -0,0 +1,23 @@ +#============================================================================= +# ExecuteR - http{}-level companion to executer.conf +#============================================================================= +# +# The WebSocket upgrade map MUST be included at http{} level, NOT inside a +# site: +# +# plain nginx: drop this file in /etc/nginx/conf.d/ (the stock nginx.conf +# includes conf.d/*.conf at http level) +# Nginx UI: Manage Configs -> create conf.d/executer-http.conf with +# this content. Do NOT paste it into the site under Manage +# Sites. +# +# The rate-limit zones live in executer.conf itself - they are fine in a +# site file. If your nginx.conf already defines this map, delete the +# duplicate here or nginx will refuse to start. +#============================================================================= + +# "upgrade" for WebSocket requests, "close" otherwise. +map $http_upgrade $connection_upgrade { + default upgrade; + '' close; +} diff --git a/src/Infra/nginx/executer.conf b/src/Infra/nginx/executer.conf index ee0d6e5..b7df832 100644 --- a/src/Infra/nginx/executer.conf +++ b/src/Infra/nginx/executer.conf @@ -1,5 +1,5 @@ #============================================================================= -# ExecuteR - nginx site (single self-contained file, nginx-ui friendly) +# ExecuteR - nginx site (nginx-ui friendly) #============================================================================= # # Fronts the three stack services on one public TLS edge: @@ -13,23 +13,23 @@ # 10.0.0.10 the Docker host running the ExecuteR stack # /etc/nginx/ssl/... your certificate paths # -# Self-contained: no include/snippet files required. +# COMPANION FILE: executer-http.conf carries the WebSocket upgrade map, +# which must be included at http{} level - conf.d/ on plain nginx, Manage +# Configs in Nginx UI. Everything else, including the rate-limit zones +# below, lives right here in the site. #============================================================================= -# --- http{} level directives ------------------------------------------------ -# These three must live at http{} level. If your nginx.conf already defines -# any of them, delete the duplicate here or nginx will refuse to start. - +# --- Rate-limit zones ------------------------------------------------------- limit_req_zone $binary_remote_addr zone=executer_enroll:10m rate=10r/m; limit_req_zone $binary_remote_addr zone=executer_auth:10m rate=20r/m; -# "upgrade" for WebSocket requests, "close" otherwise. -map $http_upgrade $connection_upgrade { - default upgrade; - '' close; -} - # --- Upstreams -------------------------------------------------------------- +# If the backend runs with TLS_SELF_SIGNED=1, switch its proxy_pass to +# https:// and add `proxy_ssl_verify off;` (the hop stays encrypted; the +# self-signed roots simply are not distributed) — or import the exported +# root+intermediate and use proxy_ssl_trusted_certificate + proxy_ssl_verify +# on, re-importing when the chain rotates at expiry. Follow your +# organization's security standards. upstream executer_webui { server 10.0.0.10:13080; keepalive 16; @@ -112,6 +112,7 @@ server { # allow 10.0.0.0/8; # RFC1918 - internal # allow 172.16.0.0/12; # RFC1918 - internal # allow 192.168.0.0/16; # RFC1918 - internal + # allow 100.64.0.0/10; # CGNAT - carrier / overlay networks # allow 203.0.113.0/24; # office egress # allow 2001:db8::/32; # office egress (IPv6) # deny all; @@ -128,6 +129,7 @@ server { # Optional: agents only from trusted networks. # allow 10.0.0.0/8; + # allow 100.64.0.0/10; # CGNAT # deny all; } @@ -153,6 +155,7 @@ server { # Optional: only let known networks enroll. # allow 10.0.0.0/8; + # allow 100.64.0.0/10; # CGNAT # deny all; } diff --git a/src/Installer.Server/Product.wxs b/src/Installer.Server/Product.wxs index 39e13e9..fe2e116 100644 --- a/src/Installer.Server/Product.wxs +++ b/src/Installer.Server/Product.wxs @@ -6,10 +6,14 @@ ExecuteR Server MSI: the standalone combined server (UI + API + messaging relay + NATS sidecar) as a Windows service. - Public properties (uppercase): ADMINUSERNAME ADMINPASSWORD — the initial - admin created on first start (defaults Admin/Admin; interactive installs - edit them on the account page). After the files land, the installer runs - the binary's own cross-platform init: + Public properties (uppercase): ADMINUSERNAME ADMINPASSWORD BINDADDRESS + HTTPPORT NATSPORT NATSWSPORT NATSMONITORPORT ENABLETLS — the initial + admin account plus the listen configuration, all defaulted so a + next-next-next install works. ENABLETLS defaults to 1 (Self-Signed TLS + on; the Network page checkbox) — silent opt-out passes ENABLETLS="". + Interactive installs edit them on the Account and Network pages; silent + installs pass them as properties. After the files land, the installer + runs the binary's own cross-platform init: ExecuteR-Server.exe setup (with the admin user/password flags) ExecuteR-Server.exe service install @@ -43,6 +47,31 @@ + + Skip TLS certificate verification (self-signed servers) + Accepts the ExecuteR server's certificate without validation. Intended for servers running the built-in managed self-signed chain without a reverse proxy in front: the connection is still fully TLS-encrypted — the self-signed roots simply are not distributed to the devices, so there is nothing to validate against. + +If you enable this policy, the agent connects to HTTPS servers without validating the certificate chain (enrollment and the persistent messaging connection alike). + +If you disable or do not configure this policy, the agent uses the locally configured value, or full certificate validation by default. + +Do not enable this for servers reached through a proxy with a publicly trusted certificate — leave validation on there. Always follow your organization's security standards. + The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. diff --git a/src/Installer/Product.wxs b/src/Installer/Product.wxs index 7d6de53..417f6e0 100644 --- a/src/Installer/Product.wxs +++ b/src/Installer/Product.wxs @@ -5,7 +5,7 @@ + + + @@ -127,6 +133,10 @@ + + + @@ -199,6 +209,11 @@ + + + diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 99ae51d..53cb41f 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -324,6 +324,7 @@ public sealed record AgentPackageStatusDto( /// POST /api/admin/bootstrap-tokens request body. public sealed record CreateBootstrapTokenRequest( int? ValidMinutes, + // 1-9999, or 0 for unlimited uses (expiry and revocation still apply). int? MaxUses, string? Note); diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts index 9803700..b9b38d6 100644 --- a/src/WebUI/src/lib/api/types.ts +++ b/src/WebUI/src/lib/api/types.ts @@ -362,6 +362,12 @@ export interface SchedulePreviewDto { export interface ServerInfoDto { baseUrl: string; fromEnvironment: boolean; + /** + * The server is serving its managed self-signed chain directly (no proxy + * in between), so generated commands must skip TLS verification — the + * traffic is still encrypted; the roots just aren't distributed. + */ + selfSignedDirect: boolean; } /** diff --git a/src/WebUI/src/lib/components/AddDeviceModal.svelte b/src/WebUI/src/lib/components/AddDeviceModal.svelte new file mode 100644 index 0000000..c16dc22 --- /dev/null +++ b/src/WebUI/src/lib/components/AddDeviceModal.svelte @@ -0,0 +1,334 @@ + + + { + if (e.key === 'Escape') close(); + }} +/> + + + + diff --git a/src/WebUI/src/routes/devices/+page.svelte b/src/WebUI/src/routes/devices/+page.svelte index 0e52e3f..87d3f53 100644 --- a/src/WebUI/src/routes/devices/+page.svelte +++ b/src/WebUI/src/routes/devices/+page.svelte @@ -4,11 +4,16 @@ import { api } from '$lib/api/client'; import type { DeviceDto } from '$lib/api/types'; import { nats } from '$lib/messaging/nats'; + import { session, hasPermission } from '$lib/auth/session'; import StatusBadge from '$lib/components/StatusBadge.svelte'; import RelativeTime from '$lib/components/RelativeTime.svelte'; import EmptyState from '$lib/components/EmptyState.svelte'; + import AddDeviceModal from '$lib/components/AddDeviceModal.svelte'; let devices = $state(null); + let showAddDevice = $state(false); + // Token creation sits behind settings.manage. + const canAddDevice = $derived(hasPermission($session, 'settings.manage')); let search = $state(''); let statusFilter = $state<'all' | 'online' | 'offline'>('all'); let sortKey = $state<'hostname' | 'lastSeenUtc' | 'osCaption'>('hostname'); @@ -75,9 +80,16 @@ + {#if canAddDevice} + + {/if} +{#if showAddDevice} + (showAddDevice = false)} /> +{/if} +
{#if devices === null}
diff --git a/src/WebUI/src/routes/settings/+page.svelte b/src/WebUI/src/routes/settings/+page.svelte index 4ad56dd..a24e5f3 100644 --- a/src/WebUI/src/routes/settings/+page.svelte +++ b/src/WebUI/src/routes/settings/+page.svelte @@ -20,10 +20,11 @@ // PUBLIC_SERVER_URL (or trusted forwarded headers) beats the browser's own // origin, so the command works even when the admin browses via an internal - // hostname the target devices cannot reach. + // hostname the target devices cannot reach. Direct self-signed serving + // prefixes a PS5-safe skip-verify (the hop is still encrypted). const installCommand = $derived( newToken?.token - ? `iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex` + ? `${serverInfo?.selfSignedDirect ? '[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }; ' : ''}iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex` : '' ); @@ -109,8 +110,8 @@