fix protocol+tests: replay protection rework, wire envelope nonce auth,

flaky e2e test deadlines, build imports
This commit is contained in:
2026-02-13 16:37:30 -03:00
parent c94d189d42
commit 6ec1346cfd
22 changed files with 2275 additions and 786 deletions

View File

@@ -86,6 +86,11 @@ pub const SecureConnection = struct {
messages_received_since_rekey: u64 = 0,
/// Rekey interval (0 = disabled)
rekey_interval: u64 = DEFAULT_REKEY_INTERVAL,
/// Per-session SipHash key for wire envelope nonce derivation.
/// Derived from the Noise handshake hash via HKDF after split().
/// Each peer pair gets a unique key — an attacker with the binary
/// cannot forge envelopes for connections they aren't part of.
envelope_key: ?[16]u8 = null,
const Self = @This();
@@ -127,6 +132,7 @@ pub const SecureConnection = struct {
self.transport = hs.split() catch return Error.HandshakeFailed;
self.remote_static_key = hs.rs;
self.handshake_complete = true;
self.deriveEnvelopeKey();
// Zeroize handshake state (ephemeral keys, symmetric state)
secureZeroBytes(std.mem.asBytes(&hs));
@@ -156,6 +162,7 @@ pub const SecureConnection = struct {
self.transport = hs.split() catch return Error.HandshakeFailed;
self.remote_static_key = hs.rs;
self.handshake_complete = true;
self.deriveEnvelopeKey();
// Zeroize handshake state (ephemeral keys, symmetric state)
secureZeroBytes(std.mem.asBytes(&hs));
@@ -300,6 +307,24 @@ pub const SecureConnection = struct {
return null;
}
/// Get the per-session envelope key (null before handshake completes)
pub fn getEnvelopeKey(self: *const Self) ?[16]u8 {
return self.envelope_key;
}
/// Derive per-session envelope SipHash key from the Noise handshake hash.
/// Both peers compute identical keys because they share the same handshake hash.
/// Uses HKDF-SHA256 with a domain-specific info string to avoid key reuse
/// across different protocol layers.
fn deriveEnvelopeKey(self: *Self) void {
const hs_hash = self.getHandshakeHash() orelse return;
const hkdf = std.crypto.kdf.hkdf.HkdfSha256;
const prk = hkdf.extract(&[_]u8{}, &hs_hash);
var key: [16]u8 = undefined;
hkdf.expand(&key, "zig-p2p-v1-envelope-siphash", prk);
self.envelope_key = key;
}
/// Rekey for forward secrecy (both directions)
pub fn rekey(self: *Self) void {
if (self.transport) |*t| {