fix crypto: secure zeroization of handshake state, ephemeral keys,

derived keys
This commit is contained in:
2026-02-11 14:20:16 -03:00
parent 4770fad51c
commit e45bffbd8b
7 changed files with 195 additions and 241 deletions

View File

@@ -22,6 +22,14 @@ const Role = noise.Role;
/// Maximum message size for Noise protocol
pub const MAX_MESSAGE_SIZE = noise.MAX_MESSAGE_SIZE;
/// Volatile secure zeroing (prevents compiler from eliding the write)
fn secureZeroBytes(bytes: []u8) void {
const volatile_ptr: [*]volatile u8 = @ptrCast(bytes.ptr);
for (0..bytes.len) |i| {
volatile_ptr[i] = 0;
}
}
/// Authentication tag size
pub const TAG_SIZE = noise.TAG_SIZE;
@@ -119,6 +127,9 @@ pub const SecureConnection = struct {
self.transport = hs.split() catch return Error.HandshakeFailed;
self.remote_static_key = hs.rs;
self.handshake_complete = true;
// Zeroize handshake state (ephemeral keys, symmetric state)
secureZeroBytes(std.mem.asBytes(&hs));
}
/// Perform handshake as responder (server accepting connection)
@@ -145,6 +156,9 @@ pub const SecureConnection = struct {
self.transport = hs.split() catch return Error.HandshakeFailed;
self.remote_static_key = hs.rs;
self.handshake_complete = true;
// Zeroize handshake state (ephemeral keys, symmetric state)
secureZeroBytes(std.mem.asBytes(&hs));
}
/// Send encrypted data (blocking - will sleep on WouldBlock)
@@ -333,19 +347,20 @@ pub const SecureConnection = struct {
// Private helpers for raw socket I/O during handshake
// =========================================================================
/// Absolute wall-clock timeout for each handshake send/receive operation (nanoseconds)
const HANDSHAKE_TIMEOUT_NS: i128 = 5 * std.time.ns_per_s;
/// Send raw data (unencrypted, for handshake)
fn sendRaw(self: *Self, data: []const u8) Error!void {
var sent: usize = 0;
var retries: u32 = 0;
const max_retries: u32 = 500; // 5 seconds with 10ms sleep
const deadline = std.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS;
while (sent < data.len) {
const bytes = self.socket.send(data[sent..]) catch |err| {
switch (err) {
CoreError.ConnectionTimeout => {
// WouldBlock - retry
retries += 1;
if (retries > max_retries) return Error.HandshakeTimeout;
// WouldBlock - check absolute deadline
if (std.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout;
std.Thread.sleep(10 * std.time.ns_per_ms);
continue;
},
@@ -353,7 +368,6 @@ pub const SecureConnection = struct {
}
};
sent += bytes;
retries = 0;
}
}
@@ -361,16 +375,14 @@ pub const SecureConnection = struct {
/// Returns actual bytes received
fn receiveRaw(self: *Self, buffer: []u8, min_bytes: usize) Error!usize {
var received: usize = 0;
var retries: u32 = 0;
const max_retries: u32 = 500; // 5 seconds with 10ms sleep
const deadline = std.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS;
while (received < min_bytes) {
const bytes = self.socket.receive(buffer[received..]) catch |err| {
switch (err) {
CoreError.ConnectionTimeout => {
// WouldBlock - retry
retries += 1;
if (retries > max_retries) return Error.HandshakeTimeout;
// WouldBlock - check absolute deadline
if (std.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout;
std.Thread.sleep(10 * std.time.ns_per_ms);
continue;
},
@@ -379,7 +391,6 @@ pub const SecureConnection = struct {
}
};
received += bytes;
retries = 0;
}
return received;

View File

@@ -874,9 +874,11 @@ pub const CryptoManager = struct {
/// CRY-M4 FIX: Derive HMAC key for file integrity from identity key
fn deriveFileIntegrityKey(self: *const CryptoManager) [32]u8 {
const secret_bytes = self.identity_keypair.secret_key.toBytes();
const prk = hkdf.HkdfSha256.extract(&[_]u8{}, &secret_bytes);
var prk = hkdf.HkdfSha256.extract(&[_]u8{}, &secret_bytes);
var integrity_key: [32]u8 = undefined;
hkdf.HkdfSha256.expand(&integrity_key, "zig-p2p-tofu-file-integrity", prk);
// SECURITY: Zeroize PRK after use
secureZero([32]u8, &prk);
return integrity_key;
}
@@ -1341,11 +1343,8 @@ pub const CryptoManager = struct {
writer.writeAll(&salt) catch return CryptoError.SaveFailed;
// Derive encryption key from password
const encryption_key = deriveKeyFromPassword(password, salt);
defer {
var key_copy = encryption_key;
secureZero([32]u8, &key_copy);
}
var encryption_key = deriveKeyFromPassword(password, salt);
defer secureZero([32]u8, &encryption_key);
// Generate random nonce
var nonce: [12]u8 = undefined;
@@ -1438,11 +1437,8 @@ pub const CryptoManager = struct {
reader.readNoEof(&salt) catch return CryptoError.InvalidFormat;
// Derive decryption key from password
const decryption_key = deriveKeyFromPassword(password, salt);
defer {
var key_copy = decryption_key;
secureZero([32]u8, &key_copy);
}
var decryption_key = deriveKeyFromPassword(password, salt);
defer secureZero([32]u8, &decryption_key);
// Read nonce
var nonce: [12]u8 = undefined;
@@ -1568,11 +1564,8 @@ pub const CryptoManager = struct {
writer.writeAll(&salt) catch return CryptoError.SaveFailed;
// Derive encryption key
const encryption_key = deriveKeyFromPassword(password, salt);
defer {
var key_copy = encryption_key;
secureZero([32]u8, &key_copy);
}
var encryption_key = deriveKeyFromPassword(password, salt);
defer secureZero([32]u8, &encryption_key);
// Generate and write nonce
var nonce: [12]u8 = undefined;
@@ -1655,11 +1648,8 @@ pub const CryptoManager = struct {
reader.readNoEof(&salt) catch return CryptoError.InvalidFormat;
// Derive decryption key
const decryption_key = deriveKeyFromPassword(password, salt);
defer {
var key_copy = decryption_key;
secureZero([32]u8, &key_copy);
}
var decryption_key = deriveKeyFromPassword(password, salt);
defer secureZero([32]u8, &decryption_key);
// Read nonce
var nonce: [12]u8 = undefined;
@@ -2456,8 +2446,8 @@ pub const CryptoManager = struct {
// Generate our ephemeral key pair
var key_pair = try KeyExchange.generateKeyPair();
// CRY-H3 FIX: Zeroize ephemeral secret on error to prevent leakage
errdefer secureZero([32]u8, &key_pair.secret);
// Zeroize local stack copy after stored copy goes into key_exchanges
defer secureZero([32]u8, &key_pair.secret);
// SECURITY: Sign our_public || our_timestamp || their_session_nonce
// This binds our response to the specific initiator session
@@ -2792,23 +2782,23 @@ pub const CryptoManager = struct {
/// CRIT-4 FIX: Remove all keys for a peer (used when key confirmation fails)
/// This invalidates the session and requires a new key exchange.
pub fn removeKey(self: *CryptoManager, peer_id: [32]u8) void {
// Remove encryption key
if (self.peer_keys.fetchRemove(peer_id)) |entry| {
var key_copy = entry.value;
secureZero([32]u8, &key_copy);
// Zeroize encryption key in-place before removing from map
if (self.peer_keys.getPtr(peer_id)) |key_ptr| {
secureZero([32]u8, key_ptr);
}
_ = self.peer_keys.remove(peer_id);
// Remove HMAC key
if (self.hmac_keys.fetchRemove(peer_id)) |entry| {
var key_copy = entry.value;
secureZero([32]u8, &key_copy);
// Zeroize HMAC key in-place before removing from map
if (self.hmac_keys.getPtr(peer_id)) |key_ptr| {
secureZero([32]u8, key_ptr);
}
_ = self.hmac_keys.remove(peer_id);
// Remove any pending key exchange
if (self.key_exchanges.fetchRemove(peer_id)) |entry| {
var secret_copy = entry.value.our_secret;
secureZero([32]u8, &secret_copy);
// Zeroize key exchange secret in-place before removing
if (self.key_exchanges.getPtr(peer_id)) |exchange_ptr| {
secureZero([32]u8, &exchange_ptr.our_secret);
}
_ = self.key_exchanges.remove(peer_id);
// Remove ratchet counter
_ = self.ratchet_counters.remove(peer_id);

View File

@@ -186,72 +186,24 @@ pub const NonceTracker = struct {
/// Internal record without locking (caller must hold mutex)
fn recordLocked(self: *NonceTracker, nonce: [12]u8) !void {
const parsed = parseNonce(nonce);
const nonce_key = self.nonceToFullKey(nonce);
// CRY-2 FIX: Proper eviction - remove oldest 25% of entries based on counter values
// instead of clearing everything (which opens replay window)
// CRIT-NEW-18 FIX: Loop to evict all needed entries instead of fixed 256 limit
// Track the highest counter we've seen for eviction threshold calculation
if (parsed.counter > self.highest_counter) {
self.highest_counter = parsed.counter;
}
// Sliding-window eviction: when full, advance min_allowed_counter and clear.
// The min_allowed_counter check in checkLocked() rejects any replayed nonces
// that were evicted, so clearing the set is safe.
if (self.seen_nonces.count() >= self.max_tracked_nonces) {
// Calculate eviction threshold - remove nonces with counters in lowest 25%
// This is based on the assumption that lower counters are older
const target_evict_count = self.max_tracked_nonces / 4;
var total_evicted: usize = 0;
var max_evicted_counter: u32 = 0;
// CRIT-NEW-18 FIX: Loop until we've evicted enough entries
// Each iteration evicts up to BATCH_SIZE entries to avoid stack overflow
const BATCH_SIZE: usize = 256;
while (total_evicted < target_evict_count and self.seen_nonces.count() > 0) {
// Find minimum counter value to use as eviction threshold
var min_counter: u32 = std.math.maxInt(u32);
var iter1 = self.seen_nonces.keyIterator();
while (iter1.next()) |key_ptr| {
const counter: u32 = @intCast((key_ptr.* >> 32) & 0xFFFFFFFF);
if (counter < min_counter) {
min_counter = counter;
}
}
// Calculate threshold for this batch
const remaining_to_evict = target_evict_count - total_evicted;
const batch_evict = @min(remaining_to_evict, BATCH_SIZE);
const evict_range: u32 = @intCast(@min(batch_evict, std.math.maxInt(u32)));
const eviction_threshold = std.math.add(u32, min_counter, evict_range) catch std.math.maxInt(u32);
// Collect keys to evict in this batch
var keys_to_evict: [BATCH_SIZE]u64 = undefined;
var evict_idx: usize = 0;
var iter2 = self.seen_nonces.keyIterator();
while (iter2.next()) |key_ptr| {
if (evict_idx >= BATCH_SIZE) break;
const counter: u32 = @intCast((key_ptr.* >> 32) & 0xFFFFFFFF);
if (counter < eviction_threshold) {
keys_to_evict[evict_idx] = key_ptr.*;
evict_idx += 1;
if (counter > max_evicted_counter) {
max_evicted_counter = counter;
}
}
}
// No more entries to evict in this threshold - break to prevent infinite loop
if (evict_idx == 0) break;
// Evict collected keys
for (0..evict_idx) |idx| {
_ = self.seen_nonces.remove(keys_to_evict[idx]);
}
total_evicted += evict_idx;
}
// SEC-H4 FIX: Update min_allowed_counter to prevent replay of evicted nonces
// Any nonce with counter <= max_evicted_counter will be rejected
if (total_evicted > 0) {
// Add 1 because we want to reject counters UP TO AND INCLUDING the max evicted
self.min_allowed_counter = @max(self.min_allowed_counter, max_evicted_counter + 1);
std.log.debug("SEC-H4: Evicted {d} old nonces, min_allowed_counter now {d}", .{ total_evicted, self.min_allowed_counter });
}
// Keep a window of 3/4 of max_tracked_nonces below highest_counter
const window: u32 = @intCast(@min(self.max_tracked_nonces * 3 / 4, std.math.maxInt(u32)));
const new_min = self.highest_counter -| window;
self.min_allowed_counter = @max(self.min_allowed_counter, new_min);
self.seen_nonces.clearRetainingCapacity();
std.log.debug("Nonce tracker eviction: min_allowed_counter now {d}", .{self.min_allowed_counter});
}
try self.seen_nonces.put(nonce_key, {});
}
@@ -456,44 +408,36 @@ pub const EncryptionKey = struct {
/// Returns a 12-byte nonce combining generation + counter + random
/// Returns error if nonce space is exhausted and key rotation is required
pub fn getNextNonce(self: *EncryptionKey) ![12]u8 {
// CRITICAL: Check for nonce exhaustion BEFORE using the counter
// This prevents nonce wraparound which would catastrophically break security
// CRIT-NEW-16 FIX: Use atomic load
const current_counter = self.nonce_counter.load(.acquire);
// Atomically claim a unique counter value. fetchAdd guarantees no two
// threads get the same counter regardless of memory ordering.
// Using .monotonic since we only need atomicity, not ordering —
// the nonce value is used locally and the encryption call provides
// its own barriers.
const current_counter = self.nonce_counter.fetchAdd(1, .monotonic);
if (current_counter >= NONCE_ROTATION_THRESHOLD) {
self.needs_rotation = true;
// SECURITY FIX: Zeroize key material on nonce exhaustion
self.onNonceExhaustion();
return crypto.CryptoError.NonceExhaustion;
}
var nonce: [12]u8 = undefined;
// MED-2 FIX: Validate generation fits in u32 before truncation
// This should never happen in practice (would require 2^32+ key rotations)
// but we check for defense in depth
if (self.generation > std.math.maxInt(u32)) {
std.log.err("MED-2 SECURITY: Generation counter overflow - nonce uniqueness compromised!", .{});
std.log.err("SECURITY: Generation counter overflow - nonce uniqueness compromised!", .{});
self.needs_rotation = true;
return crypto.CryptoError.NonceExhaustion;
}
// First 4 bytes: generation (prevents nonce reuse across key rotations)
// SAFETY: Validated above that generation fits in u32
std.mem.writeInt(u32, nonce[0..4], @as(u32, @intCast(self.generation)), .little);
// Next 4 bytes: counter (prevents nonce reuse within key generation)
// SAFETY: nonce_counter is checked against NONCE_ROTATION_THRESHOLD (< u32 max)
// CRIT-NEW-16 FIX: Use value already loaded atomically above
// Next 4 bytes: counter (unique per fetchAdd, fits in u32 due to threshold)
std.mem.writeInt(u32, nonce[4..8], @as(u32, @intCast(current_counter)), .little);
// Last 4 bytes: random (additional entropy)
std.crypto.random.bytes(nonce[8..12]);
// Increment counter atomically
// CRIT-NEW-16 FIX: Use atomic fetchAdd for thread safety
_ = self.nonce_counter.fetchAdd(1, .release);
return nonce;
}
@@ -828,13 +772,16 @@ pub const EncryptionManager = struct {
var new_hmac_key: [32]u8 = undefined;
// Derive encryption key
const enc_prk = std.crypto.kdf.hkdf.HkdfSha256.extract(&salt_buf, &current.key);
var enc_prk = std.crypto.kdf.hkdf.HkdfSha256.extract(&salt_buf, &current.key);
std.crypto.kdf.hkdf.HkdfSha256.expand(&new_enc_key_bytes, enc_info, enc_prk);
// SECURITY: Also derive new HMAC key from the same root key
// This ensures HMAC and encryption keys are rotated together
std.crypto.kdf.hkdf.HkdfSha256.expand(&new_hmac_key, hmac_info, enc_prk);
// Zeroize PRK after use
crypto.secureZero([32]u8, &enc_prk);
// Create new encryption key with previous key stored for in-flight messages
// CRY-M2 FIX: Use setPreviousKey to track timestamp for expiry
var new_enc_key = EncryptionKey.init(new_enc_key_bytes, new_generation);

View File

@@ -1,5 +1,6 @@
//! Message handler framework
const std = @import("std");
const core = @import("core");
const protocol = @import("protocol.zig");
const message = @import("message.zig");
const serializer = @import("serializer.zig");
@@ -1024,6 +1025,8 @@ pub const HandlerRegistry = struct {
self.context.source_peer_id = source_id;
defer self.context.source_peer_id = null;
const msg_type = msg.getType();
// SECURITY: Check for replay attack (compile-time enforced, cannot be disabled)
if (comptime REQUIRE_REPLAY_PROTECTION) {
self.replay_protector.checkMessage(
@@ -1032,6 +1035,7 @@ pub const HandlerRegistry = struct {
nonce,
sequence,
source_id,
@intFromEnum(msg_type),
) catch |err| {
// Replay detected - reject message and record failure
self.context.metrics.recordMessageFailed();
@@ -1049,8 +1053,6 @@ pub const HandlerRegistry = struct {
};
}
const msg_type = msg.getType();
// FIX: Copy handlers while holding lock, then release lock before calling handlers
// This prevents deadlock if a handler tries to register/unregister handlers
var handlers_copy: std.ArrayList(MessageHandler) = .{};
@@ -1301,8 +1303,6 @@ pub const DiscoveryHandler = struct {
// 1. Add known nodes to peer list
// MEM-M1 FIX: Use type-safe getter instead of direct cast
if (context.getPeerManager() catch null) |pm| {
const core = @import("core");
for (msg.known_nodes) |_| {
// Create address from node ID (simplified - in production would use proper addressing)
var addr = core.Address.init();
@@ -1377,7 +1377,7 @@ pub const DiscoveryHandler = struct {
if (context.getPeerManager() catch null) |pm| {
const network = @import("network");
const peer_id = network.PeerId{ .bytes = source_id };
const core = @import("core");
// Check if peer exists (getPeerById returns a copy for thread safety)
if (pm.getPeerById(peer_id)) |_| {

View File

@@ -37,13 +37,15 @@ const MessageEntry = struct {
const PeerMessageKey = struct {
peer_id_prefix: [8]u8, // First 8 bytes of peer ID for compact storage
msg_id: u64,
msg_type: u8, // Distinguishes request/response with same request_id
pub fn init(peer_id: [32]u8, msg_id: u64) PeerMessageKey {
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]);
return .{
.peer_id_prefix = prefix,
.msg_id = msg_id,
.msg_type = msg_type,
};
}
};
@@ -208,6 +210,7 @@ pub const ReplayProtector = struct {
nonce: u64,
sequence: u64,
peer_id: [32]u8,
msg_type: u8,
) !void {
self.mutex.lock();
defer self.mutex.unlock();
@@ -239,8 +242,9 @@ pub const ReplayProtector = struct {
// 1. Validate timestamp
try self.validateTimestamp(timestamp, current_time);
// 2. Check for duplicate message ID (per-peer to avoid collisions)
if (try self.isReplay(peer_id, msg_id, timestamp, nonce)) {
// 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)) {
return ReplayError.DuplicateMessageId;
}
@@ -266,8 +270,8 @@ pub const ReplayProtector = struct {
try self.checkSequence(peer_id, sequence, current_time);
}
// 5. Record this message as seen (per-peer key)
const key = PeerMessageKey.init(peer_id, msg_id);
// 5. 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,
@@ -299,10 +303,10 @@ pub const ReplayProtector = struct {
}
/// Check if message ID was seen before (per-peer)
/// Uses PeerMessageKey to ensure message IDs are tracked per-peer,
/// avoiding collisions when different peers use the same sequence numbers
fn isReplay(self: *ReplayProtector, peer_id: [32]u8, msg_id: u64, timestamp: i64, nonce: u64) !bool {
const key = PeerMessageKey.init(peer_id, msg_id);
/// 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 {
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
@@ -580,7 +584,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);
const result = protector.checkMessage(1, old_timestamp, 1000, 0, peer_id, 0);
try std.testing.expectError(ReplayError.TimestampTooOld, result);
}
@@ -593,7 +597,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);
const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id, 0);
try std.testing.expectError(ReplayError.TimestampTooFarInFuture, result);
}
@@ -607,7 +611,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);
try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id, 0);
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 1), stats.tracked_messages);
@@ -621,10 +625,10 @@ 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);
try protector.checkMessage(42, current_time, 1000, 0, peer_id, 0);
// Duplicate message ID should fail
const result = protector.checkMessage(42, current_time, 1001, 0, peer_id);
const result = protector.checkMessage(42, current_time, 1001, 0, peer_id, 0);
try std.testing.expectError(ReplayError.DuplicateMessageId, result);
}
@@ -636,10 +640,10 @@ test "duplicate nonce detection" {
const peer_id = [_]u8{1} ** 32;
// First message with nonce 5000
try protector.checkMessage(1, current_time, 5000, 0, peer_id);
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);
const result = protector.checkMessage(2, current_time, 5000, 0, peer_id, 0);
try std.testing.expectError(ReplayError.DuplicateNonce, result);
}
@@ -651,9 +655,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);
try protector.checkMessage(2, current_time + 1, 1001, 2, peer_id);
try protector.checkMessage(3, current_time + 2, 1002, 3, peer_id);
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);
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 1), stats.tracked_peers);
@@ -667,10 +671,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);
try protector.checkMessage(2, current_time + 1, 2001, 2, peer_id);
try protector.checkMessage(3, current_time + 2, 2002, 5, peer_id);
try protector.checkMessage(4, current_time + 3, 2003, 3, peer_id);
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);
}
test "sequence number enforcement - reject duplicate sequence" {
@@ -681,10 +685,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);
try protector.checkMessage(2, current_time + 1, 3001, 2, peer_id);
try protector.checkMessage(1, current_time, 3000, 1, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 3001, 2, peer_id, 0);
const result = protector.checkMessage(3, current_time + 2, 3002, 2, peer_id);
const result = protector.checkMessage(3, current_time + 2, 3002, 2, peer_id, 0);
try std.testing.expectError(ReplayError.DuplicateMessageId, result);
}
@@ -696,9 +700,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);
try protector.checkMessage(1, current_time, 4000, 100, peer_id, 0);
const result = protector.checkMessage(2, current_time + 1, 4001, 1, peer_id);
const result = protector.checkMessage(2, current_time + 1, 4001, 1, peer_id, 0);
try std.testing.expectError(ReplayError.SequenceTooOld, result);
}
@@ -710,13 +714,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);
try protector.checkMessage(1, current_time, 5000, 10, peer_id, 0);
// Large jump (> window size)
try protector.checkMessage(2, current_time + 1, 5001, 200, peer_id);
try protector.checkMessage(2, current_time + 1, 5001, 200, peer_id, 0);
// Should accept because window was reset
try protector.checkMessage(3, current_time + 2, 5002, 201, peer_id);
try protector.checkMessage(3, current_time + 2, 5002, 201, peer_id, 0);
}
test "cleanup removes old entries" {
@@ -730,8 +734,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);
try protector.checkMessage(2, base_time, 6001, 2, peer_id);
try protector.checkMessage(1, base_time, 6000, 1, peer_id, 0);
try protector.checkMessage(2, base_time, 6001, 2, peer_id, 0);
var stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 2), stats.tracked_messages);
@@ -754,14 +758,14 @@ test "peer sequence reset" {
const peer_id = [_]u8{7} ** 32;
// Send some messages
try protector.checkMessage(1, current_time, 7000, 5, peer_id);
try protector.checkMessage(2, current_time + 1, 7001, 6, peer_id);
try protector.checkMessage(1, current_time, 7000, 5, peer_id, 0);
try protector.checkMessage(2, current_time + 1, 7001, 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);
try protector.checkMessage(3, current_time + 2, 7002, 1, peer_id, 0);
}
test "multiple peers tracked independently" {
@@ -773,10 +777,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);
try protector.checkMessage(2, current_time, 8001, 1, peer2);
try protector.checkMessage(3, current_time + 1, 8002, 2, peer1);
try protector.checkMessage(4, current_time + 1, 8003, 2, peer2);
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);
const stats = protector.getStats();
try std.testing.expectEqual(@as(usize, 2), stats.tracked_peers);