2df42b09ed
Envelope v2 on top of TLS and NATS permissions: AES-256-GCM with a key per message (HKDF-SHA256 over an ECDH P-256 secret, message id as salt, direction as info), the header (kid, type, message id, issue/expiry, sender, subject) as associated data, and an Ed25519 signature (server signing key / agent NKey) over header, nonce and ciphertext. v1 is still parsed from unsealed agents. - Keys: the server's signing + ECDH key set is a Data Protection-encrypted setting, current + previous (7 days), rotated from Settings > Message Security and announced to sealed agents signed with the old key. Agents keep an ECDH key with their credentials and pin the server's keys at enrollment, or for agents enrolled earlier at their first credential renewal (HTTPS, proof signed with the enrolled NKey covering the message key). - Replay: issued/expiry on every message (live 2 min, queued commands 2 days, job states 7 days, 5 min skew, configurable both sides); seen ids persisted on the agent (job store), in the database for agent events, in a bounded window otherwise; queued messages remembered on ack. - Remote View and file/log/registry transfers: per-stream AES-GCM frames with counter nonces; duplicates and reordering refused. - Browser NATS traffic (events, job and shell output, keystrokes) sealed per session with a WebCrypto ECDH key. - Rollout: Sealed chip on the device list and page, inventory reports it, Require Sealed Agents (off by default) refuses v1 and sends nothing to unsealed agents. Job messages must be signed by the device they name. - Migrations MessageSecurity (Sqlite, Postgres, SqlServer); README Message security section. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
216 lines
8.4 KiB
C#
216 lines
8.4 KiB
C#
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using Agent.Configuration;
|
|
using Agent.Enrollment;
|
|
using Agent.Identity;
|
|
using Agent.Inventory;
|
|
using Agent.Platform;
|
|
using Agent.Storage;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Shared.Infrastructure.Constants;
|
|
using Xunit;
|
|
|
|
namespace Agent.Tests;
|
|
|
|
/// <summary>Redeploying over an enrolled agent: the working enrollment survives anything but success.</summary>
|
|
public class EnrollmentServiceTests
|
|
{
|
|
private static readonly HardwareIdentity Hardware = new("4C4C4544-0002-0010-8039-B4C04F303233", "SN1002", null, null, "Dell", "OptiPlex");
|
|
private static readonly string ClientId = ClientIdentityFactory.ComputeClientId(Hardware);
|
|
|
|
private readonly InMemoryRegistryStore registry = new();
|
|
private readonly InMemoryCredentialStore credentials = new();
|
|
|
|
[Fact]
|
|
public async Task ARejectedTokenKeepsTheWorkingEnrollmentAndIsDropped()
|
|
{
|
|
using var server = new BootstrapServer(HttpStatusCode.Unauthorized, body: null);
|
|
var stored = Enrolled("jwt-current");
|
|
Configure(server.Url);
|
|
|
|
var result = await Service().EnsureEnrolledAsync(LoadConfiguration(), CancellationToken.None);
|
|
|
|
Assert.Same(stored, result);
|
|
Assert.Same(stored, credentials.Current);
|
|
Assert.Null(registry.ReadString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnUnreachableServerKeepsTheEnrollmentAndTheTokenForNextTime()
|
|
{
|
|
var stored = Enrolled("jwt-current");
|
|
Configure($"http://127.0.0.1:{FreePort()}");
|
|
|
|
var result = await Service().EnsureEnrolledAsync(LoadConfiguration(), CancellationToken.None);
|
|
|
|
Assert.Same(stored, result);
|
|
Assert.Same(stored, credentials.Current);
|
|
Assert.Equal("install-token", registry.ReadString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ASuccessfulReEnrollmentReplacesTheCredentials()
|
|
{
|
|
var enrollmentId = Guid.NewGuid();
|
|
using var server = new BootstrapServer(
|
|
HttpStatusCode.OK,
|
|
$$"""{"enrollmentId":"{{enrollmentId}}","clientId":"{{ClientId}}","userJwt":"jwt-new"}""");
|
|
Enrolled("jwt-current");
|
|
Configure(server.Url);
|
|
|
|
var result = await Service().EnsureEnrolledAsync(LoadConfiguration(), CancellationToken.None);
|
|
|
|
Assert.Equal("jwt-new", result!.UserJwt);
|
|
Assert.Equal(enrollmentId, credentials.Current!.EnrollmentId);
|
|
Assert.Null(registry.ReadString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task EnrollmentSendsAMessageKeyAndPinsTheServersKeys()
|
|
{
|
|
using var signing = NATS.NKeys.KeyPair.CreatePair(NATS.NKeys.PrefixByte.Server);
|
|
using var ecdh = Shared.Infrastructure.Security.Messaging.MessageKeys.Create();
|
|
var serverEcdh = Shared.Infrastructure.Security.Messaging.MessageKeys.PublicKeyOf(ecdh);
|
|
using var server = new BootstrapServer(
|
|
HttpStatusCode.OK,
|
|
$$$"""{"enrollmentId":"{{{Guid.NewGuid()}}}","clientId":"{{{ClientId}}}","userJwt":"jwt-new","serverKeys":{"current":{"kid":"k1","signingPublic":"{{{signing.GetPublicKey()}}}","ecdhPublic":"{{{serverEcdh}}}"},"sealedSinceUtc":"2026-11-06T12:00:00Z"}}""");
|
|
var before = Enrolled("jwt-current");
|
|
Configure(server.Url);
|
|
|
|
var result = await Service().EnsureEnrolledAsync(LoadConfiguration(), CancellationToken.None);
|
|
|
|
using var request = System.Text.Json.JsonDocument.Parse(server.LastRequestBody!);
|
|
var offered = request.RootElement.GetProperty("messageKeyPublic").GetString();
|
|
using var kept = Shared.Infrastructure.Security.Messaging.MessageKeys.FromPrivateKey(result!.MessageKey!);
|
|
Assert.Equal(Shared.Infrastructure.Security.Messaging.MessageKeys.PublicKeyOf(kept), offered);
|
|
Assert.Equal("k1", result.ServerKeys!.Current.Kid);
|
|
Assert.Equal(serverEcdh, result.ServerKeys.Current.EcdhPublic);
|
|
// Re-enrollment replaces both keys.
|
|
Assert.NotEqual(before.MessageKey, result.MessageKey);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task EnrollmentReportsWindowsPeOnlyInWindowsPe(bool inWinPe)
|
|
{
|
|
using var server = new BootstrapServer(
|
|
HttpStatusCode.OK,
|
|
$$"""{"enrollmentId":"{{Guid.NewGuid()}}","clientId":"{{ClientId}}","userJwt":"jwt-new"}""");
|
|
Configure(server.Url);
|
|
|
|
await Service(new WindowsPhase(() => inWinPe)).EnsureEnrolledAsync(LoadConfiguration(), CancellationToken.None);
|
|
|
|
using var request = System.Text.Json.JsonDocument.Parse(server.LastRequestBody!);
|
|
var device = request.RootElement.GetProperty("device");
|
|
var caption = device.GetProperty("osCaption").GetString();
|
|
if (inWinPe)
|
|
{
|
|
Assert.Equal("Windows PE", caption);
|
|
}
|
|
else
|
|
{
|
|
Assert.NotEqual("Windows PE", caption);
|
|
}
|
|
|
|
// The real build version either way.
|
|
Assert.StartsWith($"{Environment.OSVersion.Version.Major}.", device.GetProperty("osVersion").GetString());
|
|
Assert.Equal(Environment.MachineName, device.GetProperty("hostname").GetString());
|
|
}
|
|
|
|
private AgentCredentials Enrolled(string jwt)
|
|
{
|
|
var stored = new AgentCredentials(AgentCredentials.CurrentVersion, ClientId, Guid.NewGuid(), jwt, "SUSEED", null);
|
|
credentials.Save(stored);
|
|
return stored;
|
|
}
|
|
|
|
private void Configure(string serverUrl)
|
|
{
|
|
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, serverUrl);
|
|
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken, "install-token");
|
|
}
|
|
|
|
private AgentConfiguration LoadConfiguration() => new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
|
|
|
|
private EnrollmentService Service(WindowsPhase? phase = null) => new(
|
|
credentials, new RuntimeStateStore(registry), new FixedHardware(),
|
|
new InventoryCollector(new FixedHardware(), phase ?? new WindowsPhase(() => false)),
|
|
NullLogger<EnrollmentService>.Instance);
|
|
|
|
private static int FreePort()
|
|
{
|
|
var probe = new TcpListener(IPAddress.Loopback, 0);
|
|
probe.Start();
|
|
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
|
probe.Stop();
|
|
return port;
|
|
}
|
|
|
|
private sealed class FixedHardware : IHardwareIdentitySource
|
|
{
|
|
public HardwareIdentity Read() => Hardware;
|
|
}
|
|
|
|
private sealed class InMemoryCredentialStore : ICredentialStore
|
|
{
|
|
public AgentCredentials? Current { get; private set; }
|
|
|
|
public AgentCredentials? Load() => Current;
|
|
|
|
public void Save(AgentCredentials credentials) => Current = credentials;
|
|
|
|
public void Delete() => Current = null;
|
|
}
|
|
|
|
/// <summary>Loopback stand-in for the bootstrap endpoint answering with a fixed status/body.</summary>
|
|
private sealed class BootstrapServer : IDisposable
|
|
{
|
|
private readonly HttpListener listener = new();
|
|
|
|
public BootstrapServer(HttpStatusCode status, string? body)
|
|
{
|
|
Url = $"http://127.0.0.1:{FreePort()}";
|
|
listener.Prefixes.Add(Url + "/");
|
|
listener.Start();
|
|
_ = Task.Run(async () =>
|
|
{
|
|
while (listener.IsListening)
|
|
{
|
|
HttpListenerContext context;
|
|
try
|
|
{
|
|
context = await listener.GetContextAsync();
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return;
|
|
}
|
|
|
|
using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))
|
|
{
|
|
LastRequestBody = await reader.ReadToEndAsync();
|
|
}
|
|
|
|
context.Response.StatusCode = (int)status;
|
|
if (body is not null)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes(body);
|
|
context.Response.ContentType = "application/json";
|
|
await context.Response.OutputStream.WriteAsync(bytes);
|
|
}
|
|
|
|
context.Response.Close();
|
|
}
|
|
});
|
|
}
|
|
|
|
public string Url { get; }
|
|
|
|
public string? LastRequestBody { get; private set; }
|
|
|
|
public void Dispose() => listener.Stop();
|
|
}
|
|
}
|