network reliability and security hardening. auto-cleanup expired backoff

entries, atomic file writes for key pinning, forward secrecy via
rekeying, peer eviction when at max connections, NAT-PMP source address
verification, UPnP response timeout
This commit is contained in:
2026-02-10 20:10:50 -03:00
parent b744ba5c09
commit bc4c49f724
7 changed files with 189 additions and 18 deletions

View File

@@ -50,6 +50,10 @@ pub const Error = error{
OutOfMemory,
};
/// Number of messages sent/received before automatic rekeying for forward secrecy.
/// Set to 0 to disable automatic rekeying.
pub const DEFAULT_REKEY_INTERVAL: u64 = 1000;
/// SecureConnection wraps a socket with Noise protocol encryption
pub const SecureConnection = struct {
/// Underlying socket
@@ -68,6 +72,12 @@ pub const SecureConnection = struct {
decrypt_buf: [MAX_MESSAGE_SIZE]u8,
/// Allocator for any dynamic allocations
allocator: mem.Allocator,
/// Messages sent since last outbound rekey
messages_sent_since_rekey: u64 = 0,
/// Messages received since last inbound rekey
messages_received_since_rekey: u64 = 0,
/// Rekey interval (0 = disabled)
rekey_interval: u64 = DEFAULT_REKEY_INTERVAL,
const Self = @This();
@@ -163,6 +173,8 @@ pub const SecureConnection = struct {
// Send encrypted payload
try self.sendRaw(self.encrypt_buf[0..encrypted_len]);
self.maybeRekeyOutbound();
return plaintext.len;
}
@@ -206,6 +218,8 @@ pub const SecureConnection = struct {
});
}
self.maybeRekeyOutbound();
return packet;
}
@@ -249,6 +263,8 @@ pub const SecureConnection = struct {
};
};
self.maybeRekeyInbound();
return plaintext;
}
@@ -282,6 +298,37 @@ pub const SecureConnection = struct {
return self.socket;
}
// =========================================================================
// Forward secrecy: automatic rekeying
// =========================================================================
/// Rekey outbound cipher after reaching the message threshold.
/// Both sides independently rekey their own send CipherState at the same
/// message count, so the corresponding receive CipherState on the other
/// side stays synchronized without explicit coordination (Noise spec §11.3).
fn maybeRekeyOutbound(self: *Self) void {
if (self.rekey_interval == 0) return;
self.messages_sent_since_rekey += 1;
if (self.messages_sent_since_rekey >= self.rekey_interval) {
if (self.transport) |*t| {
t.rekeyOutbound();
self.messages_sent_since_rekey = 0;
}
}
}
/// Rekey inbound cipher after reaching the message threshold.
fn maybeRekeyInbound(self: *Self) void {
if (self.rekey_interval == 0) return;
self.messages_received_since_rekey += 1;
if (self.messages_received_since_rekey >= self.rekey_interval) {
if (self.transport) |*t| {
t.rekeyInbound();
self.messages_received_since_rekey = 0;
}
}
}
// =========================================================================
// Private helpers for raw socket I/O during handshake
// =========================================================================