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

@@ -463,7 +463,10 @@ pub const DhtCoordinator = struct {
pending_responses: std.AutoHashMap(u64, PendingResponse),
/// Network sender for propagation (set by P2P layer)
network_sender: NetworkSender = .{},
/// Next request ID (atomic for thread safety)
/// Next request ID (atomic for thread safety).
/// Starts at 1 on all nodes — this is safe because replay protection uses per-message
/// random wire_nonce (not request_id) for global deduplication. request_id is only used
/// for correlating request/response pairs within a single node.
next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1),
/// Mutex for thread safety
mutex: std.Thread.Mutex = .{},
@@ -504,13 +507,7 @@ pub const DhtCoordinator = struct {
// Generate Ed25519 identity keypair for signing
const identity_keypair = Ed25519.KeyPair.generate();
// SECURITY FIX: Initialize request_id with random value to prevent nonce collisions
// When multiple nodes start simultaneously, they would all start with request_id=1
// causing the replay protection system to detect false positives (DuplicateNonce errors)
var random_start: u64 = undefined;
std.crypto.random.bytes(std.mem.asBytes(&random_start));
var dht = DhtCoordinator{
return DhtCoordinator{
.allocator = allocator,
.routing_table = routing_table,
.local_id = local_id,
@@ -522,8 +519,6 @@ pub const DhtCoordinator = struct {
.peer_rate_limits = std.AutoHashMap(NodeId, PeerRateLimit).init(allocator),
.discovered_peers = std.AutoHashMap(NodeId, DiscoveredPeer).init(allocator),
};
dht.next_request_id.store(random_start, .monotonic);
return dht;
}
/// Initialize with custom TOFU callback for peer verification (recommended for production)

View File

@@ -207,6 +207,14 @@ pub const PeerConnection = struct {
return null;
}
/// Get per-session envelope key from Noise handshake (null when unencrypted)
pub fn getEnvelopeKey(self: *const PeerConnection) ?[16]u8 {
if (self.secure) |sec| {
return sec.getEnvelopeKey();
}
return null;
}
/// Get remaining data to send (if any)
pub fn getPendingRemaining(self: *const PeerConnection) ?[]const u8 {
if (self.pending_send) |*ps| {
@@ -643,8 +651,18 @@ pub const NetworkManager = struct {
if (peer_conn.secure) |secure| {
defer self.releaseSocketLock();
// SecureConnection.send handles encryption and length prefixing
_ = secure.send(data) catch |err| {
// Prepend 4-byte big-endian inner length header to plaintext.
// The receive side strips this after decryption (line ~1184).
// This matches the unencrypted framing format inside the ciphertext.
var inner_msg = self.allocator.alloc(u8, 4 + data.len) catch {
return Error.OutOfMemory;
};
defer self.allocator.free(inner_msg);
std.mem.writeInt(u32, inner_msg[0..4], @intCast(data.len), .big);
@memcpy(inner_msg[4..], data);
// SecureConnection.send handles encryption and outer length prefixing
_ = secure.send(inner_msg) catch |err| {
self.stats.recordSendError();
return switch (err) {
secure_connection.Error.HandshakeTimeout,

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| {

View File

@@ -59,6 +59,7 @@ pub const stats = @import("p2p/stats.zig");
pub const circuit_breaker = @import("p2p/circuit_breaker.zig");
pub const p2p_impl = @import("p2p/p2p.zig");
pub const dht = @import("p2p/dht.zig");
pub const messaging = @import("p2p/messaging.zig");
// Re-export main types
pub const P2P = p2p_impl.P2P;

View File

@@ -180,8 +180,11 @@ pub const NetworkConfig = struct {
turn_fallback_timeout_ms: u32 = 5000,
/// TURN allocation refresh interval (milliseconds)
turn_refresh_interval_ms: u32 = 300000, // 5 minutes
/// Enable Noise protocol encryption for all connections
enable_noise_encryption: bool = false,
/// Enable Noise protocol encryption for all connections.
/// SECURITY: Must be true for production. When false, transport is unencrypted
/// and unauthenticated — peer IDs are random bytes, replay protection is passive
/// only, and any active attacker can forge or modify messages.
enable_noise_encryption: bool = true,
/// Optional static private key for Noise protocol (32 bytes)
/// If null, a random keypair will be generated on init
noise_static_key: ?[32]u8 = null,

View File

@@ -27,6 +27,13 @@ const MAX_DHT_NODES_PER_RESPONSE: u32 = 20;
/// Maximum size of a DHT value in bytes (1 MB)
const MAX_DHT_VALUE_SIZE: u32 = 1024 * 1024;
/// Generate a cryptographically random wire nonce for replay detection
fn generateWireNonce() u64 {
var bytes: [8]u8 = undefined;
std.crypto.random.bytes(&bytes);
return std.mem.readInt(u64, &bytes, .little);
}
// =========================================================================
// DHT (Distributed Hash Table) API
// =========================================================================
@@ -200,6 +207,8 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.sender_id = msg.sender_id,
.target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};
@@ -221,6 +230,8 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.sender_id = msg.sender_id,
.target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};
@@ -240,6 +251,8 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.sender_id = msg.sender_id,
.target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};
@@ -270,43 +283,47 @@ pub const DhtMsgType = enum(u8) {
};
/// Compute the serialized size of a DHT message (for heap allocation when stack buffer is too small)
/// Wire format: [type:1][wire_nonce:8][wire_timestamp:8][request_id:8][...fields...]
fn dhtMessageSize(msg: protocol.message.Message) ?usize {
const node_size = 32 + 46 + 1;
// All messages have: type(1) + wire_nonce(8) + wire_timestamp(8) + request_id(8) = 25 base bytes
return switch (msg) {
.dht_find_node => |m| 1 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_store => |m| 1 + 8 + 32 + 32 + 4 + 4 + m.value.len + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_find_value => |m| 1 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_find_node_response => |m| 1 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18)),
.dht_store_response => |m| 1 + 8 + 1 + 1 + @as(usize, @min(m.observed_addr_len, 18)),
.dht_find_node => |m| 1 + 8 + 8 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_store => |m| 1 + 8 + 8 + 8 + 32 + 32 + 4 + 4 + m.value.len + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_find_value => |m| 1 + 8 + 8 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_find_node_response => |m| 1 + 8 + 8 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18)),
.dht_store_response => |m| 1 + 8 + 8 + 8 + 1 + 1 + @as(usize, @min(m.observed_addr_len, 18)),
.dht_find_value_response => |m| blk: {
const value_len = if (m.value) |v| v.len else 0;
break :blk 1 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18));
break :blk 1 + 8 + 8 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18));
},
else => null,
};
}
/// Serialize a DHT message to simple binary format
/// Format: [1 byte type][8 bytes request_id][32 bytes sender_id][payload...]
/// Format: [1 byte type][8 bytes wire_nonce LE][8 bytes wire_timestamp LE][8 bytes request_id BE][payload...]
/// Public for testing IP Reflection variable-length encoding
pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
var offset: usize = 0;
switch (msg) {
.dht_find_node => |m| {
// Format: [type][request_id][sender_id][target_id][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: include target's observed address in request
// Format: [type][wire_nonce][wire_timestamp][request_id][sender_id][target_id][target_observed_addr_len][target_observed_addr:len]
const addr_len: usize = @min(m.target_observed_addr_len, 18);
if (buffer.len < 1 + 8 + 32 + 32 + 1 + addr_len) return null;
if (buffer.len < 1 + 8 + 8 + 8 + 32 + 32 + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_node);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.wire_nonce, .little);
offset += 8;
std.mem.writeInt(i64, buffer[offset..][0..8], m.wire_timestamp, .little);
offset += 8;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
@memcpy(buffer[offset..][0..32], &m.sender_id);
offset += 32;
@memcpy(buffer[offset..][0..32], &m.target_id);
offset += 32;
// Bidirectional IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.target_observed_addr_len;
offset += 1;
if (addr_len > 0) {
@@ -316,13 +333,16 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
return offset;
},
.dht_store => |m| {
// Format: [type][request_id][sender_id][key][ttl][value_len][value][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: include target's observed address in request
// Format: [type][wire_nonce][wire_timestamp][request_id][sender_id][key][ttl][value_len][value][target_observed_addr_len][target_observed_addr:len]
const value_len = m.value.len;
const addr_len: usize = @min(m.target_observed_addr_len, 18);
if (buffer.len < 1 + 8 + 32 + 32 + 4 + 4 + value_len + 1 + addr_len) return null;
if (buffer.len < 1 + 8 + 8 + 8 + 32 + 32 + 4 + 4 + value_len + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.store);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.wire_nonce, .little);
offset += 8;
std.mem.writeInt(i64, buffer[offset..][0..8], m.wire_timestamp, .little);
offset += 8;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
@memcpy(buffer[offset..][0..32], &m.sender_id);
@@ -335,7 +355,6 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
offset += 4;
@memcpy(buffer[offset..][0..value_len], m.value);
offset += value_len;
// Bidirectional IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.target_observed_addr_len;
offset += 1;
if (addr_len > 0) {
@@ -345,19 +364,21 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
return offset;
},
.dht_find_value => |m| {
// Format: [type][request_id][sender_id][key][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: include target's observed address in request
// Format: [type][wire_nonce][wire_timestamp][request_id][sender_id][key][target_observed_addr_len][target_observed_addr:len]
const addr_len: usize = @min(m.target_observed_addr_len, 18);
if (buffer.len < 1 + 8 + 32 + 32 + 1 + addr_len) return null;
if (buffer.len < 1 + 8 + 8 + 8 + 32 + 32 + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_value);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.wire_nonce, .little);
offset += 8;
std.mem.writeInt(i64, buffer[offset..][0..8], m.wire_timestamp, .little);
offset += 8;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
@memcpy(buffer[offset..][0..32], &m.sender_id);
offset += 32;
@memcpy(buffer[offset..][0..32], &m.key);
offset += 32;
// Bidirectional IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.target_observed_addr_len;
offset += 1;
if (addr_len > 0) {
@@ -367,14 +388,17 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
return offset;
},
.dht_find_node_response => |m| {
// Format: [type][request_id][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes (saves 12 bytes for IPv4)
const node_size = 32 + 46 + 1; // node_id + address + address_len
// Format: [type][wire_nonce][wire_timestamp][request_id][node_count][nodes...][observed_addr_len][observed_addr:len]
const node_size = 32 + 46 + 1;
const addr_len: usize = @min(m.observed_addr_len, 18);
const required = 1 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + addr_len;
const required = 1 + 8 + 8 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + addr_len;
if (buffer.len < required) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_node_response);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.wire_nonce, .little);
offset += 8;
std.mem.writeInt(i64, buffer[offset..][0..8], m.wire_timestamp, .little);
offset += 8;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
std.mem.writeInt(u32, buffer[offset..][0..4], @intCast(m.closest_nodes.len), .big);
@@ -387,7 +411,6 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
buffer[offset] = node.address_len;
offset += 1;
}
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@@ -397,17 +420,19 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
return offset;
},
.dht_store_response => |m| {
// Format: [type][request_id][success][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes (saves 12 bytes for IPv4)
// Format: [type][wire_nonce][wire_timestamp][request_id][success][observed_addr_len][observed_addr:len]
const addr_len: usize = @min(m.observed_addr_len, 18);
if (buffer.len < 1 + 8 + 1 + 1 + addr_len) return null;
if (buffer.len < 1 + 8 + 8 + 8 + 1 + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.store_response);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.wire_nonce, .little);
offset += 8;
std.mem.writeInt(i64, buffer[offset..][0..8], m.wire_timestamp, .little);
offset += 8;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
buffer[offset] = if (m.success) 1 else 0;
offset += 1;
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@@ -417,15 +442,18 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
return offset;
},
.dht_find_value_response => |m| {
// Format: [type][request_id][found][value_len][value][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes (saves 12 bytes for IPv4)
// Format: [type][wire_nonce][wire_timestamp][request_id][found][value_len][value][node_count][nodes...][observed_addr_len][observed_addr:len]
const node_size = 32 + 46 + 1;
const value_len = if (m.value) |v| v.len else 0;
const addr_len: usize = @min(m.observed_addr_len, 18);
const required = 1 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + addr_len;
const required = 1 + 8 + 8 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + addr_len;
if (buffer.len < required) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_value_response);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.wire_nonce, .little);
offset += 8;
std.mem.writeInt(i64, buffer[offset..][0..8], m.wire_timestamp, .little);
offset += 8;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
buffer[offset] = if (m.found) 1 else 0;
@@ -446,7 +474,6 @@ pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
buffer[offset] = node.address_len;
offset += 1;
}
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@@ -467,18 +494,23 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
const msg_type = std.meta.intToEnum(DhtMsgType, data[0]) catch return null;
var offset: usize = 1;
// All message types start with wire_nonce(8 LE) + wire_timestamp(8 LE) after the type byte
if (data.len < 1 + 8 + 8) return null;
const wire_nonce = std.mem.readInt(u64, data[offset..][0..8], .little);
offset += 8;
const wire_timestamp = std.mem.readInt(i64, data[offset..][0..8], .little);
offset += 8;
switch (msg_type) {
.find_node => {
// Format: [type][request_id][sender_id][target_id][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: read target's observed address from request
if (data.len < 1 + 8 + 32 + 32 + 1) return null;
// Format: [type][wire_nonce][wire_timestamp][request_id][sender_id][target_id][target_observed_addr_len][target_observed_addr:len]
if (data.len < 1 + 8 + 8 + 8 + 32 + 32 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const sender_id = data[offset..][0..32].*;
offset += 32;
const target_id = data[offset..][0..32].*;
offset += 32;
// Read target observed address (may be empty for backward compatibility)
var target_observed_addr: [18]u8 = [_]u8{0} ** 18;
var target_observed_addr_len: u8 = 0;
if (offset < data.len) {
@@ -497,13 +529,14 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.target_id = target_id,
.target_observed_addr = target_observed_addr,
.target_observed_addr_len = target_observed_addr_len,
.wire_nonce = wire_nonce,
.wire_timestamp = wire_timestamp,
},
};
},
.store => {
// Format: [type][request_id][sender_id][key][ttl][value_len][value][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: read target's observed address from request
if (data.len < 1 + 8 + 32 + 32 + 4 + 4) return null;
// Format: [type][wire_nonce][wire_timestamp][request_id][sender_id][key][ttl][value_len][value][target_observed_addr_len][target_observed_addr:len]
if (data.len < 1 + 8 + 8 + 8 + 32 + 32 + 4 + 4) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const sender_id = data[offset..][0..32].*;
@@ -517,10 +550,8 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
// SECURITY: Reject excessive value sizes to prevent DoS
if (value_len > MAX_DHT_VALUE_SIZE) return null;
if (data.len < offset + value_len) return null;
// Allocate and copy value
const value = allocator.dupe(u8, data[offset..][0..value_len]) catch return null;
offset += value_len;
// Read target observed address (may be empty for backward compatibility)
var target_observed_addr: [18]u8 = [_]u8{0} ** 18;
var target_observed_addr_len: u8 = 0;
if (offset < data.len) {
@@ -541,20 +572,20 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.value = value,
.target_observed_addr = target_observed_addr,
.target_observed_addr_len = target_observed_addr_len,
.wire_nonce = wire_nonce,
.wire_timestamp = wire_timestamp,
},
};
},
.find_value => {
// Format: [type][request_id][sender_id][key][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: read target's observed address from request
if (data.len < 1 + 8 + 32 + 32 + 1) return null;
// Format: [type][wire_nonce][wire_timestamp][request_id][sender_id][key][target_observed_addr_len][target_observed_addr:len]
if (data.len < 1 + 8 + 8 + 8 + 32 + 32 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const sender_id = data[offset..][0..32].*;
offset += 32;
const key = data[offset..][0..32].*;
offset += 32;
// Read target observed address (may be empty for backward compatibility)
var target_observed_addr: [18]u8 = [_]u8{0} ** 18;
var target_observed_addr_len: u8 = 0;
if (offset < data.len) {
@@ -573,13 +604,14 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.key = key,
.target_observed_addr = target_observed_addr,
.target_observed_addr_len = target_observed_addr_len,
.wire_nonce = wire_nonce,
.wire_timestamp = wire_timestamp,
},
};
},
.find_node_response => {
// Format: [type][request_id][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes
if (data.len < 1 + 8 + 4 + 1) return null;
// Format: [type][wire_nonce][wire_timestamp][request_id][node_count][nodes...][observed_addr_len][observed_addr:len]
if (data.len < 1 + 8 + 8 + 8 + 4 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const node_count = std.mem.readInt(u32, data[offset..][0..4], .big);
@@ -590,7 +622,6 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
// SECURITY: Use checked multiplication to prevent integer overflow
const total_node_bytes = std.math.mul(usize, node_count, node_size) catch return null;
if (data.len < offset + total_node_bytes + 1) return null;
// Allocate nodes array
const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null;
for (0..node_count) |i| {
nodes[i] = .{
@@ -600,7 +631,6 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
};
offset += node_size;
}
// IP Reflection: variable-length encoding (len first, then data)
const observed_addr_len = data[offset];
offset += 1;
var observed_addr: [18]u8 = [_]u8{0} ** 18;
@@ -615,18 +645,18 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.closest_nodes = nodes,
.observed_addr = observed_addr,
.observed_addr_len = observed_addr_len,
.wire_nonce = wire_nonce,
.wire_timestamp = wire_timestamp,
},
};
},
.store_response => {
// Format: [type][request_id][success][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes
if (data.len < 1 + 8 + 1 + 1) return null;
// Format: [type][wire_nonce][wire_timestamp][request_id][success][observed_addr_len][observed_addr:len]
if (data.len < 1 + 8 + 8 + 8 + 1 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const success = data[offset] != 0;
offset += 1;
// IP Reflection: variable-length encoding (len first, then data)
const observed_addr_len = data[offset];
offset += 1;
var observed_addr: [18]u8 = [_]u8{0} ** 18;
@@ -641,13 +671,14 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.success = success,
.observed_addr = observed_addr,
.observed_addr_len = observed_addr_len,
.wire_nonce = wire_nonce,
.wire_timestamp = wire_timestamp,
},
};
},
.find_value_response => {
// Format: [type][request_id][found][value_len][value][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes
if (data.len < 1 + 8 + 1 + 4 + 4 + 1) return null;
// Format: [type][wire_nonce][wire_timestamp][request_id][found][value_len][value][node_count][nodes...][observed_addr_len][observed_addr:len]
if (data.len < 1 + 8 + 8 + 8 + 1 + 4 + 4 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const found = data[offset] != 0;
@@ -710,6 +741,8 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.closest_nodes = nodes,
.observed_addr = observed_addr,
.observed_addr_len = observed_addr_len,
.wire_nonce = wire_nonce,
.wire_timestamp = wire_timestamp,
},
};
},

View File

@@ -90,6 +90,13 @@ pub fn startImpl(p2p: *P2P) Error!void {
p2p.state_mutex.unlock();
}
// SECURITY: Warn when Noise encryption is disabled
if (!p2p.config.network.enable_noise_encryption) {
std.log.warn("SECURITY: Noise encryption is DISABLED. Transport is unencrypted and " ++
"unauthenticated. Peer identities are NOT verified. Wire envelope replay protection " ++
"is passive only (no payload binding). Do NOT use this configuration in production.", .{});
}
// Allocate and initialize network components
const peer_id = PeerId.init();
p2p.topology = p2p.allocator.create(NetworkTopology) catch return Error.SystemError;

View File

@@ -34,6 +34,62 @@ const file_ops = @import("file_ops.zig");
// Message Sending
// ============================================================================
/// Size of the wire envelope prepended to non-DHT, non-file-transfer messages:
/// 8 bytes random salt (LE) + 8 bytes sender timestamp (LE)
///
/// Wire format: [app_id:1][salt:8 LE][timestamp:8 LE][payload:N]
///
/// ## Security model
///
/// **Noise ON (production)**: The entire message is inside AEAD ciphertext, so
/// transport-level authentication prevents any modification or replay. The
/// envelope provides defense-in-depth: a per-session SipHash key derived from
/// the Noise handshake hash binds (salt || timestamp || app_id || payload) into
/// a replay nonce. Even if a Noise implementation bug allows replay, this
/// independent layer catches it. The per-session key means an attacker who
/// compromises one session cannot forge envelopes for other peer pairs.
///
/// **Noise OFF (dev/testing only)**: No shared secret exists, so the raw salt
/// is used directly as the replay nonce. This stops passive network replays
/// (exact byte replay by a router/ISP) but provides NO authentication — any
/// active attacker can construct fresh messages. This mode is NOT secure for
/// production. Enforce `enable_noise_encryption = true` in production configs.
pub const WIRE_ENVELOPE_SIZE: usize = 16;
/// Derive a replay nonce bound to the envelope, payload, and per-session key.
/// Uses keyed SipHash-2-4 over (salt, timestamp, app_id, payload).
/// The per-session key is derived from the Noise handshake hash, so only the
/// two peers in the session can compute the correct nonce.
fn deriveEnvelopeNonce(key: *const [16]u8, salt: *const [8]u8, ts_bytes: *const [8]u8, app_id: u8, payload: []const u8) u64 {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(key);
hasher.update(salt);
hasher.update(ts_bytes);
hasher.update(&[_]u8{app_id});
hasher.update(payload);
return hasher.finalInt();
}
/// Look up the per-session envelope key for a peer from their Noise connection.
/// Returns null when the peer has no Noise session (Noise off or not yet handshaked).
/// Caller MUST hold peer_connections_mutex or accept TOCTOU (acceptable here since
/// the key is immutable after handshake and the connection outlives message processing).
fn getPerSessionEnvelopeKey(p2p: *P2P, peer_id: PeerId) ?[16]u8 {
p2p.peer_connections_mutex.lock();
defer p2p.peer_connections_mutex.unlock();
const peer_conn = p2p.peer_connections.get(peer_id) orelse return null;
return peer_conn.getEnvelopeKey();
}
/// Reserved app_ids that have their own send paths and replay protection.
/// File transfer (0x01): own integrity via piece hashing / session tracking.
/// DHT (0x02): own wire_nonce/wire_timestamp embedded in serialization.
const RESERVED_FILE_TRANSFER: u8 = 0x01;
const RESERVED_DHT: u8 = 0x02;
fn isReservedAppId(app_id: u8) bool {
return app_id == RESERVED_FILE_TRANSFER or app_id == RESERVED_DHT;
}
/// Send a custom message to a peer
pub fn sendMessageImpl(p2p: *P2P, destination: ?PeerId, message_type: u8, data: []const u8) Error!u64 {
if (!p2p.running.load(.acquire)) return Error.InvalidState;
@@ -44,10 +100,29 @@ pub fn sendMessageImpl(p2p: *P2P, destination: ?PeerId, message_type: u8, data:
const nm = p2p.network_manager orelse return Error.InvalidState;
var full_msg = p2p.allocator.alloc(u8, data.len + 1) catch return Error.OutOfMemory;
// Only add wire envelope for non-reserved app_ids.
// Reserved types (file transfer, DHT) have their own send paths with
// their own replay protection; adding an envelope here would corrupt
// them if someone mistakenly sends through the public API.
const envelope_len: usize = if (isReservedAppId(message_type)) 0 else WIRE_ENVELOPE_SIZE;
var full_msg = p2p.allocator.alloc(u8, data.len + 1 + envelope_len) catch return Error.OutOfMemory;
defer p2p.allocator.free(full_msg);
full_msg[0] = message_type;
@memcpy(full_msg[1..], data);
if (!isReservedAppId(message_type)) {
// Write wire envelope: salt (8 random LE) + timestamp (8 LE)
// The receiver derives the replay nonce from these fields:
// - Noise ON: SipHash(session_key, salt || ts || app_id || payload)
// - Noise OFF: raw salt (passive replay protection only)
const wire_salt = protocol.message.generateWireNonce(); // 8 random bytes
const wire_timestamp = std.time.timestamp();
std.mem.writeInt(u64, full_msg[1..9], wire_salt, .little);
std.mem.writeInt(i64, full_msg[9..17], wire_timestamp, .little);
}
// Copy payload after app_id + envelope (if any)
@memcpy(full_msg[1 + envelope_len ..], data);
if (destination) |peer_id| {
const msg_id = try nm.sendMessage(peer_id, full_msg);
@@ -259,7 +334,50 @@ pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*an
return;
}
const payload_src: []const u8 = if (data.len > 1) data[1..] else &[_]u8{};
// Non-DHT, non-file-transfer: extract wire envelope and check replay
if (data.len < 1 + WIRE_ENVELOPE_SIZE) {
// Too short to contain envelope — drop silently
return;
}
const wire_timestamp = std.mem.readInt(i64, data[9..17], .little);
const payload_src: []const u8 = if (data.len > 1 + WIRE_ENVELOPE_SIZE) data[1 + WIRE_ENVELOPE_SIZE ..] else &[_]u8{};
// Derive per-peer message ID. Two modes:
//
// 1. Noise ON: Use per-session SipHash key from the Noise handshake.
// This binds (salt || timestamp || app_id || payload) into an ID that
// only the two peers in this session can compute. An attacker who captures
// traffic cannot forge envelopes without the session key.
//
// 2. Noise OFF: No shared secret. Use the raw 8-byte salt as the ID.
// This only stops passive replay (exact same bytes). No authentication.
const envelope_msg_id = if (getPerSessionEnvelopeKey(p2p, peer_id)) |key|
deriveEnvelopeNonce(&key, data[1..9], data[9..17], app_id, payload_src)
else
std.mem.readInt(u64, data[1..9], .little); // raw salt fallback
// Replay protection check (per-peer msg_id dedup + timestamp validation)
if (p2p.handler_registry) |registry| {
registry.replay_protector.checkMessage(
envelope_msg_id, // msg_id: per-peer dedup
wire_timestamp, // sender's timestamp
0, // sequence: not applicable
peer_id.bytes, // [32]u8 peer ID
app_id, // message type
) catch |err| {
std.log.warn("Replay protection rejected non-DHT message: {s} (app_id={}, peer_hint={x:0>2}{x:0>2})", .{
@errorName(err), app_id, peer_id.bytes[0], peer_id.bytes[1],
});
return;
};
} else {
// SECURITY: No handler registry means no replay protection. Drop the message.
// This should never happen after start() completes (handler_registry is initialized
// in startImpl before network callbacks are wired), but guard against it defensively.
std.log.warn("SECURITY: Non-DHT message DROPPED — no handler registry for replay protection (app_id={})", .{app_id});
return;
}
const payload = p2p.allocator.dupe(u8, payload_src) catch return;

View File

@@ -1013,7 +1013,6 @@ pub const HandlerRegistry = struct {
// Extract message metadata for replay detection
const msg_id = msg.getIdForReplay();
const timestamp = msg.getTimestamp();
const nonce = msg.getNonce();
const sequence = msg.getSequence();
// Get source from message (fallback since msg.getSource() may return zeros)
@@ -1032,7 +1031,6 @@ pub const HandlerRegistry = struct {
self.replay_protector.checkMessage(
msg_id,
timestamp,
nonce,
sequence,
source_id,
@intFromEnum(msg_type),
@@ -1041,7 +1039,7 @@ pub const HandlerRegistry = struct {
self.context.metrics.recordMessageFailed();
// SEC-M4 FIX: Don't log full peer ID to prevent correlation attacks
// Only log first 4 bytes as identifier hint
std.log.err("SECURITY: Replay attack detected: {s} (msg_id={}, peer_hint={x:0>2}{x:0>2}{x:0>2}{x:0>2})", .{
core.log.err("SECURITY: Replay attack detected: {s} (msg_id={}, peer_hint={x:0>2}{x:0>2}{x:0>2}{x:0>2})", .{
@errorName(err),
msg_id,
source_id[0],
@@ -1110,9 +1108,8 @@ pub const HandlerRegistry = struct {
// SEC-M7 FIX: Use std.log instead of debug.print for production
const stats = self.replay_protector.getStats();
std.log.debug("Replay protection cleanup: {d} messages, {d} nonces, {d} peers tracked", .{
std.log.debug("Replay protection cleanup: {d} messages, {d} peers tracked", .{
stats.tracked_messages,
stats.tracked_nonces,
stats.tracked_peers,
});
}

View File

@@ -956,6 +956,8 @@ pub fn handleDhtFindNode(
.closest_nodes = converted_nodes,
.observed_addr = observed.addr,
.observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};
@@ -1072,6 +1074,8 @@ pub fn handleDhtStore(
.success = false,
.observed_addr = observed.addr,
.observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};
_ = context.sendDhtMessage(msg.sender_id, fail_response);
@@ -1086,6 +1090,8 @@ pub fn handleDhtStore(
.success = response.success,
.observed_addr = observed.addr,
.observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};
@@ -1200,6 +1206,8 @@ pub fn handleDhtFindValue(
.closest_nodes = converted_nodes,
.observed_addr = observed.addr,
.observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
},
};

View File

@@ -548,6 +548,10 @@ pub const DhtFindNode = struct {
/// This tells the receiver what their address looks like from our perspective
target_observed_addr: [18]u8 = [_]u8{0} ** 18,
target_observed_addr_len: u8 = 0,
/// Per-message random salt for per-peer replay detection
wire_nonce: u64 = 0,
/// Sender timestamp for temporal replay validation
wire_timestamp: i64 = 0,
pub fn init(target: NodeId, sender: NodeId) DhtFindNode {
return .{
@@ -556,6 +560,8 @@ pub const DhtFindNode = struct {
.sender_id = sender,
.target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
@@ -566,6 +572,8 @@ pub const DhtFindNode = struct {
.sender_id = sender,
.target_observed_addr = addr,
.target_observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
};
@@ -579,6 +587,10 @@ pub const DhtFindNodeResponse = struct {
/// Format: IPv4 = 6 bytes (4 IP + 2 port), IPv6 = 18 bytes (16 IP + 2 port)
observed_addr: [18]u8 = [_]u8{0} ** 18,
observed_addr_len: u8 = 0,
/// Per-message random salt for per-peer replay detection
wire_nonce: u64 = 0,
/// Sender timestamp for temporal replay validation
wire_timestamp: i64 = 0,
pub const NodeInfo = struct {
node_id: NodeId,
@@ -592,6 +604,8 @@ pub const DhtFindNodeResponse = struct {
.closest_nodes = closest_nodes,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
@@ -601,6 +615,8 @@ pub const DhtFindNodeResponse = struct {
.closest_nodes = closest_nodes,
.observed_addr = addr,
.observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
};
@@ -617,6 +633,10 @@ pub const DhtStore = struct {
/// This tells the receiver what their address looks like from our perspective
target_observed_addr: [18]u8 = [_]u8{0} ** 18,
target_observed_addr_len: u8 = 0,
/// Per-message random salt for per-peer replay detection
wire_nonce: u64 = 0,
/// Sender timestamp for temporal replay validation
wire_timestamp: i64 = 0,
pub fn init(key: [32]u8, value: []const u8, ttl: u32, sender: NodeId) DhtStore {
return .{
@@ -627,6 +647,8 @@ pub const DhtStore = struct {
.sender_id = sender,
.target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
@@ -639,6 +661,8 @@ pub const DhtStore = struct {
.sender_id = sender,
.target_observed_addr = addr,
.target_observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
};
@@ -651,6 +675,10 @@ pub const DhtStoreResponse = struct {
/// IP Reflection: The observed source address of the requester (bundled STUN)
observed_addr: [18]u8 = [_]u8{0} ** 18,
observed_addr_len: u8 = 0,
/// Per-message random salt for per-peer replay detection
wire_nonce: u64 = 0,
/// Sender timestamp for temporal replay validation
wire_timestamp: i64 = 0,
pub fn init(request_id: u64, success: bool) DhtStoreResponse {
return .{
@@ -658,6 +686,8 @@ pub const DhtStoreResponse = struct {
.success = success,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
@@ -667,6 +697,8 @@ pub const DhtStoreResponse = struct {
.success = success,
.observed_addr = addr,
.observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
};
@@ -681,6 +713,10 @@ pub const DhtFindValue = struct {
/// This tells the receiver what their address looks like from our perspective
target_observed_addr: [18]u8 = [_]u8{0} ** 18,
target_observed_addr_len: u8 = 0,
/// Per-message random salt for per-peer replay detection
wire_nonce: u64 = 0,
/// Sender timestamp for temporal replay validation
wire_timestamp: i64 = 0,
pub fn init(key: [32]u8, sender: NodeId) DhtFindValue {
return .{
@@ -689,6 +725,8 @@ pub const DhtFindValue = struct {
.sender_id = sender,
.target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
@@ -699,6 +737,8 @@ pub const DhtFindValue = struct {
.sender_id = sender,
.target_observed_addr = addr,
.target_observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
};
@@ -713,6 +753,10 @@ pub const DhtFindValueResponse = struct {
/// IP Reflection: The observed source address of the requester (bundled STUN)
observed_addr: [18]u8 = [_]u8{0} ** 18,
observed_addr_len: u8 = 0,
/// Per-message random salt for per-peer replay detection
wire_nonce: u64 = 0,
/// Sender timestamp for temporal replay validation
wire_timestamp: i64 = 0,
pub fn init(request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const DhtFindNodeResponse.NodeInfo) DhtFindValueResponse {
return .{
@@ -722,6 +766,8 @@ pub const DhtFindValueResponse = struct {
.closest_nodes = closest_nodes,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
@@ -733,25 +779,26 @@ pub const DhtFindValueResponse = struct {
.closest_nodes = closest_nodes,
.observed_addr = addr,
.observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(),
};
}
};
/// Generate a unique request ID using cryptographic randomness
///
/// CRY-M1 FIX: Uses timestamp + random combination to reduce collision risk
/// Generate a cryptographically random wire nonce for replay detection
pub fn generateWireNonce() u64 {
var bytes: [8]u8 = undefined;
std.crypto.random.bytes(&bytes);
return std.mem.readInt(u64, &bytes, .little);
}
/// Generate a unique request ID for correlating DHT request/response pairs.
/// Replay detection is handled by wire_nonce, so this only needs to be unique
/// enough to match responses to their pending requests.
fn generateRequestId() u64 {
// Get nanosecond timestamp and use lower 32 bits
const ts = std.time.nanoTimestamp();
const ts_component: u32 = @truncate(@as(u64, @bitCast(ts)));
// Get 4 bytes of cryptographic randomness
var random_bytes: [4]u8 = undefined;
std.crypto.random.bytes(&random_bytes);
const random_component = std.mem.readInt(u32, &random_bytes, .little);
// Combine: timestamp in high bits, random in low bits
return (@as(u64, ts_component) << 32) | @as(u64, random_component);
var bytes: [8]u8 = undefined;
std.crypto.random.bytes(&bytes);
return std.mem.readInt(u64, &bytes, .little);
}
/// Security messages for key exchange
@@ -873,7 +920,28 @@ pub const KeyConfirmation = struct {
}
};
/// Per-process random SipHash key for deterministic nonce/ID computation.
/// Used only on the receiver side (getIdForReplay),
/// so it does NOT need to agree between sender and receiver. A per-process
/// random key prevents attackers from precomputing hash collisions.
///
/// Thread safety: Uses std.once to ensure exactly one initialization even when
/// multiple HandlerRegistry instances (e.g. TestP2PPair server + client) call
/// getReplaySiphashKey() concurrently from different processing_mutex scopes.
var replay_siphash_key: [16]u8 = undefined;
var replay_siphash_key_once = std.once(initReplaySiphashKey);
fn initReplaySiphashKey() void {
std.crypto.random.bytes(&replay_siphash_key);
}
fn getReplaySiphashKey() *const [16]u8 {
replay_siphash_key_once.call();
return &replay_siphash_key;
}
/// Union of all message types
pub const Message = union(protocol.MessageType) {
discovery_hello: DiscoveryHello,
discovery_response: DiscoveryResponse,
@@ -930,67 +998,124 @@ pub const Message = union(protocol.MessageType) {
};
}
/// Get message ID for replay protection (generates one if not available)
/// Get message ID for replay protection (derives stable ID when not available)
pub fn getIdForReplay(self: Message) MessageId {
return self.getId() orelse blk: {
// For messages without explicit IDs, generate a cryptographically strong random ID
var id: [8]u8 = undefined;
std.crypto.random.bytes(&id);
break :blk std.mem.readInt(u64, &id, .little);
return self.getId() orelse switch (self) {
// Discovery messages: derive ID from signer identity + timestamp
.discovery_hello => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(m.signer_id[0..8]);
hasher.update(std.mem.asBytes(&m.timestamp));
break :blk hasher.finalInt();
},
.discovery_announce => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(m.signer_id[0..8]);
hasher.update(std.mem.asBytes(&m.timestamp));
break :blk hasher.finalInt();
},
// App messages: derive ID from app_id + content
.app_data => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(std.mem.asBytes(&m.app_id));
const data_prefix = m.data[0..@min(m.data.len, 64)];
hasher.update(data_prefix);
break :blk hasher.finalInt();
},
.app_control => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(std.mem.asBytes(&m.app_id));
hasher.update(std.mem.asBytes(&m.command));
break :blk hasher.finalInt();
},
// Sequenced types: derive ID from sequence + content prefix.
// These also have sliding window protection via checkSequence().
.topology_update => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(std.mem.asBytes(&m.sequence));
hasher.update(std.mem.asBytes(&m.ttl));
const changes_prefix = m.changes[0..@min(m.changes.len, 32)];
hasher.update(changes_prefix);
break :blk hasher.finalInt();
},
.data_chunk => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(std.mem.asBytes(&m.sequence));
const id_prefix = m.data_id[0..@min(m.data_id.len, 32)];
hasher.update(id_prefix);
break :blk hasher.finalInt();
},
.route_update => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(std.mem.asBytes(&m.sequence));
hasher.update(m.signer_id[0..8]);
break :blk hasher.finalInt();
},
// Key exchange: derive from unique cryptographic material
.key_exchange_response => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(&m.responder_public_key);
hasher.update(std.mem.asBytes(&m.timestamp));
break :blk hasher.finalInt();
},
.key_confirmation => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(&m.confirmation_tag);
break :blk hasher.finalInt();
},
.key_exchange_init => |m| blk: {
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey());
hasher.update(&m.initiator_public_key);
hasher.update(std.mem.asBytes(&m.timestamp));
break :blk hasher.finalInt();
},
else => blk: {
// All known message types are handled above or by getId().
// If we reach here, a new message type was added without updating
// this switch. Using random means replay protection relies solely
// on per-peer msg_id dedup and Noise AEAD.
var id: [8]u8 = undefined;
std.crypto.random.bytes(&id);
break :blk std.mem.readInt(u64, &id, .little);
},
};
}
/// Get timestamp for replay protection (current time as fallback)
/// Get timestamp for replay protection.
///
/// Returns the sender-provided timestamp where available, enabling the replay
/// protector to reject stale or future-dated messages. Types without an embedded
/// timestamp return the receiver's clock (std.time.timestamp()), which makes
/// timestamp validation a no-op for those types. This is acceptable because:
///
/// - With Noise ON (production): AEAD prevents replay at the transport layer.
/// - msg_id dedup (PeerMessageKey) catches duplicate request_id/query_id.
/// - Sequenced types (topology_update, data_chunk, route_update) have sliding
/// window protection via checkSequence().
/// - Non-DHT custom messages bypass this entirely — they use the wire envelope
/// timestamp directly in handleNetworkMessageImpl().
pub fn getTimestamp(self: Message) i64 {
_ = self;
// Message union doesn't store timestamp, use current time
return std.time.timestamp();
}
/// Get nonce for replay protection
/// SEC-5 FIX: Computes a deterministic nonce from message content
/// This ensures sender and receiver compute the same nonce for the same message,
/// which is required for replay detection to work correctly.
/// The nonce is derived by hashing the message type and ID together.
pub fn getNonce(self: Message) u64 {
// SECURITY: Compute deterministic nonce from message properties
// This ensures the same message always produces the same nonce
const msg_id = self.getId() orelse 0;
const msg_type_byte: u8 = @intFromEnum(self.getType());
// CRY-M3 SECURITY ANALYSIS:
// The SipHash key is intentionally fixed (not runtime-random) because:
// 1. Replay protection requires DETERMINISTIC nonce generation
// 2. Both sender and receiver must compute the SAME nonce for the same message
// 3. The key provides domain separation, not secrecy
// 4. Message uniqueness comes from the random message_id (line 752), not the key
//
// An attacker knowing this key cannot:
// - Forge valid messages (nonce doesn't authenticate)
// - Predict future nonces (message_id is cryptographically random)
// - Bypass replay protection (they'd need the same message_id)
//
// CRY-M3 FIX: Use HKDF to derive key from domain-specific constant
// This provides proper key derivation and makes the intent explicit
const domain_separator = "zig-p2p-v1-replay-nonce-siphash-key";
const derived_key = comptime blk: {
// HKDF requires many iterations for SHA-256 rounds
@setEvalBranchQuota(100000);
var key: [16]u8 = undefined;
// Use HKDF-SHA256 to derive a proper key from the domain separator
const hkdf = std.crypto.kdf.hkdf.HkdfSha256;
const prk = hkdf.extract(&[_]u8{}, domain_separator);
hkdf.expand(&key, "siphash-key", prk);
break :blk key;
return switch (self) {
// DHT messages: wire-level timestamp from serialization
.dht_find_node => |m| m.wire_timestamp,
.dht_find_node_response => |m| m.wire_timestamp,
.dht_store => |m| m.wire_timestamp,
.dht_store_response => |m| m.wire_timestamp,
.dht_find_value => |m| m.wire_timestamp,
.dht_find_value_response => |m| m.wire_timestamp,
// Discovery and key exchange: embedded sender timestamp
.discovery_hello => |m| m.timestamp,
.discovery_announce => |m| m.timestamp,
.discovery_response => |m| m.timestamp,
.key_exchange_init => |m| m.timestamp,
.key_exchange_response => |m| m.timestamp,
// RouteResponse has a signed timestamp
.route_response => |m| m.timestamp,
// All other types have no sender timestamp. Returning receiver's clock
// makes validateTimestamp() a no-op. Replay defense for these types relies
// on msg_id dedup, sequence windows, and Noise AEAD.
else => std.time.timestamp(),
};
// Hash: message_type || message_id || sequence
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(&derived_key);
hasher.update(&[_]u8{msg_type_byte});
hasher.update(std.mem.asBytes(&msg_id));
hasher.update(std.mem.asBytes(&self.getSequence()));
return hasher.finalInt();
}
/// Get sequence number for replay protection

View File

@@ -3,7 +3,7 @@
//! - Message ID tracking with TTL-based cleanup
//! - Timestamp validation with clock skew tolerance
//! - Per-peer sequence number tracking with sliding windows
//! - Nonce tracking for uniqueness
//! - Per-peer, per-type message ID dedup
const std = @import("std");
const message = @import("message.zig");
@@ -19,8 +19,6 @@ pub const ReplayError = error{
DuplicateMessageId,
/// Sequence number is out of order or too old
InvalidSequence,
/// Nonce has been seen before
DuplicateNonce,
/// Peer sequence is too far behind (possible replay)
SequenceTooOld,
};
@@ -28,20 +26,19 @@ pub const ReplayError = error{
/// Message tracking entry
const MessageEntry = struct {
timestamp: i64,
nonce: u64,
};
/// Composite key for per-peer message tracking
/// This ensures message IDs are tracked per-peer to avoid collisions
/// when different peers use the same sequence numbers
const PeerMessageKey = struct {
peer_id_prefix: [8]u8, // First 8 bytes of peer ID for compact storage
peer_id_prefix: [16]u8, // First 16 bytes of peer ID (128-bit prefix)
msg_id: u64,
msg_type: u8, // Distinguishes request/response with same request_id
pub fn init(peer_id: [32]u8, msg_id: u64, msg_type: u8) PeerMessageKey {
var prefix: [8]u8 = undefined;
@memcpy(&prefix, peer_id[0..8]);
var prefix: [16]u8 = undefined;
@memcpy(&prefix, peer_id[0..16]);
return .{
.peer_id_prefix = prefix,
.msg_id = msg_id,
@@ -132,24 +129,19 @@ pub const MemoryError = error{
TooManyMessages,
/// Too many tracked peers - memory limit reached
TooManyPeers,
/// Too many tracked nonces - memory limit reached
TooManyNonces,
};
/// Main replay protection implementation
pub const ReplayProtector = struct {
allocator: std.mem.Allocator,
/// Track seen message IDs with their timestamps and nonces (per-peer)
/// Track seen message IDs with their timestamps (per-peer, per-type)
/// Uses PeerMessageKey to avoid collisions when different peers use same sequence numbers
seen_messages: std.AutoHashMap(PeerMessageKey, MessageEntry),
/// Track per-peer sequence numbers
peer_sequences: std.AutoHashMap([32]u8, PeerSequenceState),
/// Track seen nonces globally (prevents nonce reuse across messages)
seen_nonces: std.AutoHashMap(u64, i64),
/// Maximum allowed clock skew in seconds (default: 5 seconds)
/// HIGH-3 FIX: Reduced from 15 to 5 seconds for tighter replay protection
/// SECURITY: Modern NTP typically achieves <100ms accuracy, 5s is conservative
@@ -177,15 +169,11 @@ pub const ReplayProtector = struct {
/// SECURITY: Maximum number of tracked peers to prevent memory exhaustion
pub const MAX_TRACKED_PEERS: usize = 10_000;
/// SECURITY: Maximum number of tracked nonces to prevent memory exhaustion
pub const MAX_TRACKED_NONCES: usize = 600_000;
pub fn init(allocator: std.mem.Allocator) ReplayProtector {
return .{
.allocator = allocator,
.seen_messages = std.AutoHashMap(PeerMessageKey, MessageEntry).init(allocator),
.peer_sequences = std.AutoHashMap([32]u8, PeerSequenceState).init(allocator),
.seen_nonces = std.AutoHashMap(u64, i64).init(allocator),
.max_clock_skew = 5, // HIGH-3: 5 seconds (reduced from 15s)
.message_ttl = 10, // HIGH-3: 10 seconds (reduced from 30s)
.last_cleanup = std.time.timestamp(),
@@ -197,17 +185,22 @@ pub const ReplayProtector = struct {
pub fn deinit(self: *ReplayProtector) void {
self.seen_messages.deinit();
self.peer_sequences.deinit();
self.seen_nonces.deinit();
}
/// Check if a message is a replay attack
/// Returns error if message should be rejected
///
/// Defense layers (each independent, no overlap):
/// - Timestamp validation: rejects stale/future messages
/// - Per-peer msg_id dedup: rejects same (peer, msg_id, msg_type) tuple
/// - Sequence windows: rejects out-of-order/replayed ordered messages
/// - Noise AEAD (external): prevents wire-level replay and forgery
///
/// SECURITY: Enforces memory limits to prevent DoS via memory exhaustion
pub fn checkMessage(
self: *ReplayProtector,
msg_id: u64,
timestamp: i64,
nonce: u64,
sequence: u64,
peer_id: [32]u8,
msg_type: u8,
@@ -218,25 +211,16 @@ pub const ReplayProtector = struct {
const current_time = std.time.timestamp();
// SECURITY: Check and enforce memory limits before adding entries
// If we're at the limit, force cleanup first
if (self.seen_messages.count() >= MAX_TRACKED_MESSAGES or
self.seen_nonces.count() >= MAX_TRACKED_NONCES)
{
std.log.warn("SECURITY: Replay protection at memory limit, forcing cleanup (messages={}, nonces={})", .{
if (self.seen_messages.count() >= MAX_TRACKED_MESSAGES) {
std.log.warn("SECURITY: Replay protection at memory limit, forcing cleanup (messages={})", .{
self.seen_messages.count(),
self.seen_nonces.count(),
});
self.cleanup(current_time);
// If still at limit after cleanup, reject to prevent exhaustion
if (self.seen_messages.count() >= MAX_TRACKED_MESSAGES) {
std.log.err("SECURITY: Replay protection message limit exceeded after cleanup - possible DoS attack", .{});
return MemoryError.TooManyMessages;
}
if (self.seen_nonces.count() >= MAX_TRACKED_NONCES) {
std.log.err("SECURITY: Replay protection nonce limit exceeded after cleanup - possible DoS attack", .{});
return MemoryError.TooManyNonces;
}
}
// 1. Validate timestamp
@@ -244,16 +228,11 @@ pub const ReplayProtector = struct {
// 2. Check for duplicate message ID (per-peer, per-type to avoid collisions
// between request/response pairs that share the same request_id)
if (try self.isReplay(peer_id, msg_id, msg_type, timestamp, nonce)) {
if (self.isReplay(peer_id, msg_id, msg_type)) {
return ReplayError.DuplicateMessageId;
}
// 3. Check nonce uniqueness
if (try self.isDuplicateNonce(nonce, timestamp)) {
return ReplayError.DuplicateNonce;
}
// 4. Check sequence number for ordered messages
// 3. Check sequence number for ordered messages
if (sequence != 0) {
// SECURITY: Check peer limit before potentially adding new peer
if (!self.peer_sequences.contains(peer_id) and
@@ -270,17 +249,13 @@ pub const ReplayProtector = struct {
try self.checkSequence(peer_id, sequence, current_time);
}
// 5. Record this message as seen (per-peer, per-type key)
// 4. Record this message as seen (per-peer, per-type key)
const key = PeerMessageKey.init(peer_id, msg_id, msg_type);
try self.seen_messages.put(key, .{
.timestamp = timestamp,
.nonce = nonce,
});
// 6. Record nonce as seen
try self.seen_nonces.put(nonce, timestamp);
// 7. Periodic cleanup
// 5. Periodic cleanup
if (current_time - self.last_cleanup > self.cleanup_interval) {
self.cleanup(current_time);
self.last_cleanup = current_time;
@@ -305,55 +280,9 @@ pub const ReplayProtector = struct {
/// Check if message ID was seen before (per-peer)
/// Uses PeerMessageKey to ensure message IDs are tracked per-peer and per-type,
/// avoiding collisions between request/response pairs that share the same request_id
fn isReplay(self: *ReplayProtector, peer_id: [32]u8, msg_id: u64, msg_type: u8, timestamp: i64, nonce: u64) !bool {
fn isReplay(self: *ReplayProtector, peer_id: [32]u8, msg_id: u64, msg_type: u8) bool {
const key = PeerMessageKey.init(peer_id, msg_id, msg_type);
if (self.seen_messages.get(key)) |entry| {
// Found duplicate message ID from this peer
// Additional check: if timestamp and nonce match, it's definitely a replay
if (entry.timestamp == timestamp and entry.nonce == nonce) {
return true;
}
// Different timestamp or nonce with same ID is suspicious but could be
// a collision (unlikely with 64-bit random IDs)
return true;
}
return false;
}
/// Check if nonce was seen before
/// IMP-M6 FIX: Now uses timestamp for temporal validation
fn isDuplicateNonce(self: *ReplayProtector, nonce: u64, timestamp: i64) !bool {
const current_time = std.time.timestamp();
// IMP-M6 FIX: Reject messages with timestamps too far in the future
// This prevents attackers from pre-computing future nonces
const max_future_skew: i64 = 60; // 1 minute max clock skew
if (timestamp > current_time + max_future_skew) {
std.log.warn("SECURITY: Rejecting message with future timestamp (delta={}s)", .{
timestamp - current_time,
});
return true; // Treat as duplicate to reject
}
// IMP-M6 FIX: Reject messages with timestamps older than TTL
// This is a defense-in-depth against replay with old timestamps
if (current_time - timestamp > self.message_ttl) {
std.log.debug("Rejecting message with stale timestamp (age={}s)", .{
current_time - timestamp,
});
return true; // Treat as duplicate to reject
}
if (self.seen_nonces.get(nonce)) |seen_timestamp| {
// Nonce was seen before
// Allow nonce reuse if old entry has expired
if (current_time - seen_timestamp > self.message_ttl) {
// Old nonce, can be reused
return false;
}
return true;
}
return false;
return self.seen_messages.contains(key);
}
/// Check sequence number for ordered messages
@@ -411,37 +340,6 @@ pub const ReplayProtector = struct {
_ = self.seen_messages.remove(key);
}
// Clean up old nonces
var nonce_it = self.seen_nonces.iterator();
var to_remove_nonces = std.ArrayList(u64){};
defer to_remove_nonces.deinit(self.allocator);
// SEC-M3 FIX: Limit pre-allocation to prevent memory DoS
const nonce_prealloc = @min(self.seen_nonces.count(), MAX_PREALLOC);
to_remove_nonces.ensureTotalCapacity(self.allocator, nonce_prealloc) catch |err| {
std.log.err("Failed to pre-allocate nonce cleanup list (capacity {}): {}", .{ nonce_prealloc, err });
};
var nonce_cleanup_failures: usize = 0;
while (nonce_it.next()) |entry| {
const age = current_time - entry.value_ptr.*;
if (age > self.message_ttl) {
to_remove_nonces.append(self.allocator, entry.key_ptr.*) catch |err| {
std.log.err("Failed to track expired nonce during cleanup: {}", .{err});
nonce_cleanup_failures += 1;
continue;
};
}
}
if (nonce_cleanup_failures > 0) {
std.log.warn("Nonce cleanup encountered {} failures", .{nonce_cleanup_failures});
}
for (to_remove_nonces.items) |nonce| {
_ = self.seen_nonces.remove(nonce);
}
// Clean up inactive peer sequences (older than 24 hours)
const peer_timeout = 24 * 3600; // 24 hours
var peer_it = self.peer_sequences.iterator();
@@ -530,7 +428,6 @@ pub const ReplayProtector = struct {
return .{
.tracked_messages = self.seen_messages.count(),
.tracked_nonces = self.seen_nonces.count(),
.tracked_peers = self.peer_sequences.count(),
.last_cleanup = self.last_cleanup,
};
@@ -561,7 +458,6 @@ pub const ReplayProtector = struct {
/// Statistics for replay protection monitoring
pub const ReplayStats = struct {
tracked_messages: usize,
tracked_nonces: usize,
tracked_peers: usize,
last_cleanup: i64,
};
@@ -572,7 +468,6 @@ test "replay protector initialization" {
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 0), stats.tracked_messages);
try std.testing.expectEqual(@as(usize, 0), stats.tracked_nonces);
try std.testing.expectEqual(@as(usize, 0), stats.tracked_peers);
}
@@ -584,7 +479,7 @@ test "timestamp validation - reject old timestamps" {
const old_timestamp = current_time - 7200; // 2 hours ago
const peer_id = [_]u8{1} ** 32;
const result = protector.checkMessage(1, old_timestamp, 1000, 0, peer_id, 0);
const result = protector.checkMessage(1, old_timestamp, 0, peer_id, 0);
try std.testing.expectError(ReplayError.TimestampTooOld, result);
}
@@ -597,7 +492,7 @@ test "timestamp validation - reject future timestamps" {
const future_timestamp = current_time + 600; // 10 minutes in future
const peer_id = [_]u8{1} ** 32;
const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id, 0);
const result = protector.checkMessage(1, future_timestamp, 0, peer_id, 0);
try std.testing.expectError(ReplayError.TimestampTooFarInFuture, result);
}
@@ -611,7 +506,7 @@ test "timestamp validation - accept valid timestamps" {
const valid_timestamp = current_time - 5;
const peer_id = [_]u8{1} ** 32;
try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id, 0);
try protector.checkMessage(1, valid_timestamp, 0, peer_id, 0);
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 1), stats.tracked_messages);
@@ -625,28 +520,13 @@ test "duplicate message ID detection" {
const peer_id = [_]u8{1} ** 32;
// First message should succeed
try protector.checkMessage(42, current_time, 1000, 0, peer_id, 0);
try protector.checkMessage(42, current_time, 0, peer_id, 0);
// Duplicate message ID should fail
const result = protector.checkMessage(42, current_time, 1001, 0, peer_id, 0);
const result = protector.checkMessage(42, current_time, 0, peer_id, 0);
try std.testing.expectError(ReplayError.DuplicateMessageId, result);
}
test "duplicate nonce detection" {
var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{1} ** 32;
// First message with nonce 5000
try protector.checkMessage(1, current_time, 5000, 0, peer_id, 0);
// Different message ID but same nonce should fail
const result = protector.checkMessage(2, current_time, 5000, 0, peer_id, 0);
try std.testing.expectError(ReplayError.DuplicateNonce, result);
}
test "sequence number enforcement - in order" {
var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit();
@@ -655,9 +535,9 @@ test "sequence number enforcement - in order" {
const peer_id = [_]u8{1} ** 32;
// Send messages in order
try protector.checkMessage(1, current_time, 1000, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 1001, 2, peer_id, 0);
try protector.checkMessage(3, current_time + 2, 1002, 3, peer_id, 0);
try protector.checkMessage(1, current_time, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 2, peer_id, 0);
try protector.checkMessage(3, current_time + 2, 3, peer_id, 0);
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 1), stats.tracked_peers);
@@ -671,10 +551,10 @@ test "sequence number enforcement - out of order within window" {
const peer_id = [_]u8{2} ** 32;
// Send sequence 1, 2, 5, then 3 (out of order but within window)
try protector.checkMessage(1, current_time, 2000, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 2001, 2, peer_id, 0);
try protector.checkMessage(3, current_time + 2, 2002, 5, peer_id, 0);
try protector.checkMessage(4, current_time + 3, 2003, 3, peer_id, 0);
try protector.checkMessage(1, current_time, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 2, peer_id, 0);
try protector.checkMessage(3, current_time + 2, 5, peer_id, 0);
try protector.checkMessage(4, current_time + 3, 3, peer_id, 0);
}
test "sequence number enforcement - reject duplicate sequence" {
@@ -685,10 +565,10 @@ test "sequence number enforcement - reject duplicate sequence" {
const peer_id = [_]u8{3} ** 32;
// Send sequence 1, 2, then 2 again
try protector.checkMessage(1, current_time, 3000, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 3001, 2, peer_id, 0);
try protector.checkMessage(1, current_time, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 2, peer_id, 0);
const result = protector.checkMessage(3, current_time + 2, 3002, 2, peer_id, 0);
const result = protector.checkMessage(3, current_time + 2, 2, peer_id, 0);
try std.testing.expectError(ReplayError.DuplicateMessageId, result);
}
@@ -700,9 +580,9 @@ test "sequence number enforcement - reject too old sequence" {
const peer_id = [_]u8{4} ** 32;
// Send sequence 100, then try to send sequence 1 (too old, outside window)
try protector.checkMessage(1, current_time, 4000, 100, peer_id, 0);
try protector.checkMessage(1, current_time, 100, peer_id, 0);
const result = protector.checkMessage(2, current_time + 1, 4001, 1, peer_id, 0);
const result = protector.checkMessage(2, current_time + 1, 1, peer_id, 0);
try std.testing.expectError(ReplayError.SequenceTooOld, result);
}
@@ -714,13 +594,13 @@ test "sliding window - large sequence jump" {
const peer_id = [_]u8{5} ** 32;
// Small sequence
try protector.checkMessage(1, current_time, 5000, 10, peer_id, 0);
try protector.checkMessage(1, current_time, 10, peer_id, 0);
// Large jump (> window size)
try protector.checkMessage(2, current_time + 1, 5001, 200, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 200, peer_id, 0);
// Should accept because window was reset
try protector.checkMessage(3, current_time + 2, 5002, 201, peer_id, 0);
try protector.checkMessage(3, current_time + 2, 201, peer_id, 0);
}
test "cleanup removes old entries" {
@@ -734,8 +614,8 @@ test "cleanup removes old entries" {
const peer_id = [_]u8{6} ** 32;
// Add messages with current timestamp (within TTL window)
try protector.checkMessage(1, base_time, 6000, 1, peer_id, 0);
try protector.checkMessage(2, base_time, 6001, 2, peer_id, 0);
try protector.checkMessage(1, base_time, 1, peer_id, 0);
try protector.checkMessage(2, base_time, 2, peer_id, 0);
var stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 2), stats.tracked_messages);
@@ -758,14 +638,14 @@ test "peer sequence reset" {
const peer_id = [_]u8{7} ** 32;
// Send some messages
try protector.checkMessage(1, current_time, 7000, 5, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 7001, 6, peer_id, 0);
try protector.checkMessage(1, current_time, 5, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 6, peer_id, 0);
// Reset peer sequence
try protector.resetPeerSequence(peer_id);
// Should be able to start from sequence 1 again
try protector.checkMessage(3, current_time + 2, 7002, 1, peer_id, 0);
try protector.checkMessage(3, current_time + 2, 1, peer_id, 0);
}
test "multiple peers tracked independently" {
@@ -777,10 +657,10 @@ test "multiple peers tracked independently" {
const peer2 = [_]u8{2} ** 32;
// Send messages from different peers
try protector.checkMessage(1, current_time, 8000, 1, peer1, 0);
try protector.checkMessage(2, current_time, 8001, 1, peer2, 0);
try protector.checkMessage(3, current_time + 1, 8002, 2, peer1, 0);
try protector.checkMessage(4, current_time + 1, 8003, 2, peer2, 0);
try protector.checkMessage(1, current_time, 1, peer1, 0);
try protector.checkMessage(2, current_time, 1, peer2, 0);
try protector.checkMessage(3, current_time + 1, 2, peer1, 0);
try protector.checkMessage(4, current_time + 1, 2, peer2, 0);
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 2), stats.tracked_peers);