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

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