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

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