diff --git a/.env.example b/.env.example index fb79a43..7ed4c0a 100644 --- a/.env.example +++ b/.env.example @@ -52,7 +52,13 @@ PROXY_HTTPS_PORT=18443 PROXY_PUBLIC_HOSTNAME=control.example.com # ── Host-published ports (uncommon range; front with the edge proxy) ─────── -BIND_EXTERNAL_ADDRESS=0.0.0.0 +# App services (backend, webui, NATS WebSocket) publish on loopback by +# default — safe, and enough when the edge proxy runs on this same host +# (it reaches them over the compose network). Set this to 0.0.0.0 or a +# specific host IP when the edge proxy runs on ANOTHER host and must reach +# them directly. The bundled proxy binds publicly via PROXY_BIND_ADDRESS. +BIND_EXTERNAL_ADDRESS=127.0.0.1 +PROXY_BIND_ADDRESS=0.0.0.0 WEBUI_PORT=13080 BACKEND_PORT=19080 NATS_WS_PORT=19222 diff --git a/IaC/compose/docker-compose.proxy.yml b/IaC/compose/docker-compose.proxy.yml index 6b8ea8a..5582d96 100644 --- a/IaC/compose/docker-compose.proxy.yml +++ b/IaC/compose/docker-compose.proxy.yml @@ -32,8 +32,8 @@ services: EXTERNAL: INTERNAL: ports: - - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${PROXY_HTTP_PORT:-18080}:80' - - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${PROXY_HTTPS_PORT:-18443}:443' + - '${PROXY_BIND_ADDRESS:-0.0.0.0}:${PROXY_HTTP_PORT:-18080}:80' + - '${PROXY_BIND_ADDRESS:-0.0.0.0}:${PROXY_HTTPS_PORT:-18443}:443' volumes: - /etc/timezone:/etc/timezone:ro - /etc/localtime:/etc/localtime:ro diff --git a/IaC/compose/docker-compose.yml b/IaC/compose/docker-compose.yml index 08f2a3e..04c72dc 100644 --- a/IaC/compose/docker-compose.yml +++ b/IaC/compose/docker-compose.yml @@ -51,7 +51,7 @@ services: - '4222' ports: # WebSocket listener — the external reverse proxy maps /messaging/* here. - - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${NATS_WS_PORT:-19222}:9222' + - '${BIND_EXTERNAL_ADDRESS:-127.0.0.1}:${NATS_WS_PORT:-19222}:9222' volumes: - /etc/timezone:/etc/timezone:ro - /etc/localtime:/etc/localtime:ro @@ -94,7 +94,7 @@ services: expose: - '8080' ports: - - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${BACKEND_PORT:-19080}:8080' + - '${BIND_EXTERNAL_ADDRESS:-127.0.0.1}:${BACKEND_PORT:-19080}:8080' # Operators remap with PUID/PGID when volume ownership requires it. user: "${PUID:-1000}:${PGID:-1000}" environment: @@ -183,7 +183,7 @@ services: expose: - '3000' ports: - - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${WEBUI_PORT:-13080}:3000' + - '${BIND_EXTERNAL_ADDRESS:-127.0.0.1}:${WEBUI_PORT:-13080}:3000' # Operators remap with PUID/PGID when volume ownership requires it. user: "${PUID:-1000}:${PGID:-1000}" environment: diff --git a/docs/screenshots/add-device.png b/docs/screenshots/add-device.png index 69d2211..6c1e8ca 100644 Binary files a/docs/screenshots/add-device.png and b/docs/screenshots/add-device.png differ diff --git a/src/Agent/Commands/AgentCli.cs b/src/Agent/Commands/AgentCli.cs index 1fa8cb0..2bbedc8 100644 --- a/src/Agent/Commands/AgentCli.cs +++ b/src/Agent/Commands/AgentCli.cs @@ -134,11 +134,10 @@ public static class AgentCli } } - var installServerCa = args.Contains("--install-server-ca"); var skipTlsVerify = args.Contains("--skip-tls-verify"); - if (url is null && token is null && proxy is null && !installServerCa && !skipTlsVerify) + if (url is null && token is null && proxy is null && !skipTlsVerify) { - Console.Error.WriteLine("Usage: configure --url [--token ] [--proxy ] [--install-server-ca] [--skip-tls-verify]"); + Console.Error.WriteLine("Usage: configure --url [--token ] [--proxy ] [--skip-tls-verify]"); return 1; } @@ -160,18 +159,12 @@ public static class AgentCli registry.WriteString(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.ProxyUrl, proxy); } - if (installServerCa) - { - // Install the server's self-signed CA into the OS trust store (and - // keep it current) so system validation trusts a direct/local - // connection. Not pinning — a real cert behind a proxy still works. - registry.WriteDword(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.ServerCaAutoInstall, 1); - } - if (skipTlsVerify) { - // Escape hatch: accept any certificate (still encrypted). Prefer - // --install-server-ca for self-signed servers. + // Escape hatch: accept any certificate (still encrypted). Not + // usually needed — a self-signed server's CA is fetched and trusted + // automatically; reach for this only for a private/edge cert the + // agent cannot otherwise validate. registry.WriteDword(Branding.AgentRegistryKey, Agent.Configuration.AgentConfigurationKeys.TlsSkipVerify, 1); } diff --git a/src/Agent/Configuration/AgentConfiguration.cs b/src/Agent/Configuration/AgentConfiguration.cs index 2eb0cc8..8e3e824 100644 --- a/src/Agent/Configuration/AgentConfiguration.cs +++ b/src/Agent/Configuration/AgentConfiguration.cs @@ -21,14 +21,6 @@ public sealed class AgentConfiguration public required ConfigurationValue TlsSkipVerify { get; init; } public required ConfigurationValue ProxyUrl { get; init; } - /// - /// Install the server's managed self-signed CA into the OS trust store so - /// ordinary system validation succeeds on a direct/local connection. Not - /// pinning and not forced — a later reverse proxy with a real certificate - /// still validates normally and the self-signed CA just goes unused. - /// - public ConfigurationValue ServerCaAutoInstall { get; init; } = new(false, ConfigurationSource.Default); - /// Parsed ServerURL; null when unset or invalid. public ServerUrl? ServerUrl => Shared.Infrastructure.Routing.ServerUrl.TryParse(ServerUrlText.Value, out var parsed, out _) ? parsed : null; @@ -58,7 +50,6 @@ public sealed class AgentConfigurationLoader(IRegistryStore registry, bool allow AllowScriptExecution = ResolveBool(AgentConfigurationKeys.AllowScriptExecution, defaultValue: true), TlsSkipVerify = ResolveBool(AgentConfigurationKeys.TlsSkipVerify, defaultValue: false), ProxyUrl = ResolveString(AgentConfigurationKeys.ProxyUrl, AgentConfigurationKeys.EnvironmentNames.ProxyUrl, null), - ServerCaAutoInstall = ResolveBool(AgentConfigurationKeys.ServerCaAutoInstall, defaultValue: false), }; } diff --git a/src/Agent/Configuration/AgentConfigurationKeys.cs b/src/Agent/Configuration/AgentConfigurationKeys.cs index 36f7568..819389a 100644 --- a/src/Agent/Configuration/AgentConfigurationKeys.cs +++ b/src/Agent/Configuration/AgentConfigurationKeys.cs @@ -20,14 +20,6 @@ public static class AgentConfigurationKeys /// public const string TlsSkipVerify = "TlsSkipVerify"; - /// - /// DWORD 1: fetch the server's managed self-signed CA and install it into - /// the OS trust store (and keep it current across renewals) so system - /// validation trusts a direct/local self-signed server. Not pinning — - /// a proxy with a real certificate added later still validates normally. - /// - public const string ServerCaAutoInstall = "ServerCaAutoInstall"; - /// /// Explicit outbound proxy URL (http://proxy:8080). Unset, the agent /// honors the system/environment proxy; either way it authenticates to diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs index 7697b54..79ea6e7 100644 --- a/src/Agent/Enrollment/EnrollmentService.cs +++ b/src/Agent/Enrollment/EnrollmentService.cs @@ -80,13 +80,13 @@ public sealed class EnrollmentService( AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly), Device: ReadDeviceInfo()); - // Self-signed servers: make the CA available to the OS trust store - // first so ordinary system validation succeeds here — not pinned, so - // a proxy with a real certificate added later still validates. - if (configuration.ServerCaAutoInstall.Value) - { - await ServerTrust.FetchAndInstallCaAsync(serverUrl, HttpClient.DefaultProxy, logger, cancellationToken); - } + // Always probe for a self-signed CA first (the probe accepts any + // certificate — it only asks whether the server is self-signed and + // fetches public CA certs). A self-signed server's chain lands in the + // OS trust store so ordinary system validation succeeds below; a real + // certificate returns 404 and this is a no-op. Not pinned — a proxy + // with a real certificate added later still validates. + await ServerTrust.FetchAndInstallCaAsync(serverUrl, HttpClient.DefaultProxy, logger, cancellationToken); // TlsSkipVerify is the accept-any escape hatch; otherwise validate // against the OS trust store (which now contains the CA above). diff --git a/src/Agent/Messaging/AgentNatsOptionsFactory.cs b/src/Agent/Messaging/AgentNatsOptionsFactory.cs index 4e5f7e6..e47d387 100644 --- a/src/Agent/Messaging/AgentNatsOptionsFactory.cs +++ b/src/Agent/Messaging/AgentNatsOptionsFactory.cs @@ -38,8 +38,8 @@ public static class AgentNatsOptionsFactory }; // TlsSkipVerify accepts any cert (still encrypted); otherwise the OS - // trust store validates the wss server cert — which contains the - // self-signed CA when ServerCaAutoInstall installed it. + // trust store validates the wss server cert — which trusts the + // self-signed CA the agent auto-installs at enrollment. var skipVerify = configuration.TlsSkipVerify.Value; if (skipVerify) { diff --git a/src/Agent/Service/AgentHost.cs b/src/Agent/Service/AgentHost.cs index 53a6863..973950a 100644 --- a/src/Agent/Service/AgentHost.cs +++ b/src/Agent/Service/AgentHost.cs @@ -69,7 +69,8 @@ public static class AgentHost builder.Services.AddSingleton(new AgentConfigurationLoader(registry, allowEnvironment: !runAsService)); builder.Services.AddHostedService(); - // Keeps the pinned server CA current across renewals (pinned mode only). + // Keeps a self-signed server's CA current in the OS trust store across + // renewals (no-op for a real/edge certificate). builder.Services.AddHostedService(); return builder.Build(); diff --git a/src/Agent/Service/CaRefreshService.cs b/src/Agent/Service/CaRefreshService.cs index 3053bb8..412fd4b 100644 --- a/src/Agent/Service/CaRefreshService.cs +++ b/src/Agent/Service/CaRefreshService.cs @@ -6,30 +6,26 @@ using Microsoft.Extensions.Logging; namespace Agent.Service; /// -/// Keeps the server's self-signed CA present in the OS trust store when -/// ServerCaAutoInstall is set: installs it on start and re-installs every few -/// hours, so a server-side chain rotation stays trusted without operator -/// action. It never forces validation against the CA — a proxy with a real -/// certificate added later is unaffected. Idle otherwise. +/// Keeps the server's self-signed CA present in the OS trust store: probes +/// GET /api/enrollment/ca on start and every few hours, installing the chain +/// when the server is self-signed so a server-side rotation stays trusted +/// without operator action. The probe accepts any certificate (it is only +/// asking whether the server is self-signed and fetching public CA certs); a +/// 404 means the server is not self-signed, so it is a harmless no-op. It never +/// forces validation against the CA — a proxy with a real certificate is +/// unaffected. /// public sealed class CaRefreshService( AgentConfigurationLoader loader, ILogger logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - if (!loader.Load().ServerCaAutoInstall.Value) - { - logger.LogDebug("Server CA auto-install idle (not enabled)"); - return; - } - using var timer = new PeriodicTimer(TimeSpan.FromHours(6)); try { do { - var configuration = loader.Load(); - if (configuration.ServerCaAutoInstall.Value && configuration.ServerUrl is { } serverUrl) + if (loader.Load().ServerUrl is { } serverUrl) { await ServerTrust.FetchAndInstallCaAsync( serverUrl, System.Net.Http.HttpClient.DefaultProxy, logger, stoppingToken); diff --git a/src/Backend/Enrollment/InstallEndpoints.cs b/src/Backend/Enrollment/InstallEndpoints.cs index d1a54e3..006d211 100644 --- a/src/Backend/Enrollment/InstallEndpoints.cs +++ b/src/Backend/Enrollment/InstallEndpoints.cs @@ -32,9 +32,11 @@ public static class InstallEndpoints /// /// Serves the managed self-signed CA chain (root + intermediate, public - /// certs only) so agents can pin it and keep validating the server across - /// renewals. 404 when the server is not running self-signed TLS — nothing - /// to distribute, agents validate against the real edge certificate. + /// certs only) so agents can trust the server across renewals. This is the + /// self-signed signal too: a 200 (a chain) means the server runs self-signed + /// TLS and agents should auto-trust it; a 404 means it is not self-signed + /// (a real edge certificate validates on its own — nothing to distribute). + /// The chain is not pinned; it is installed into the OS trust store. /// private static IResult GetCaChain(HttpContext context) { @@ -46,7 +48,7 @@ public static class InstallEndpoints } private static IResult GetInstallScript( - HttpContext context, IConfiguration configuration, string? token, string? type, string? skipVerify) + HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, string? token, string? type) { if (string.IsNullOrWhiteSpace(token)) { @@ -55,21 +57,25 @@ public static class InstallEndpoints var baseUrl = ResolveBaseUrl(context, configuration); - // Skip-verify is an OPERATOR CHOICE (&skipVerify=1), never inferred: - // a self-signed server that later gains a proxy with a real - // certificate must not leave agents skipping validation needlessly. - // The Add Device modal pre-selects it only while serving the - // self-signed chain directly. - var skipTlsVerify = skipVerify is "1" or "true"; + // The only thing the script needs from the server is whether its own + // download must skip verification: true when this request arrived over + // the self-signed listener directly (no proxy in front), so the agent's + // download from the same URL succeeds. A proxied request (real cert) + // needs no skip. Trust itself is handled by the agent at enrollment: it + // always probes GET /api/enrollment/ca (accept-any) and installs the CA + // when self-signed (404 = not self-signed = nothing to do). Where TLS + // terminates follows the URL, which keeps this flexible. + var skipDownloadVerify = tls.IsSelfSignedDirect(context); // Token is embedded so the operator can paste one command; knowledge of a - // valid token is itself the enrollment gate. + // valid token is itself the enrollment gate. The Windows scripts + // self-elevate (see PsElevateOrRun) without re-fetching anything. var script = type?.ToLowerInvariant() switch { - "linux" => BuildUnixScript(baseUrl, token!, "linux", skipTlsVerify), - "osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipTlsVerify), - "zip" => BuildZipScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip", skipTlsVerify), - _ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", skipTlsVerify), + "linux" => BuildUnixScript(baseUrl, token!, "linux", skipDownloadVerify), + "osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipDownloadVerify), + "zip" => BuildZipScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip", skipDownloadVerify), + _ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", skipDownloadVerify), }; return Results.Text(script, "text/plain; charset=utf-8"); @@ -123,17 +129,39 @@ public static class InstallEndpoints // the agent is told to install the server CA into the OS trust store (and // keep it current) — system validation then trusts the server, without // pinning, so a proxy with a real cert added later still works. - private static string BuildMsiScript(string baseUrl, string token, string packageUrl, bool selfSigned) => $$""" - #Requires -RunAsAdministrator + // Auto-elevation trailer: the install work sits in an $install scriptblock + // above this. If already admin (a build pipeline), run it in place. If not, + // write that same scriptblock to a temp .ps1 and re-launch it elevated + // (UAC) with -NoExit so the result stays visible. No re-fetch, no + // -EncodedCommand (which trips AV/EDR heuristics). The elevated copy + // deletes itself via $PSCommandPath. + private const string PsElevateOrRun = """ + if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + & $install + } else { + Write-Host 'ExecuteR Agent install needs administrator rights - requesting elevation...' + $self = Join-Path $env:TEMP ('ExecuteRInstall-' + [guid]::NewGuid().ToString('N') + '.ps1') + Set-Content -LiteralPath $self -Value $install.ToString() -Encoding UTF8 + try { + Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-NoExit','-File',$self) + } catch { + Remove-Item -LiteralPath $self -Force -ErrorAction SilentlyContinue + Write-Warning 'Elevation was cancelled; the agent was not installed.' + } + } + """; + + private static string BuildMsiScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify) => $$""" $ErrorActionPreference = 'Stop' + $install = { Write-Host 'Installing ExecuteR Agent...' - {{(selfSigned ? PsSkipVerify : "")}} + {{(skipDownloadVerify ? 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"{{(selfSigned ? ", 'CAINSTALL=1'" : "")}}) + $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token") $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.' @@ -141,6 +169,9 @@ public static class InstallEndpoints finally { Remove-Item $msi -ErrorAction SilentlyContinue } + if ($PSCommandPath) { Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue } + } + {{PsElevateOrRun}} """; /// @@ -148,7 +179,7 @@ public static class InstallEndpoints /// 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 selfSigned) => $$""" + private static string BuildUnixScript(string baseUrl, string token, string os, bool skipDownloadVerify) => $$""" #!/usr/bin/env bash set -euo pipefail if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi @@ -164,7 +195,7 @@ public static class InstallEndpoints tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT echo "Installing ExecuteR Agent ({{os}}-${arch})..." - curl -fsSL{{(selfSigned ? "k" : "")}} "$pkg" -o "$tmp/agent.zip" + curl -fsSL{{(skipDownloadVerify ? "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" @@ -172,17 +203,16 @@ public static class InstallEndpoints python3 -m zipfile -e "$tmp/agent.zip" "$dest" fi chmod +x "$dest/executer-agent" - {{(selfSigned ? "# Trust the server's managed self-signed CA for host tooling too.\n curl -fsSLk \"" + baseUrl + ApiRoutes.EnrollmentCaChain + "\" -o /tmp/executer-ca.pem 2>/dev/null && {\n if [ -d /usr/local/share/ca-certificates ]; then cp /tmp/executer-ca.pem /usr/local/share/ca-certificates/executer-ca.crt && update-ca-certificates >/dev/null 2>&1 || true;\n elif [ -d /etc/pki/ca-trust/source/anchors ]; then cp /tmp/executer-ca.pem /etc/pki/ca-trust/source/anchors/executer-ca.crt && update-ca-trust >/dev/null 2>&1 || true; fi; rm -f /tmp/executer-ca.pem; }" : "")}} - "$dest/executer-agent" configure --url "$server" --token "$token"{{(selfSigned ? " --install-server-ca" : "")}} + "$dest/executer-agent" configure --url "$server" --token "$token" "$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 selfSigned) => $$""" - #Requires -RunAsAdministrator + private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify) => $$""" $ErrorActionPreference = 'Stop' + $install = { Write-Host 'Installing ExecuteR Agent (portable)...' - {{(selfSigned ? PsSkipVerify : "")}} + {{(skipDownloadVerify ? PsSkipVerify : "")}} $server = '{{baseUrl}}' $token = '{{token}}' $dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent' @@ -196,12 +226,14 @@ 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 - {{(selfSigned ? "Set-ItemProperty -Path 'HKLM:\\SOFTWARE\\ExecuteR' -Name 'ServerCaAutoInstall' -Value 1 -Type DWord" : "")}} & $exe initialize Write-Host 'ExecuteR Agent installed and starting.' } finally { Remove-Item $zip -ErrorAction SilentlyContinue } + if ($PSCommandPath) { Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue } + } + {{PsElevateOrRun}} """; } diff --git a/src/Backend/Nats/NatsAuthCli.cs b/src/Backend/Nats/NatsAuthCli.cs index e4fee57..d91743e 100644 --- a/src/Backend/Nats/NatsAuthCli.cs +++ b/src/Backend/Nats/NatsAuthCli.cs @@ -27,6 +27,15 @@ public static class NatsAuthCli ? args[outputIndex + 1] : Path.Combine("secrets", "nats"); + // Where the file resolver keeps account JWTs. Absolute '/data/resolver' + // suits containers (a bind-mounted volume); the standalone server + // passes a path relative to the sidecar's working dir so it lands under + // its own data directory, not the filesystem root (e.g. C:\data). + var resolverIndex = Array.IndexOf(args, "--resolver-dir"); + var resolverDir = resolverIndex >= 0 && resolverIndex + 1 < args.Length + ? args[resolverIndex + 1] + : "/data/resolver"; + Directory.CreateDirectory(outputDir); var now = DateTimeOffset.UtcNow; @@ -89,7 +98,7 @@ public static class NatsAuthCli resolver { type: full - dir: '/data/resolver' + dir: '{{resolverDir}}' allow_delete: true interval: "2m" } diff --git a/src/Backend/Standalone/ServerCli.cs b/src/Backend/Standalone/ServerCli.cs index dd42e0b..81c26af 100644 --- a/src/Backend/Standalone/ServerCli.cs +++ b/src/Backend/Standalone/ServerCli.cs @@ -40,6 +40,11 @@ public static class ServerCli var natsPort = 4222; var natsWsPort = 9222; var natsMonitorPort = 8222; + // The sidecar listens on loopback by default (the backend proxies its + // WebSocket, so nothing NATS exposes is public). Adaptable via + // --nats-bind: set 0.0.0.0 when an edge proxy on ANOTHER host must + // reach the NATS listeners directly. Auth is JWT either way. + var natsBind = "127.0.0.1"; // Self-signed TLS is on by default; --tls 0 (or an unchecked MSI // checkbox, which passes an empty value) opts out. var selfSignedTls = true; @@ -74,6 +79,15 @@ public static class ServerCli ? $"[{parsed}]" : parsed.ToString(); break; + case "--nats-bind": + var natsCandidate = args[++i]; + if (!System.Net.IPAddress.TryParse(natsCandidate, out _)) + { + throw new ArgumentException($"--nats-bind must be an IP address (got '{natsCandidate}')."); + } + + natsBind = natsCandidate; + break; case "--admin-user": adminUser = args[++i]; break; @@ -111,8 +125,10 @@ public static class ServerCli var baseDir = AppContext.BaseDirectory; var natsDir = Path.Combine(baseDir, "nats"); - var secretsDir = Path.Combine(baseDir, "secrets", "nats"); var dataDir = Path.Combine(baseDir, "data"); + // Everything stateful lives under data/ as siblings: db, keys, + // jetstream, resolver, tls and the NATS auth secrets. + var secretsDir = Path.Combine(dataDir, "secrets", "nats"); Directory.CreateDirectory(natsDir); Directory.CreateDirectory(Path.Combine(dataDir, "db")); @@ -124,10 +140,12 @@ public static class ServerCli return ensured; } - // NATS operator/account keys + resolver preload (idempotent). + // NATS operator/account keys + resolver preload (idempotent). The + // resolver dir is relative to the sidecar's working dir (natsDir), so + // it lands in data/resolver rather than the filesystem root. if (!File.Exists(Path.Combine(secretsDir, "resolver.conf"))) { - var result = NatsAuthCli.Run(["init", "--output", secretsDir]); + var result = NatsAuthCli.Run(["init", "--output", secretsDir, "--resolver-dir", "../data/resolver"]); if (result != 0) { return result; @@ -149,10 +167,11 @@ public static class ServerCli # 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:{{natsPort}} - http: 127.0.0.1:{{natsMonitorPort}} + # Listeners bind to {{natsBind}} (loopback by default; the server + # proxies /messaging/* to the websocket port). Set --nats-bind + # to open them when an edge proxy on another host needs them. + listen: {{natsBind}}:{{natsPort}} + http: {{natsBind}}:{{natsMonitorPort}} jetstream { # nats-server appends "jetstream" itself: this lands in @@ -161,11 +180,11 @@ public static class ServerCli } websocket { - listen: 127.0.0.1:{{natsWsPort}} + listen: {{natsBind}}:{{natsWsPort}} no_tls: true } - include "../secrets/nats/resolver.conf" + include "../data/secrets/nats/resolver.conf" """); Console.WriteLine($"Wrote {natsConf}"); } @@ -183,9 +202,10 @@ public static class ServerCli File.WriteAllText(appsettings, $$""" { "Urls": "http://{{bindAddress}}:{{httpPort}}", + "DATA_PATH": "{{dataDir.Replace('\\', '/')}}", "DATABASE_PATH": "{{Path.Combine(dataDir, "db", "app.db").Replace('\\', '/')}}", "DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}", - "LOG_PATH": "{{Path.Combine(baseDir, "logs").Replace('\\', '/')}}", + "LOG_DIRECTORY": "{{Path.Combine(baseDir, "logs").Replace('\\', '/')}}", "AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}", "NATS_URL": "nats://127.0.0.1:{{natsPort}}", "NATS_SIDECAR": "1", @@ -214,7 +234,7 @@ public static class ServerCli ? $" - First sign-in: {adminUser} / admin — a new password is required immediately." : $" - First sign-in: {adminUser} / ."); var scheme = selfSignedTls ? "https" : "http"; - Console.WriteLine($" - UI + API on {scheme}://{bindAddress}:{httpPort} (NATS local-only on {natsPort}/{natsWsPort}/{natsMonitorPort})."); + Console.WriteLine($" - UI + API on {scheme}://{bindAddress}:{httpPort} (NATS on {natsBind}: {natsPort}/{natsWsPort}/{natsMonitorPort})."); if (selfSignedTls) { Console.WriteLine(" - Self-signed TLS: the hop is encrypted; reverse proxies either skip"); @@ -223,7 +243,7 @@ public static class ServerCli 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(" - Run the binary directly, or `service install` to register the Windows service."); Console.WriteLine(" - Put a TLS-terminating proxy in front for production use."); return 0; } diff --git a/src/Backend/Tls/SelfSignedTlsManager.cs b/src/Backend/Tls/SelfSignedTlsManager.cs index d9339df..18cc847 100644 --- a/src/Backend/Tls/SelfSignedTlsManager.cs +++ b/src/Backend/Tls/SelfSignedTlsManager.cs @@ -160,6 +160,10 @@ public sealed class SelfSignedTlsManager certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 1, critical: true)); request.CertificateExtensions.Add(new X509KeyUsageExtension( X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true)); + // Constrain the whole chain to TLS server authentication only — this is + // not a client-auth PKI. EKU nests down to the leaf. + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + [new Oid("1.3.6.1.5.5.7.3.1")], critical: false)); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root); } @@ -172,6 +176,9 @@ public sealed class SelfSignedTlsManager certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 0, critical: true)); request.CertificateExtensions.Add(new X509KeyUsageExtension( X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true)); + // Server-authentication-only chain (see root); no client auth. + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + [new Oid("1.3.6.1.5.5.7.3.1")], critical: false)); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); request.CertificateExtensions.Add( X509AuthorityKeyIdentifierExtension.CreateFromCertificate( diff --git a/src/Backend/Tls/TlsSettings.cs b/src/Backend/Tls/TlsSettings.cs index d679c37..a0f3b68 100644 --- a/src/Backend/Tls/TlsSettings.cs +++ b/src/Backend/Tls/TlsSettings.cs @@ -45,8 +45,14 @@ public sealed class TlsSettings { var enabled = configuration["TLS_SELF_SIGNED"] != "0"; var certDir = configuration["TLS_CERT_DIR"]; - var dataDir = Path.GetDirectoryName(Path.GetFullPath( - configuration["DATABASE_PATH"] is { Length: > 0 } db ? db : "data/app.db")) ?? "data"; + // Prefer the explicit data root; otherwise fall back to the database's + // directory. The DB now lives in data/db, so deriving from it alone + // would nest the cert store at data/db/tls — DATA_PATH keeps it at + // data/tls alongside db, keys and jetstream. + var dataDir = configuration["DATA_PATH"] is { Length: > 0 } dataRoot + ? Path.GetFullPath(dataRoot) + : 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 }; diff --git a/src/Installer.Server/Product.wxs b/src/Installer.Server/Product.wxs index a1a0897..7df2f66 100644 --- a/src/Installer.Server/Product.wxs +++ b/src/Installer.Server/Product.wxs @@ -47,9 +47,7 @@ - - Install the server's self-signed CA - Installs the ExecuteR server's managed self-signed CA (root + intermediate) into the machine trust store, and keeps it current when the server rotates its chain. - -If you enable this policy, ordinary system certificate validation trusts a direct or local connection to a self-signed server. It is not certificate pinning and it is not forced: if the server is later reached through a reverse proxy presenting a publicly trusted certificate, that certificate validates normally and the installed self-signed CA simply goes unused. - -If you disable or do not configure this policy, the agent does not install the CA. Use this for a self-signed server without a proxy; leave it off when a real edge certificate is in front. - -For an accept-any escape hatch (no validation at all), see "Skip TLS certificate verification" instead. - The agent reads configuration at service start; restart the "ExecuteR Agent" service (ExecuteRAgent) to apply a change immediately. Outbound proxy URL diff --git a/src/Installer/Product.wxs b/src/Installer/Product.wxs index 17521cc..64801bc 100644 --- a/src/Installer/Product.wxs +++ b/src/Installer/Product.wxs @@ -5,7 +5,9 @@ - - - - - - - @@ -149,17 +137,19 @@ - - - - - + + + + + @@ -169,6 +159,11 @@ + + + - + /// Reads LOG_LEVEL / LOG_JSON / LOG_DIRECTORY / LOG_RETAIN_FILES / /// LOG_MAX_BYTES, falling back to the supplied per-role - /// . + /// . LOG_PATH is accepted as an alias for + /// LOG_DIRECTORY so a mismatched key never silently disables file logging. /// public static LogSettings FromConfiguration( IConfiguration configuration, @@ -40,6 +41,11 @@ public sealed record LogSettings string? defaultDirectory = null) { var directory = configuration["LOG_DIRECTORY"]; + if (string.IsNullOrWhiteSpace(directory)) + { + directory = configuration["LOG_PATH"]; + } + if (string.IsNullOrWhiteSpace(directory)) { directory = defaultDirectory; diff --git a/src/Shared.Infrastructure/Logging/LoggingSetup.cs b/src/Shared.Infrastructure/Logging/LoggingSetup.cs index 2fdf1d0..743fa76 100644 --- a/src/Shared.Infrastructure/Logging/LoggingSetup.cs +++ b/src/Shared.Infrastructure/Logging/LoggingSetup.cs @@ -47,7 +47,11 @@ public static class LoggingSetup if (settings.FileEnabled) { - var path = Path.Combine(settings.Directory!, settings.FileName); + // Name logs after the running binary so they read + // ExecuteR-Server-.log / ExecuteR-Agent-.log and track + // the executable if it is renamed. The trailing '-' becomes the + // date separator (Serilog inserts the date before the extension). + var path = Path.Combine(settings.Directory!, $"{LogFileBaseName(settings.FileName)}-.log"); try { Directory.CreateDirectory(settings.Directory!); @@ -91,6 +95,24 @@ public static class LoggingSetup ? parsed : LogEventLevel.Information; + /// + /// Base log-file name from the running executable (e.g. "ExecuteR-Server"). + /// Falls back to the entry assembly under `dotnet run`/`dotnet App.dll` + /// (where the process is the shared host) and finally to the role default. + /// + private static string LogFileBaseName(string roleFallback) + { + var name = Path.GetFileNameWithoutExtension(Environment.ProcessPath); + if (string.IsNullOrWhiteSpace(name) || name.Equals("dotnet", StringComparison.OrdinalIgnoreCase)) + { + name = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name; + } + + return string.IsNullOrWhiteSpace(name) + ? Path.GetFileNameWithoutExtension(roleFallback) + : name; + } + /// Structured-log property names used for correlation. public static class Fields { diff --git a/src/WebUI/src/lib/components/AddDeviceModal.svelte b/src/WebUI/src/lib/components/AddDeviceModal.svelte index 0421be2..7016322 100644 --- a/src/WebUI/src/lib/components/AddDeviceModal.svelte +++ b/src/WebUI/src/lib/components/AddDeviceModal.svelte @@ -16,7 +16,6 @@ let token = $state(''); let tokenId = $state(''); let baseUrl = $state(''); - let skipTlsVerify = $state(false); let errorText = $state(''); let busy = $state(false); let regenTimer: ReturnType | undefined; @@ -32,10 +31,6 @@ .serverInfo() .then((info) => { baseUrl = info.baseUrl ?? location.origin; - // Pre-select only while the server serves its self-signed chain - // directly; the operator decides either way (a proxy added later - // should not leave agents skipping verification needlessly). - skipTlsVerify = info.selfSignedDirect ?? false; }) .catch(() => (baseUrl = location.origin)); @@ -97,30 +92,27 @@ const command = $derived.by(() => { if (!token || !baseUrl) return ''; - // skipVerify=1 makes the served script configure the agent's - // TlsSkipVerify too; the fetch itself gets the same treatment. The - // hop is still encrypted — the roots just aren't distributed. - const install = `${baseUrl}/api/enrollment/install?token=${token}${skipTlsVerify ? '&skipVerify=1' : ''}`; - const curl = skipTlsVerify ? 'curl -fsSLk' : 'curl -fsSL'; - // PS7's iwr/irm need -SkipCertificateCheck (set as a wildcard default - // so the fetched script inherits it too); PS5.1 needs the callback. - const psPrefix = skipTlsVerify - ? "if ($PSVersionTable.PSVersion.Major -ge 6) { $PSDefaultParameterValues['*:SkipCertificateCheck'] = $true } else { [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } }; " - : ''; + // The served script decides trust itself: when the server runs + // self-signed TLS it makes the agent fetch and trust the CA, and if this + // origin is the self-signed listener directly it also skips verification + // for its own download. Nothing here to toggle. + const install = `${baseUrl}/api/enrollment/install?token=${token}`; switch (platform) { case 'windows': - return `${psPrefix}iwr '${install}' -UseBasicParsing | iex`; + // Wrapped as a single powershell.exe -Command so it pastes into + // a Run box (Win+R) or an elevated prompt, not just a PS host. + return `powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "iwr '${install}' -UseBasicParsing | iex"`; case 'linux': - return `${curl} '${install}&type=linux' | sudo bash`; + return `bash -c "curl -fsSL '${install}&type=linux' | sudo bash"`; case 'macos': - return `${curl} '${install}&type=osx' | sudo bash`; + return `bash -c "curl -fsSL '${install}&type=osx' | sudo bash"`; } }); const shellHint = $derived( platform === 'windows' - ? 'Run in an elevated PowerShell on the device.' - : 'Run in a terminal on the device (needs sudo).' + ? 'Paste into a prompt or the Win+R Run box on the device.' + : 'Paste into a terminal on the device (needs sudo).' ); @@ -192,11 +184,6 @@ (pipelines and pre-staged installers; revoke when done) {/if} - {#if errorText} @@ -205,7 +192,7 @@ {#if command}
- +

{#if busy}Updating the token…{:else} diff --git a/src/WebUI/src/lib/components/CopyChip.svelte b/src/WebUI/src/lib/components/CopyChip.svelte index 037f16d..4287b7f 100644 --- a/src/WebUI/src/lib/components/CopyChip.svelte +++ b/src/WebUI/src/lib/components/CopyChip.svelte @@ -1,5 +1,7 @@