Files
Alphaeus Mote 2df42b09ed feat(security): seal, sign and replay-protect every server/agent/browser message
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>
2026-11-06 18:10:22 -05:00

276 lines
13 KiB
C#

using System.Security.Cryptography;
using System.Text;
using NATS.NKeys;
using Shared.Contracts.Messages;
using Shared.Infrastructure.Security.Messaging;
using Xunit;
namespace Shared.Tests;
/// <summary>Envelope v2: sealing, signatures, freshness and the key material, as both sides use them.</summary>
public class MessageSealingTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 6, 12, 0, 0, TimeSpan.Zero);
/// <summary>Two ECDH keys (server, agent), their shared secret both ways, and the agent's NKey.</summary>
private sealed class Parties : IDisposable
{
public ECDiffieHellman Server { get; } = MessageKeys.Create();
public ECDiffieHellman Agent { get; } = MessageKeys.Create();
public KeyPair AgentNkey { get; } = KeyPair.CreatePair(PrefixByte.User);
public NkeySigner Signer { get; }
public Parties() => Signer = new NkeySigner(AgentNkey.GetSeed());
public byte[] AgentSecret => MessageKeys.Agree(Agent, MessageKeys.PublicKeyOf(Server));
public byte[] ServerSecret => MessageKeys.Agree(Server, MessageKeys.PublicKeyOf(Agent));
public SealedEnvelope Seal(byte[] plaintext, string subject = "agent.c1.presence", TimeSpan? lifetime = null)
=> MessageSealing.Seal(
"k1", MessageTypes.AgentPresence, "c1", subject, Now, Now + (lifetime ?? TimeSpan.FromMinutes(2)),
AgentSecret, MessageDirections.AgentToServer, plaintext, Signer);
public void Dispose()
{
Server.Dispose();
Agent.Dispose();
AgentNkey.Dispose();
Signer.Dispose();
}
}
[Fact]
public void BothSidesAgreeOnTheSecret()
{
using var parties = new Parties();
Assert.Equal(parties.AgentSecret, parties.ServerSecret);
Assert.Equal(32, parties.AgentSecret.Length);
}
[Fact]
public void ARoundTripOpensAndVerifies()
{
using var parties = new Parties();
var plaintext = Encoding.UTF8.GetBytes("""{"messageType":"agent.presence","payload":{"secret":"s3cr3t"}}""");
var envelope = parties.Seal(plaintext);
var wire = MessageSealing.ToBytes(envelope);
Assert.True(MessageSealing.IsSealed(wire));
Assert.DoesNotContain("s3cr3t", Encoding.UTF8.GetString(wire), StringComparison.Ordinal);
var parsed = MessageSealing.Parse(wire);
Assert.NotNull(parsed);
Assert.True(MessageSealing.VerifySignature(parsed, parties.AgentNkey.GetPublicKey()));
Assert.Equal(plaintext, MessageSealing.TryDecrypt(parsed, parties.ServerSecret, MessageDirections.AgentToServer));
}
[Fact]
public void TamperingWithAnyCiphertextOrNonceByteFails()
{
using var parties = new Parties();
var envelope = parties.Seal(Encoding.UTF8.GetBytes("a payload long enough to flip many bytes"));
for (var i = 0; i < envelope.Ciphertext.Length; i++)
{
var bytes = (byte[])envelope.Ciphertext.Clone();
bytes[i] ^= 0x01;
var tampered = envelope with { Ciphertext = bytes };
Assert.Null(MessageSealing.TryDecrypt(tampered, parties.ServerSecret, MessageDirections.AgentToServer));
Assert.False(MessageSealing.VerifySignature(tampered, parties.AgentNkey.GetPublicKey()));
}
for (var i = 0; i < envelope.Nonce.Length; i++)
{
var nonce = (byte[])envelope.Nonce.Clone();
nonce[i] ^= 0x80;
var tampered = envelope with { Nonce = nonce };
Assert.Null(MessageSealing.TryDecrypt(tampered, parties.ServerSecret, MessageDirections.AgentToServer));
Assert.False(MessageSealing.VerifySignature(tampered, parties.AgentNkey.GetPublicKey()));
}
}
[Fact]
public void TamperingWithAnyWireByteNeverOpens()
{
using var parties = new Parties();
var wire = MessageSealing.ToBytes(parties.Seal(Encoding.UTF8.GetBytes("payload")));
for (var i = 0; i < wire.Length; i++)
{
var bytes = (byte[])wire.Clone();
bytes[i] ^= 0x04;
var parsed = MessageSealing.Parse(bytes);
if (parsed is null)
{
continue;
}
// Whatever still parses must fail the signature or the decryption, unless the flip was invisible (JSON whitespace or escape).
var opened = MessageSealing.VerifySignature(parsed, parties.AgentNkey.GetPublicKey())
? MessageSealing.TryDecrypt(parsed, parties.ServerSecret, MessageDirections.AgentToServer)
: null;
if (opened is not null)
{
Assert.Equal(MessageSealing.SignatureInput(MessageSealing.Parse(wire)!), MessageSealing.SignatureInput(parsed));
}
}
}
public static TheoryData<string> HeaderFields => ["kid", "type", "messageId", "issued", "expires", "sender", "subject"];
[Theory]
[MemberData(nameof(HeaderFields))]
public void ChangingAnyHeaderFieldFailsBothTheAadAndTheSignature(string field)
{
using var parties = new Parties();
var envelope = parties.Seal(Encoding.UTF8.GetBytes("payload"));
var changed = field switch
{
"kid" => envelope with { Kid = "k2" },
"type" => envelope with { Type = MessageTypes.CommandScript },
"messageId" => envelope with { MessageId = Guid.NewGuid() },
"issued" => envelope with { IssuedUtc = envelope.IssuedUtc.AddMilliseconds(1) },
"expires" => envelope with { ExpiresUtc = envelope.ExpiresUtc.AddDays(1) },
"sender" => envelope with { Sender = "c2" },
_ => envelope with { Subject = "agent.c1.inventory" },
};
Assert.False(MessageSealing.VerifySignature(changed, parties.AgentNkey.GetPublicKey()));
if (field != "messageId")
{
// The message id is also the key's salt; every other field is associated data.
Assert.NotEqual(MessageSealing.Header(envelope), MessageSealing.Header(changed));
}
Assert.Null(MessageSealing.TryDecrypt(changed, parties.ServerSecret, MessageDirections.AgentToServer));
}
[Fact]
public void TheWrongKeyOrDirectionDoesNotOpen()
{
using var parties = new Parties();
using var stranger = MessageKeys.Create();
var envelope = parties.Seal(Encoding.UTF8.GetBytes("payload"));
var strangerSecret = MessageKeys.Agree(stranger, MessageKeys.PublicKeyOf(parties.Agent));
Assert.Null(MessageSealing.TryDecrypt(envelope, strangerSecret, MessageDirections.AgentToServer));
Assert.Null(MessageSealing.TryDecrypt(envelope, parties.ServerSecret, MessageDirections.ServerToAgent));
Assert.Null(MessageSealing.TryDecrypt(envelope, RandomNumberGenerator.GetBytes(32), MessageDirections.AgentToServer));
}
[Fact]
public void AnotherSignerOrATamperedSignatureDoesNotVerify()
{
using var parties = new Parties();
using var other = KeyPair.CreatePair(PrefixByte.User);
var envelope = parties.Seal(Encoding.UTF8.GetBytes("payload"));
Assert.False(MessageSealing.VerifySignature(envelope, other.GetPublicKey()));
var signature = (byte[])envelope.Signature!.Clone();
signature[10] ^= 1;
Assert.False(MessageSealing.VerifySignature(envelope with { Signature = signature }, parties.AgentNkey.GetPublicKey()));
Assert.False(MessageSealing.VerifySignature(envelope with { Signature = null }, parties.AgentNkey.GetPublicKey()));
Assert.False(MessageSealing.VerifySignature(envelope, "not-a-key"));
}
[Fact]
public void EveryMessageGetsItsOwnNonceAndKey()
{
using var parties = new Parties();
var a = parties.Seal(Encoding.UTF8.GetBytes("same"));
var b = parties.Seal(Encoding.UTF8.GetBytes("same"));
Assert.NotEqual(a.MessageId, b.MessageId);
Assert.NotEqual(a.Nonce, b.Nonce);
Assert.NotEqual(a.Ciphertext, b.Ciphertext);
Assert.NotEqual(
MessageSealing.DeriveKey(parties.AgentSecret, a.MessageId, MessageDirections.AgentToServer),
MessageSealing.DeriveKey(parties.AgentSecret, b.MessageId, MessageDirections.AgentToServer));
}
[Fact]
public void FreshnessAllowsTheSkewAndNoMore()
{
using var parties = new Parties();
var skew = TimeSpan.FromMinutes(5);
var live = TimeSpan.FromMinutes(2);
var envelope = parties.Seal([1], lifetime: live);
Assert.Null(MessageSealing.CheckFreshness(envelope, Now, skew, live));
// A receiver whose clock is behind: issued in its future, within the skew.
Assert.Null(MessageSealing.CheckFreshness(envelope, Now - TimeSpan.FromMinutes(4), skew, live));
Assert.Contains("future", MessageSealing.CheckFreshness(envelope, Now - TimeSpan.FromMinutes(6), skew, live));
// Expired, but within the skew; then beyond it.
Assert.Null(MessageSealing.CheckFreshness(envelope, Now + live + TimeSpan.FromMinutes(4), skew, live));
Assert.Contains("expired", MessageSealing.CheckFreshness(envelope, Now + live + TimeSpan.FromMinutes(6), skew, live));
// A sender may not claim more life than the kind of message has.
Assert.Contains("lifetime", MessageSealing.CheckFreshness(parties.Seal([1], lifetime: TimeSpan.FromHours(1)), Now, skew, live));
Assert.Contains("before", MessageSealing.CheckFreshness(envelope with { ExpiresUtc = Now.AddSeconds(-1) }, Now, skew, live));
}
[Fact]
public void AQueuedCommandStaysFreshForDays()
{
using var parties = new Parties();
var envelope = parties.Seal([1], lifetime: MessageSecurityDefaults.DurableCommandLifetime);
Assert.Null(MessageSealing.CheckFreshness(envelope, Now + TimeSpan.FromDays(1.9), MessageSecurityDefaults.ClockSkew, MessageSecurityDefaults.MaxLifetime));
Assert.NotNull(MessageSealing.CheckFreshness(envelope, Now + TimeSpan.FromDays(2.1), MessageSecurityDefaults.ClockSkew, MessageSecurityDefaults.MaxLifetime));
}
[Fact]
public void V1AndGarbageAreNotSealed()
{
var v1 = MessageEnvelope.Create(MessageTypes.AgentPresence, new EndpointRef(EndpointKinds.Agent, "c1"), new { a = 1 }).ToUtf8Bytes();
Assert.False(MessageSealing.IsSealed(v1));
Assert.Null(MessageSealing.Parse(v1));
Assert.Null(MessageSealing.Parse("""{"v":2,"kid":"k"}"""u8));
Assert.Null(MessageSealing.Parse("""{"v":2,"kid":"k","type":"t","sender":"s","nonce":"AAAA","ciphertext":"AAAA"}"""u8));
Assert.Null(MessageSealing.Parse("""{"v":2, broken"""u8));
Assert.Null(MessageSealing.Parse([0xE7, 1, 2, 3]));
}
[Fact]
public void OnlyP256PublicKeysAreAccepted()
{
using var p256 = MessageKeys.Create();
using var p384 = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP384);
Assert.True(MessageKeys.IsValidPublicKey(MessageKeys.PublicKeyOf(p256)));
Assert.False(MessageKeys.IsValidPublicKey(Convert.ToBase64String(p384.ExportSubjectPublicKeyInfo())));
Assert.False(MessageKeys.IsValidPublicKey("not base64!"));
Assert.False(MessageKeys.IsValidPublicKey(Convert.ToBase64String(new byte[91])));
Assert.False(MessageKeys.IsValidPublicKey(null));
Assert.Throws<CryptographicException>(() => MessageKeys.Agree(p256, Convert.ToBase64String(p384.ExportSubjectPublicKeyInfo())));
}
[Fact]
public void APrivateKeyRoundTripsThroughItsStoredForm()
{
using var key = MessageKeys.Create();
using var restored = MessageKeys.FromPrivateKey(MessageKeys.PrivateKeyOf(key));
Assert.Equal(MessageKeys.PublicKeyOf(key), MessageKeys.PublicKeyOf(restored));
}
/// <summary>
/// A message the console's WebCrypto code (src/WebUI/src/messaging/sealing.ts) sealed under
/// Node's WebCrypto: the same envelope, header, HKDF and AES-GCM, so the server opens it.
/// </summary>
[Fact]
public void TheBrowsersSealingOpensHere()
{
const string serverPkcs8 = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg6PJRd+afVlQ9aT3HOdCyB7cKRwQqPym36hF/DaNg1UahRANCAAQpVY1OLq3yAg5hUnax+OWaGX7DVSM/zGWYudoJtpa9FMOxaoaC+rNzsmG+WlcBtLZSuy7fWeD7OtewoQvu9zXp";
const string browserSpki = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEE0DESqWpARmyc7xebKInvWHOB36kfYRsd9TaJgyIuRK41GKsT5PbIshYGfyzW80z8x573Mtv4QLAd9Nboy4noQ==";
const string envelope = """{"v":2,"kid":"bkid","type":"shell.input","messageId":"44b94e84-22ee-4880-a55f-7ed866fdaac3","issuedUtc":"2026-11-06T22:32:46.393Z","expiresUtc":"2026-11-06T22:34:46.393Z","sender":"sess1","subject":"browser.sess1.shell.00000000-0000-0000-0000-000000000001.input","nonce":"0nV8dBN5OhOwvvtw","ciphertext":"7jkYb176PwQM6S7ctlzV50E/i6+MBim7ndkFhhpdFlIJ5uNPTs0="}""";
using var server = MessageKeys.FromPrivateKey(serverPkcs8);
var secret = MessageKeys.Agree(server, browserSpki);
var parsed = MessageSealing.Parse(Encoding.UTF8.GetBytes(envelope));
Assert.NotNull(parsed);
Assert.Equal("hello from the browser", Encoding.UTF8.GetString(MessageSealing.TryDecrypt(parsed, secret, MessageDirections.BrowserToServer)!));
Assert.Null(MessageSealing.TryDecrypt(parsed with { Subject = "browser.sess1.event" }, secret, MessageDirections.BrowserToServer));
Assert.Null(MessageSealing.TryDecrypt(parsed, secret, MessageDirections.ServerToBrowser));
}
}