f0268c899d
The stream time a queued v1 message is judged by comes from the NATS server, which is inside the threat model; once nothing from before the key exchange can still be in the stream, unsealed messages are refused outright. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
14 KiB
C#
310 lines
14 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Agent.Enrollment;
|
|
using Agent.Messaging;
|
|
using Agent.Storage;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using NATS.NKeys;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Infrastructure.Security.Messaging;
|
|
using Xunit;
|
|
|
|
namespace Agent.Tests;
|
|
|
|
/// <summary>
|
|
/// The agent's end of sealed messaging against a server that seals the way the
|
|
/// backend does (the shared envelope code with the server's signing and ECDH keys):
|
|
/// what it takes, what it refuses, what it remembers, and rotations.
|
|
/// </summary>
|
|
public sealed class AgentMessageSecurityTests : IDisposable
|
|
{
|
|
private const string ClientId = "client-1";
|
|
private const string Subject = "agent.client-1.command.screen.open";
|
|
|
|
private readonly string root = Path.Combine(Path.GetTempPath(), "executer-sealing-tests", Guid.NewGuid().ToString("N"));
|
|
private readonly MemoryStore store = new();
|
|
private readonly KeyPair agentNkey = KeyPair.CreatePair(PrefixByte.User);
|
|
private readonly ECDiffieHellman agentEcdh = MessageKeys.Create();
|
|
private readonly Server server = new("k1");
|
|
// The persisted replay store keeps wall-clock time, so the test clock starts at now.
|
|
private readonly ManualTime time = new(DateTimeOffset.UtcNow);
|
|
private readonly JobHistoryStore seen;
|
|
|
|
public AgentMessageSecurityTests()
|
|
{
|
|
Directory.CreateDirectory(root);
|
|
seen = new JobHistoryStore(Path.Combine(root, "jobs.db"));
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
seen.Dispose();
|
|
agentNkey.Dispose();
|
|
agentEcdh.Dispose();
|
|
server.Dispose();
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
try
|
|
{
|
|
Directory.Delete(root, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
}
|
|
}
|
|
|
|
private sealed class ManualTime(DateTimeOffset now) : TimeProvider
|
|
{
|
|
public DateTimeOffset Now { get; set; } = now;
|
|
|
|
public override DateTimeOffset GetUtcNow() => Now;
|
|
}
|
|
|
|
private sealed class MemoryStore : ICredentialStore
|
|
{
|
|
public AgentCredentials? Current { get; set; }
|
|
|
|
public AgentCredentials? Load() => Current;
|
|
|
|
public void Save(AgentCredentials credentials) => Current = credentials;
|
|
|
|
public void Delete() => Current = null;
|
|
}
|
|
|
|
/// <summary>The server's side, as the backend seals: its signing key, its ECDH key, one kid.</summary>
|
|
private sealed class Server(string kid) : IDisposable
|
|
{
|
|
public KeyPair Signing { get; } = KeyPair.CreatePair(PrefixByte.Server);
|
|
public ECDiffieHellman Ecdh { get; } = MessageKeys.Create();
|
|
public string Kid => kid;
|
|
public ServerKeyInfo Info => new(kid, Signing.GetPublicKey(), MessageKeys.PublicKeyOf(Ecdh));
|
|
|
|
public byte[] Seal(string agentPublic, string subject, string type, byte[] plaintext, DateTimeOffset issued, TimeSpan lifetime)
|
|
{
|
|
using var signer = new NkeySigner(Signing.GetSeed());
|
|
return MessageSealing.ToBytes(MessageSealing.Seal(
|
|
kid, type, MessageSecurityNames.ServerSender, subject, issued, issued + lifetime,
|
|
MessageKeys.Agree(Ecdh, agentPublic), MessageDirections.ServerToAgent, plaintext, signer));
|
|
}
|
|
|
|
public byte[]? Open(byte[] data, string agentPublic, string agentNkeyPublic)
|
|
{
|
|
var envelope = MessageSealing.Parse(data);
|
|
return envelope is not null && MessageSealing.VerifySignature(envelope, agentNkeyPublic)
|
|
? MessageSealing.TryDecrypt(envelope, MessageKeys.Agree(Ecdh, agentPublic), MessageDirections.AgentToServer)
|
|
: null;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Signing.Dispose();
|
|
Ecdh.Dispose();
|
|
}
|
|
}
|
|
|
|
private string AgentPublic => MessageKeys.PublicKeyOf(agentEcdh);
|
|
|
|
private AgentMessageSecurity Security(bool sealedAgent = true, DateTimeOffset? sealedSince = null, ServerKeyInfo? previous = null)
|
|
{
|
|
store.Current = new AgentCredentials(
|
|
AgentCredentials.CurrentVersion, ClientId, Guid.NewGuid(), "jwt", agentNkey.GetSeed(), null,
|
|
sealedAgent ? MessageKeys.PrivateKeyOf(agentEcdh) : null,
|
|
sealedAgent ? new ServerMessageKeys(server.Info, previous, sealedSince ?? time.Now - TimeSpan.FromHours(1)) : null);
|
|
var security = new AgentMessageSecurity(store, seen, NullLogger.Instance, time);
|
|
security.Reload();
|
|
return security;
|
|
}
|
|
|
|
private byte[] FromServer(string subject = Subject, string type = MessageTypes.CommandScreenOpen, TimeSpan? lifetime = null, DateTimeOffset? issued = null, Server? by = null)
|
|
=> (by ?? server).Seal(AgentPublic, subject, type, Encoding.UTF8.GetBytes("{\"payload\":1}"), issued ?? time.Now, lifetime ?? MessageSecurityDefaults.LiveLifetime);
|
|
|
|
[Fact]
|
|
public void AnAgentWithoutKeysSendsAndTakesV1()
|
|
{
|
|
var security = Security(sealedAgent: false);
|
|
var v1 = Encoding.UTF8.GetBytes("""{"messageId":"x"}""");
|
|
|
|
Assert.False(security.Sealed);
|
|
Assert.Same(v1, security.Open(Subject, v1, MessageReceipt.Request)!.Payload);
|
|
Assert.Equal(v1, security.Seal("agent.client-1.presence", MessageTypes.AgentPresence, v1));
|
|
Assert.False(security.Report().Sealed);
|
|
}
|
|
|
|
[Fact]
|
|
public void WhatTheAgentSealsTheServerOpensAndAttributesToIt()
|
|
{
|
|
var security = Security();
|
|
var plaintext = Encoding.UTF8.GetBytes("{\"inventory\":true}");
|
|
|
|
var wire = security.Seal("agent.client-1.inventory", MessageTypes.AgentInventory, plaintext);
|
|
|
|
Assert.True(MessageSealing.IsSealed(wire));
|
|
var envelope = MessageSealing.Parse(wire)!;
|
|
Assert.Equal(ClientId, envelope.Sender);
|
|
Assert.Equal("agent.client-1.inventory", envelope.Subject);
|
|
Assert.Equal(server.Kid, envelope.Kid);
|
|
Assert.Equal(plaintext, server.Open(wire, AgentPublic, agentNkey.GetPublicKey()));
|
|
using var other = KeyPair.CreatePair(PrefixByte.User);
|
|
Assert.Null(server.Open(wire, AgentPublic, other.GetPublicKey()));
|
|
Assert.Equal(new InventoryMessageSecurity(true, server.Kid, store.Current!.ServerKeys!.SealedSinceUtc), security.Report());
|
|
}
|
|
|
|
[Fact]
|
|
public void ARequestIsTakenOnceEvenAcrossARestart()
|
|
{
|
|
var wire = FromServer();
|
|
|
|
Assert.NotNull(Security().Open(Subject, wire, MessageReceipt.Request));
|
|
Assert.Null(Security().Open(Subject, wire, MessageReceipt.Request, null, out var refusal));
|
|
Assert.Equal(MessageRefusal.Replay, refusal);
|
|
}
|
|
|
|
[Fact]
|
|
public void ShellFramesAreRememberedInMemoryOnly()
|
|
{
|
|
var subject = "agent.client-1.command.shell.input";
|
|
var wire = FromServer(subject, MessageTypes.CommandShellInput);
|
|
var security = Security();
|
|
|
|
Assert.NotNull(security.Open(subject, wire, MessageReceipt.Stream));
|
|
Assert.Null(security.Open(subject, wire, MessageReceipt.Stream));
|
|
Assert.False(seen.Contains(MessageSealing.Parse(wire)!.MessageId));
|
|
}
|
|
|
|
[Fact]
|
|
public void AQueuedCommandIsRememberedOnlyOnceAcknowledged()
|
|
{
|
|
var subject = "agent.client-1.command.script";
|
|
var wire = FromServer(subject, MessageTypes.CommandScript, MessageSecurityDefaults.DurableCommandLifetime);
|
|
var security = Security();
|
|
|
|
// Redelivered before the ack (the agent stopped mid-way): taken again.
|
|
var first = security.Open(subject, wire, MessageReceipt.Durable)!;
|
|
Assert.NotNull(security.Open(subject, wire, MessageReceipt.Durable));
|
|
|
|
security.Remember(first);
|
|
Assert.Null(security.Open(subject, wire, MessageReceipt.Durable, null, out var refusal));
|
|
Assert.Equal(MessageRefusal.Replay, refusal);
|
|
}
|
|
|
|
[Fact]
|
|
public void AnAgentOfflineForDaysStillTakesItsQueuedCommand()
|
|
{
|
|
var subject = "agent.client-1.command.upgrade";
|
|
var wire = FromServer(subject, MessageTypes.CommandAgentUpgrade, MessageSecurityDefaults.DurableCommandLifetime);
|
|
time.Now += TimeSpan.FromDays(1.5);
|
|
|
|
Assert.NotNull(Security().Open(subject, wire, MessageReceipt.Durable));
|
|
time.Now += TimeSpan.FromDays(1);
|
|
Assert.Null(Security().Open(subject, wire, MessageReceipt.Durable));
|
|
}
|
|
|
|
[Fact]
|
|
public void ALiveRequestMayNotClaimAQueuedCommandsLifetime()
|
|
{
|
|
var wire = FromServer(lifetime: MessageSecurityDefaults.DurableCommandLifetime);
|
|
Assert.Null(Security().Open(Subject, wire, MessageReceipt.Request));
|
|
}
|
|
|
|
[Fact]
|
|
public void ExpiredAndEarlyMessagesAreRefusedBeyondTheSkew()
|
|
{
|
|
var security = Security();
|
|
|
|
Assert.NotNull(security.Open(Subject, FromServer(issued: time.Now - TimeSpan.FromMinutes(6)), MessageReceipt.Request));
|
|
Assert.Null(security.Open(Subject, FromServer(issued: time.Now - TimeSpan.FromMinutes(8)), MessageReceipt.Request));
|
|
Assert.NotNull(security.Open(Subject, FromServer(issued: time.Now + TimeSpan.FromMinutes(4)), MessageReceipt.Request));
|
|
Assert.Null(security.Open(Subject, FromServer(issued: time.Now + TimeSpan.FromMinutes(6)), MessageReceipt.Request));
|
|
|
|
// MessageClockSkew widens it.
|
|
security.ClockSkew = TimeSpan.FromMinutes(10);
|
|
Assert.NotNull(security.Open(Subject, FromServer(issued: time.Now + TimeSpan.FromMinutes(6)), MessageReceipt.Request));
|
|
}
|
|
|
|
[Fact]
|
|
public void AMessageForAnotherSubjectOrFromAnotherServerIsRefused()
|
|
{
|
|
var security = Security();
|
|
using var impostor = new Server(server.Kid);
|
|
|
|
Assert.Null(security.Open("agent.client-1.command.files.request", FromServer(), MessageReceipt.Request));
|
|
Assert.Null(security.Open(Subject, FromServer(by: impostor), MessageReceipt.Request));
|
|
Assert.Null(security.Open(Subject, Encoding.UTF8.GetBytes("""{"v":2,"kid":"k1"}"""), MessageReceipt.Request));
|
|
}
|
|
|
|
[Fact]
|
|
public void ASealedAgentRefusesV1ExceptCommandsQueuedBeforeItsKeyExchange()
|
|
{
|
|
var sealedSince = time.Now - TimeSpan.FromMinutes(10);
|
|
var security = Security(sealedSince: sealedSince);
|
|
var v1 = MessageEnvelope.Create(MessageTypes.CommandScript, new EndpointRef(EndpointKinds.Backend, "backend"), new { }).ToUtf8Bytes();
|
|
|
|
Assert.Null(security.Open(Subject, v1, MessageReceipt.Request));
|
|
Assert.Null(security.Open("agent.client-1.command.script", v1, MessageReceipt.Durable, storedUtc: null));
|
|
Assert.Null(security.Open("agent.client-1.command.script", v1, MessageReceipt.Durable, storedUtc: sealedSince + TimeSpan.FromSeconds(1)));
|
|
Assert.NotNull(security.Open("agent.client-1.command.script", v1, MessageReceipt.Durable, storedUtc: sealedSince - TimeSpan.FromSeconds(1)));
|
|
|
|
// Once nothing from before the exchange can still be queued, the window is closed.
|
|
time.Now = sealedSince + MessageSecurityDefaults.DurableCommandLifetime + TimeSpan.FromMinutes(1);
|
|
Assert.Null(security.Open("agent.client-1.command.script", v1, MessageReceipt.Durable, storedUtc: sealedSince - TimeSpan.FromSeconds(1)));
|
|
}
|
|
|
|
[Fact]
|
|
public void AnUnknownKeyAsksForAKeyExchange()
|
|
{
|
|
var security = Security();
|
|
using var rotated = new Server("k2");
|
|
var asked = 0;
|
|
security.KeysOutdated += () => asked++;
|
|
|
|
Assert.Null(security.Open(Subject, FromServer(by: rotated), MessageReceipt.Durable, null, out var refusal));
|
|
Assert.Equal(MessageRefusal.KeysOutdated, refusal);
|
|
Assert.Equal(1, asked);
|
|
}
|
|
|
|
[Fact]
|
|
public void ARotationSignedWithThePinnedKeyMovesToTheNewKey()
|
|
{
|
|
var security = Security();
|
|
using var next = new Server("k2");
|
|
var subject = "agent.client-1.command.keys";
|
|
var announcement = security.Open(subject, FromServer(subject, MessageTypes.CommandKeyRotation, MessageSecurityDefaults.DurableCommandLifetime), MessageReceipt.Durable)!;
|
|
|
|
Assert.True(security.ApplyRotation(announcement, new ServerKeyRotationPayload(next.Info, time.Now)));
|
|
|
|
Assert.Equal(next.Info, store.Current!.ServerKeys!.Current);
|
|
Assert.Equal(server.Info, store.Current.ServerKeys.Previous);
|
|
// Both are taken now: the old key while it retires, the new one from here on.
|
|
Assert.NotNull(security.Open(Subject, FromServer(by: next), MessageReceipt.Request));
|
|
Assert.NotNull(security.Open(Subject, FromServer(by: server), MessageReceipt.Request));
|
|
// And what the agent sends goes under the new key.
|
|
Assert.Equal("k2", MessageSealing.Parse(security.Seal("agent.client-1.presence", MessageTypes.AgentPresence, [1]))!.Kid);
|
|
}
|
|
|
|
[Fact]
|
|
public void AnUnsealedOrMalformedRotationIsRefused()
|
|
{
|
|
var security = Security();
|
|
using var next = new Server("k2");
|
|
|
|
Assert.False(security.ApplyRotation(new OpenedMessage([], Sealed: false), new ServerKeyRotationPayload(next.Info, time.Now)));
|
|
var opened = new OpenedMessage([], Sealed: true, Kid: server.Kid);
|
|
Assert.False(security.ApplyRotation(opened, new ServerKeyRotationPayload(next.Info with { SigningPublic = "bogus" }, time.Now)));
|
|
Assert.False(security.ApplyRotation(new OpenedMessage([], Sealed: true, Kid: "unknown"), new ServerKeyRotationPayload(next.Info, time.Now)));
|
|
Assert.Equal(server.Info, store.Current!.ServerKeys!.Current);
|
|
}
|
|
|
|
[Fact]
|
|
public void AStreamKeyMatchesTheServersForTheSameStream()
|
|
{
|
|
var security = Security();
|
|
var streamId = Guid.NewGuid();
|
|
var agentCipher = security.StreamCipher(server.Kid, streamId, StreamPurposes.Screen)!;
|
|
var serverCipher = StreamCipher.ForServer(MessageKeys.Agree(server.Ecdh, AgentPublic), streamId, StreamPurposes.Screen);
|
|
|
|
Assert.Equal(new byte[] { 7, 7 }, agentCipher.Open(serverCipher.Seal([7, 7])));
|
|
Assert.Equal(new byte[] { 8 }, serverCipher.Open(agentCipher.Seal([8])));
|
|
Assert.Null(security.StreamCipher(null, streamId, StreamPurposes.Screen));
|
|
Assert.Null(security.StreamCipher("unknown", streamId, StreamPurposes.Screen));
|
|
}
|
|
}
|