Installer + automatic self-signed trust + standalone layout fixes #10
+7
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 230 KiB After Width: | Height: | Size: 258 KiB |
@@ -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 <server-url> [--token <bootstrap-token>] [--proxy <proxy-url>] [--install-server-ca] [--skip-tls-verify]");
|
||||
Console.Error.WriteLine("Usage: configure --url <server-url> [--token <bootstrap-token>] [--proxy <proxy-url>] [--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);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,14 +21,6 @@ public sealed class AgentConfiguration
|
||||
public required ConfigurationValue<bool> TlsSkipVerify { get; init; }
|
||||
public required ConfigurationValue<string?> ProxyUrl { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public ConfigurationValue<bool> ServerCaAutoInstall { get; init; } = new(false, ConfigurationSource.Default);
|
||||
|
||||
/// <summary>Parsed ServerURL; null when unset or invalid.</summary>
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -20,14 +20,6 @@ public static class AgentConfigurationKeys
|
||||
/// </summary>
|
||||
public const string TlsSkipVerify = "TlsSkipVerify";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const string ServerCaAutoInstall = "ServerCaAutoInstall";
|
||||
|
||||
/// <summary>
|
||||
/// Explicit outbound proxy URL (http://proxy:8080). Unset, the agent
|
||||
/// honors the system/environment proxy; either way it authenticates to
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -69,7 +69,8 @@ public static class AgentHost
|
||||
builder.Services.AddSingleton(new AgentConfigurationLoader(registry, allowEnvironment: !runAsService));
|
||||
|
||||
builder.Services.AddHostedService<AgentWorker>();
|
||||
// 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<CaRefreshService>();
|
||||
|
||||
return builder.Build();
|
||||
|
||||
@@ -6,30 +6,26 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Agent.Service;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class CaRefreshService(
|
||||
AgentConfigurationLoader loader, ILogger<CaRefreshService> 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);
|
||||
|
||||
@@ -32,9 +32,11 @@ public static class InstallEndpoints
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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}}
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
@@ -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.
|
||||
/// </summary>
|
||||
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}}
|
||||
""";
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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} / <your password>.");
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<string> { "localhost" };
|
||||
var ipAddresses = new List<IPAddress> { IPAddress.Loopback, IPAddress.IPv6Loopback };
|
||||
|
||||
@@ -47,9 +47,7 @@
|
||||
<Property Id="ADMINUSERNAME" Value="admin" />
|
||||
<Property Id="ADMINPASSWORD" Value="admin" Hidden="yes" />
|
||||
|
||||
<!-- Listen configuration (single-instance defaults). Multiple instances
|
||||
on one machine use the ZIP bundle with distinct ports and custom
|
||||
service names; the MSI installs exactly one. -->
|
||||
<!-- Listen configuration defaults. -->
|
||||
<Property Id="BINDADDRESS" Value="0.0.0.0" />
|
||||
<Property Id="HTTPPORT" Value="9080" />
|
||||
<Property Id="NATSPORT" Value="4222" />
|
||||
@@ -84,8 +82,21 @@
|
||||
<Files Include="$(var.ServerPublishDir)\**" />
|
||||
</ComponentGroup>
|
||||
|
||||
<!-- Record the install location so tools can find it later, and put the
|
||||
binary on the system PATH. Both the registry value and the PATH entry
|
||||
are removed on uninstall (Permanent="no"). -->
|
||||
<ComponentGroup Id="ServerRegistration" Directory="INSTALLFOLDER">
|
||||
<Component Id="ServerRegistration" Guid="7a1e3c92-4b6d-4e11-9f28-2c5a7d0b9e34">
|
||||
<RegistryValue Root="HKLM" Key="SOFTWARE\ExecuteR\Server" Name="InstallDir"
|
||||
Type="string" Value="[INSTALLFOLDER]" KeyPath="yes" />
|
||||
<Environment Id="ServerPath" Name="PATH" Value="[INSTALLFOLDER]" Part="last"
|
||||
Action="set" System="yes" Permanent="no" />
|
||||
</Component>
|
||||
</ComponentGroup>
|
||||
|
||||
<Feature Id="Main" Title="ExecuteR Server" Level="1">
|
||||
<ComponentGroupRef Id="ServerFiles" />
|
||||
<ComponentGroupRef Id="ServerRegistration" />
|
||||
</Feature>
|
||||
|
||||
<!-- First-boot init through the binary's own cross-platform CLI. -->
|
||||
@@ -125,10 +136,18 @@
|
||||
Impersonate="no"
|
||||
Return="ignore" />
|
||||
|
||||
<!-- Clean uninstall: PURGEDATA=1 (Remove page checkbox, or property on
|
||||
a silent uninstall) forgets the self-signed chain and deletes the
|
||||
generated data/logs/secrets/appsettings. Runs while the binary
|
||||
still exists (before RemoveFiles). -->
|
||||
<!-- Report the install location the standard way, so Win32_Product
|
||||
.InstallLocation and the ARP InstallLocation registry value point at
|
||||
the directory. Set after costing, when [INSTALLFOLDER] is resolved. -->
|
||||
<SetProperty Id="ARPINSTALLLOCATION" Value="[INSTALLFOLDER]" After="CostFinalize" />
|
||||
|
||||
<!-- Clean uninstall: PURGEDATA=1 (the Remove page checkbox in the full
|
||||
wizard, or a property on a command-line/silent uninstall) forgets the
|
||||
self-signed chain and deletes the generated
|
||||
data/logs/secrets/appsettings. Runs while the binary still exists
|
||||
(before RemoveFiles). A basic-UI uninstall (the Settings app) keeps
|
||||
everything by default — pass PURGEDATA=1 or run
|
||||
`ExecuteR-Server.exe purge` to remove it. -->
|
||||
<Property Id="PURGEDATA" Secure="yes" />
|
||||
<SetProperty Id="PurgeServerData"
|
||||
Value=""[INSTALLFOLDER]ExecuteR-Server.exe" purge --yes"
|
||||
@@ -196,7 +215,7 @@
|
||||
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
|
||||
|
||||
<Control Id="BindLabel" Type="Text" X="20" Y="54" Width="330" Height="12" NoPrefix="yes"
|
||||
Text="Bind address (0.0.0.0 = every interface; 127.0.0.1 = local proxy only):" />
|
||||
Text="Bind address (0.0.0.0 = every interface; 127.0.0.1 = this machine only):" />
|
||||
<Control Id="BindEdit" Type="Edit" X="20" Y="67" Width="140" Height="16"
|
||||
Property="BINDADDRESS" />
|
||||
|
||||
@@ -218,10 +237,10 @@
|
||||
Property="ENABLETLS" CheckBoxValue="1"
|
||||
Text="Enable Self-Signed TLS (auto-renewed)" />
|
||||
<Control Id="TlsNote" Type="Text" X="32" Y="190" Width="318" Height="20" NoPrefix="yes"
|
||||
Text="Reverse proxies: skip TLS verification (traffic stays encrypted), or import the root + intermediate and re-import when they rotate." />
|
||||
Text="Serves the listener over HTTPS with a locally managed certificate chain that renews itself. Browsers on the server trust it automatically." />
|
||||
|
||||
<Control Id="Note" Type="Text" X="20" Y="214" Width="330" Height="18" NoPrefix="yes"
|
||||
Text="Settings persist in appsettings.json next to the binary. Multiple instances on one machine: use the ZIP bundle." />
|
||||
Text="Settings persist in appsettings.json next to the binary." />
|
||||
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
|
||||
|
||||
@@ -143,15 +143,5 @@
|
||||
</elements>
|
||||
</policy>
|
||||
|
||||
<!-- ServerCaAutoInstall (REG_DWORD) -->
|
||||
<policy name="ServerCaAutoInstall" class="Machine" displayName="$(string.ServerCaAutoInstall)"
|
||||
explainText="$(string.ServerCaAutoInstall_Help)"
|
||||
key="SOFTWARE\Policies\ExecuteR"
|
||||
valueName="ServerCaAutoInstall">
|
||||
<parentCategory ref="ExecuteR" />
|
||||
<supportedOn ref="SUPPORTED_ExecuteR_1_0" />
|
||||
<enabledValue><decimal value="1" /></enabledValue>
|
||||
<disabledValue><decimal value="0" /></disabledValue>
|
||||
</policy>
|
||||
</policies>
|
||||
</policyDefinitions>
|
||||
|
||||
@@ -111,17 +111,6 @@ If you disable or do not configure this policy, the agent uses the locally confi
|
||||
|
||||
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.</string>
|
||||
|
||||
<string id="ServerCaAutoInstall">Install the server's self-signed CA</string>
|
||||
<string id="ServerCaAutoInstall_Help">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.</string>
|
||||
|
||||
<string id="ProxyUrl">Outbound proxy URL</string>
|
||||
|
||||
+19
-29
@@ -5,7 +5,9 @@
|
||||
<!--
|
||||
ExecuteR Agent MSI.
|
||||
Public properties (uppercase): SERVERURL BOOTSTRAPTOKEN LOGLEVEL
|
||||
ALLOWREMOTESHELL ALLOWSCRIPTEXECUTION SKIPTLSVERIFY PROXYURL CAINSTALL.
|
||||
ALLOWREMOTESHELL ALLOWSCRIPTEXECUTION PROXYURL. Certificate trust is not a
|
||||
property: a self-signed server's CA is fetched and trusted automatically
|
||||
at enrollment; the TlsSkipVerify escape hatch is CLI/GPO only.
|
||||
Remember-property pattern: existing registry values are read back into
|
||||
the properties at install start, so blank properties never overwrite
|
||||
configured values and upgrades preserve configuration.
|
||||
@@ -64,26 +66,12 @@
|
||||
<RegistrySearch Id="ExistingAllowScriptExecution" Root="HKLM"
|
||||
Key="$(var.AgentRegKey)" Name="AllowScriptExecution" Type="raw" />
|
||||
</Property>
|
||||
<!-- SKIPTLSVERIFY=1: accept the server's managed self-signed chain (the
|
||||
connection stays TLS-encrypted; the roots just aren't distributed). -->
|
||||
<Property Id="SKIPTLSVERIFY">
|
||||
<RegistrySearch Id="ExistingTlsSkipVerify" Root="HKLM"
|
||||
Key="$(var.AgentRegKey)" Name="TlsSkipVerify" Type="raw" />
|
||||
</Property>
|
||||
<!-- PROXYURL: explicit outbound proxy. Unset, the agent honors the
|
||||
system/environment proxy; default credentials either way. -->
|
||||
<Property Id="PROXYURL">
|
||||
<RegistrySearch Id="ExistingProxyUrl" Root="HKLM"
|
||||
Key="$(var.AgentRegKey)" Name="ProxyUrl" Type="raw" />
|
||||
</Property>
|
||||
<!-- CAINSTALL=1: install the server's managed self-signed CA into the OS
|
||||
trust store (kept current) so system validation trusts a direct
|
||||
self-signed server. Not pinning; a real cert behind a proxy still
|
||||
validates normally. -->
|
||||
<Property Id="CAINSTALL">
|
||||
<RegistrySearch Id="ExistingServerCaAutoInstall" Root="HKLM"
|
||||
Key="$(var.AgentRegKey)" Name="ServerCaAutoInstall" Type="raw" />
|
||||
</Property>
|
||||
|
||||
<StandardDirectory Id="ProgramFiles64Folder">
|
||||
<Directory Id="ExecuteRFolder" Name="ExecuteR">
|
||||
@@ -149,17 +137,19 @@
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)"
|
||||
Name="AllowScriptExecution" Type="integer" Value="[ALLOWSCRIPTEXECUTION]" KeyPath="yes" />
|
||||
</Component>
|
||||
<Component Id="RegTlsSkipVerify" Guid="6b8e4a1d-9c02-47e3-b7a4-2e1f83c5d907" Condition="SKIPTLSVERIFY">
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)"
|
||||
Name="TlsSkipVerify" Type="integer" Value="[SKIPTLSVERIFY]" KeyPath="yes" />
|
||||
</Component>
|
||||
<Component Id="RegProxyUrl" Guid="4c7d90b5-31af-4e88-9c56-d0b1f2a6e843" Condition="PROXYURL">
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)"
|
||||
Name="ProxyUrl" Type="string" Value="[PROXYURL]" KeyPath="yes" />
|
||||
</Component>
|
||||
<Component Id="RegServerCaAutoInstall" Guid="a1f5c2e7-8d43-4b9a-bc16-7e0d9f42a3b8" Condition="CAINSTALL">
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)"
|
||||
Name="ServerCaAutoInstall" Type="integer" Value="[CAINSTALL]" KeyPath="yes" />
|
||||
|
||||
<!-- Always installed: record the install location so tools can find it
|
||||
later, and put the agent on the system PATH. Both are removed on
|
||||
uninstall (Permanent="no"). -->
|
||||
<Component Id="AgentRegistration" Guid="b2d7f4a1-6c3e-4a90-8d15-3f9c2e0a7b56">
|
||||
<RegistryValue Root="HKLM" Key="$(var.AgentRegKey)" Name="InstallDir"
|
||||
Type="string" Value="[INSTALLFOLDER]" KeyPath="yes" />
|
||||
<Environment Id="AgentPath" Name="PATH" Value="[INSTALLFOLDER]" Part="last"
|
||||
Action="set" System="yes" Permanent="no" />
|
||||
</Component>
|
||||
|
||||
</ComponentGroup>
|
||||
@@ -169,6 +159,11 @@
|
||||
<ComponentGroupRef Id="BundledModules" />
|
||||
</Feature>
|
||||
|
||||
<!-- Report the install location the standard way, so Win32_Product
|
||||
.InstallLocation and the ARP InstallLocation registry value point at
|
||||
the directory. Set after costing, when [INSTALLFOLDER] is resolved. -->
|
||||
<SetProperty Id="ARPINSTALLLOCATION" Value="[INSTALLFOLDER]" After="CostFinalize" />
|
||||
|
||||
<!--
|
||||
Delayed auto-start cannot be set reliably through the MSI ServiceConfig
|
||||
table; the agent's own idempotent `install` command applies delayed
|
||||
@@ -230,13 +225,8 @@
|
||||
<Control Id="TokenEdit" Type="Edit" X="20" Y="114" Width="330" Height="17"
|
||||
Property="BOOTSTRAPTOKEN" Password="yes" />
|
||||
|
||||
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="44" NoPrefix="yes"
|
||||
Text="Blank keeps values already configured (upgrades), or set later via registry / Group Policy. The service enrolls once both values are present. Silent: SERVERURL=... BOOTSTRAPTOKEN=..." />
|
||||
|
||||
<!-- Unchecked by default; prefilled from the registry on upgrades. -->
|
||||
<Control Id="CaInstallCheck" Type="CheckBox" X="20" Y="192" Width="330" Height="14"
|
||||
Property="CAINSTALL" CheckBoxValue="1"
|
||||
Text="Trust self-signed server (install its CA into the trust store)" />
|
||||
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="60" NoPrefix="yes"
|
||||
Text="Blank keeps values already configured (upgrades), or set later via registry / Group Policy. The service enrolls once both values are present. A self-signed server's certificate is trusted automatically. Silent: SERVERURL=... BOOTSTRAPTOKEN=..." />
|
||||
|
||||
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
|
||||
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
|
||||
|
||||
@@ -32,7 +32,8 @@ public sealed record LogSettings
|
||||
/// <summary>
|
||||
/// Reads LOG_LEVEL / LOG_JSON / LOG_DIRECTORY / LOG_RETAIN_FILES /
|
||||
/// LOG_MAX_BYTES, falling back to the supplied per-role
|
||||
/// <paramref name="defaults"/>.
|
||||
/// <paramref name="defaults"/>. LOG_PATH is accepted as an alias for
|
||||
/// LOG_DIRECTORY so a mismatched key never silently disables file logging.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
@@ -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-<date>.log / ExecuteR-Agent-<date>.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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Structured-log property names used for correlation.</summary>
|
||||
public static class Fields
|
||||
{
|
||||
|
||||
@@ -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<typeof setTimeout> | 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).'
|
||||
);
|
||||
</script>
|
||||
|
||||
@@ -192,11 +184,6 @@
|
||||
<span class="faint">(pipelines and pre-staged installers; revoke when done)</span>
|
||||
</label>
|
||||
{/if}
|
||||
<label class="radio">
|
||||
<input type="checkbox" bind:checked={skipTlsVerify} />
|
||||
Trust self-signed certificate
|
||||
<span class="faint">(self-signed server without a proxy — installs its CA so system trust works)</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if errorText}
|
||||
@@ -205,7 +192,7 @@
|
||||
|
||||
{#if command}
|
||||
<div class="command-wrap" class:updating={busy}>
|
||||
<CopyChip value={command} label="Install command" />
|
||||
<CopyChip value={command} label="Install command" wrap />
|
||||
</div>
|
||||
<p class="muted small">
|
||||
{#if busy}Updating the token…{:else}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<script lang="ts">
|
||||
let { value, label }: { value: string; label?: string } = $props();
|
||||
// wrap: show the whole value (wraps to as many lines as needed) instead of
|
||||
// truncating — for paste-ready commands where the full text must be seen.
|
||||
let { value, label, wrap = false }: { value: string; label?: string; wrap?: boolean } = $props();
|
||||
|
||||
let copied = $state(false);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -16,6 +18,7 @@
|
||||
type="button"
|
||||
class="chip mono"
|
||||
class:copied
|
||||
class:wrap
|
||||
onclick={copy}
|
||||
title="Copy {label ?? value} to clipboard"
|
||||
>
|
||||
@@ -53,6 +56,24 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Full-command view: show every character, wrapping as needed. */
|
||||
.chip.wrap {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
align-items: flex-start;
|
||||
text-align: left;
|
||||
padding: 8px 10px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.chip.wrap .value {
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.glyph {
|
||||
flex-shrink: 0;
|
||||
color: var(--text-faint);
|
||||
|
||||
@@ -17,16 +17,14 @@
|
||||
let busy = $state(false);
|
||||
let copied = $state(false);
|
||||
let copiedCmd = $state(false);
|
||||
let skipTlsVerify = $state(false);
|
||||
|
||||
// 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. Skip-verify is an operator
|
||||
// choice (pre-selected only while serving the self-signed chain directly);
|
||||
// the hop stays encrypted either way.
|
||||
// hostname the target devices cannot reach. The served script decides trust
|
||||
// itself from the server's self-signed state — no operator toggle.
|
||||
const installCommand = $derived(
|
||||
newToken?.token
|
||||
? `${skipTlsVerify ? "if ($PSVersionTable.PSVersion.Major -ge 6) { $PSDefaultParameterValues['*:SkipCertificateCheck'] = $true } else { [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } }; " : ''}iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token}${skipTlsVerify ? '&skipVerify=1' : ''} -UseBasicParsing | iex`
|
||||
? `iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex`
|
||||
: ''
|
||||
);
|
||||
|
||||
@@ -40,7 +38,6 @@
|
||||
.serverInfo()
|
||||
.then((info) => {
|
||||
serverInfo = info;
|
||||
skipTlsVerify = info.selfSignedDirect ?? false;
|
||||
})
|
||||
.catch(() => (serverInfo = null));
|
||||
});
|
||||
@@ -134,10 +131,6 @@
|
||||
<div class="install-block pulse-in">
|
||||
<div class="muted">Deploy on a target device (run in an elevated PowerShell):</div>
|
||||
<div class="install-cmd mono">{installCommand}</div>
|
||||
<label class="faint small">
|
||||
<input type="checkbox" bind:checked={skipTlsVerify} />
|
||||
Trust self-signed certificate (self-signed server without a proxy — installs its CA so system trust works)
|
||||
</label>
|
||||
<button class="btn" onclick={copyCommand}>{copiedCmd ? '✔ Copied' : 'Copy command'}</button>
|
||||
<div class="faint small">
|
||||
Requires Agent.msi in the backend’s AGENT_PACKAGE_PATH. Also usable:
|
||||
|
||||
@@ -123,6 +123,28 @@ public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<Back
|
||||
Assert.Contains("test-token", script);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("msi")]
|
||||
[InlineData("zip")]
|
||||
public async Task WindowsScriptsSelfElevate(string? type)
|
||||
{
|
||||
// Not admin -> re-launch elevated (UAC) running the script's own body
|
||||
// from a temp .ps1 with -NoExit; already admin -> run in place. Plain
|
||||
// -File, never -EncodedCommand (which trips AV/EDR), and no
|
||||
// #Requires -RunAsAdministrator (which would block the auto-elevation).
|
||||
using var client = fixture.CreateClient();
|
||||
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
|
||||
var script = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
|
||||
|
||||
Assert.Contains("WindowsBuiltInRole]::Administrator", script);
|
||||
Assert.Contains("-Verb RunAs", script);
|
||||
Assert.Contains("-NoExit", script);
|
||||
Assert.Contains("$install.ToString()", script);
|
||||
Assert.DoesNotContain("-EncodedCommand", script);
|
||||
Assert.DoesNotContain("#Requires -RunAsAdministrator", script);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("linux", "type=linux-${arch}")]
|
||||
[InlineData("osx", "type=osx-${arch}")]
|
||||
@@ -151,32 +173,29 @@ public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<Back
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SkipVerifyIsAnOperatorChoicePerRequest()
|
||||
public async Task TrustIsDecidedByServerNotAQueryParameter()
|
||||
{
|
||||
// &skipVerify=1 is the operator opting in (the modal checkbox);
|
||||
// every install path then skips verification and configures the
|
||||
// agent to keep doing so. Without the parameter nothing is inferred
|
||||
// — a self-signed server that later gains a proxy must not leave
|
||||
// agents skipping validation needlessly.
|
||||
// The server decides trust: with self-signed TLS OFF (the test host
|
||||
// runs plain HTTP) the scripts neither skip verification nor
|
||||
// auto-install a CA, and the legacy skipVerify=1 parameter is ignored.
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var msi = await (await client.GetAsync("/api/enrollment/install?token=t&skipVerify=1")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("ServerCertificateValidationCallback", msi); // PS 5.1 download path
|
||||
Assert.Contains("SkipCertificateCheck", msi); // PS 7 download path
|
||||
Assert.Contains("CAINSTALL=1", msi);
|
||||
var msi = await (await client.GetAsync("/api/enrollment/install?token=t")).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("ServerCertificateValidationCallback", msi);
|
||||
Assert.DoesNotContain("SkipCertificateCheck", msi);
|
||||
Assert.DoesNotContain("CAINSTALL", msi);
|
||||
|
||||
var zip = await (await client.GetAsync("/api/enrollment/install?token=t&type=zip&skipVerify=1")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("ServerCertificateValidationCallback", zip);
|
||||
Assert.Contains("ServerCaAutoInstall", zip);
|
||||
var zip = await (await client.GetAsync("/api/enrollment/install?token=t&type=zip")).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("ServerCaAutoInstall", zip);
|
||||
|
||||
var bash = await (await client.GetAsync("/api/enrollment/install?token=t&type=linux&skipVerify=1")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("curl -fsSLk", bash);
|
||||
Assert.Contains("--install-server-ca", bash);
|
||||
var bash = await (await client.GetAsync("/api/enrollment/install?token=t&type=linux")).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("fsSLk", bash); // no -k: verification stays on
|
||||
Assert.DoesNotContain("--install-server-ca", bash);
|
||||
|
||||
var plain = await (await client.GetAsync("/api/enrollment/install?token=t")).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("ServerCertificateValidationCallback", plain);
|
||||
Assert.DoesNotContain("CAINSTALL", plain);
|
||||
Assert.DoesNotContain("--install-server-ca", plain);
|
||||
// A stray skipVerify=1 no longer changes anything — trust is not a knob.
|
||||
var ignored = await (await client.GetAsync("/api/enrollment/install?token=t&skipVerify=1")).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SkipCertificateCheck", ignored);
|
||||
Assert.DoesNotContain("CAINSTALL", ignored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user